• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.AtomicInteger;
517 import java.util.function.BiFunction;
518 import java.util.function.Consumer;
519 
520 public class ActivityManagerService extends IActivityManager.Stub
521         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
522 
523     private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED =
524             "persist.sys.device_provisioned";
525 
526     static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
527     static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
528     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
529     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
530     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
531     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
532     static final String TAG_LRU = TAG + POSTFIX_LRU;
533     static final String TAG_MU = TAG + POSTFIX_MU;
534     static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
535     static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
536     private static final String TAG_POWER = TAG + POSTFIX_POWER;
537     static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
538     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
539     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
540     static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
541 
542     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
543     // here so that while the job scheduler can depend on AMS, the other way around
544     // need not be the case.
545     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
546 
547     private static final String INTENT_BUGREPORT_REQUESTED =
548             "com.android.internal.intent.action.BUGREPORT_REQUESTED";
549     private static final String SHELL_APP_PACKAGE = "com.android.shell";
550 
551     // The flags that are set for all calls we make to the package manager.
552     public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
553 
554     static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed";
555 
556     // Maximum number of receivers an app can register.
557     private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000;
558 
559     // How long we wait for a launched process to attach to the activity manager
560     // before we decide it's never going to come up for real.
561     static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
562 
563     // How long we wait for a launched process to complete its app startup before we ANR.
564     static final int BIND_APPLICATION_TIMEOUT = 20 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
565 
566     // How long we wait to kill an application zygote, after the last process using
567     // it has gone away.
568     static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000;
569 
570     // How long we wait for a launched process to attach to the activity manager
571     // before we decide it's never going to come up for real, when the process was
572     // started with a wrapper for instrumentation (such as Valgrind) because it
573     // could take much longer than usual.
574     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
575 
576     // How long we allow a receiver to run before giving up on it.
577     static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
578     static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
579 
580     public static final int MY_PID = myPid();
581 
582     static final String[] EMPTY_STRING_ARRAY = new String[0];
583 
584     // How many bytes to write into the dropbox log before truncating
585     static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024;
586     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
587     // as one line, but close enough for now.
588     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
589 
590     // Necessary ApplicationInfo flags to mark an app as persistent
591     static final int PERSISTENT_MASK =
592             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
593 
594     // Intent sent when remote bugreport collection has been completed
595     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
596             "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
597 
598     // If set, we will push process association information in to procstats.
599     static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true;
600 
601     // The minimum memory growth threshold (in KB) for low RAM devices.
602     private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB
603 
604     /**
605      * The number of binder proxies we need to have before we start warning and
606      * dumping debug info.
607      */
608     private static final int BINDER_PROXY_HIGH_WATERMARK = 6000;
609 
610     /**
611      * Low watermark that needs to be met before we consider dumping info again,
612      * after already hitting the high watermark.
613      */
614     private static final int BINDER_PROXY_LOW_WATERMARK = 5500;
615 
616     // Max character limit for a notification title. If the notification title is larger than this
617     // the notification will not be legible to the user.
618     private static final int MAX_BUGREPORT_TITLE_SIZE = 100;
619     private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150;
620 
621     OomAdjuster mOomAdjuster;
622 
623     static final String EXTRA_TITLE = "android.intent.extra.TITLE";
624     static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION";
625     static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE";
626     static final String EXTRA_BUGREPORT_NONCE = "android.intent.extra.BUGREPORT_NONCE";
627 
628     /**
629      * It is now required for apps to explicitly set either
630      * {@link android.content.Context#RECEIVER_EXPORTED} or
631      * {@link android.content.Context#RECEIVER_NOT_EXPORTED} when registering a receiver for an
632      * unprotected broadcast in code.
633      */
634     @ChangeId
635     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
636     private static final long DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED = 161145287L;
637 
638     /**
639      * Apps targeting Android U and above will need to export components in order to invoke them
640      * through implicit intents.
641      *
642      * If a component is not exported and invoked, it will be removed from the list of receivers.
643      * This applies specifically to activities and broadcasts.
644      */
645     @ChangeId
646     @Overridable
647     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.TIRAMISU)
648     public static final long IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS = 229362273;
649 
650     /**
651      * The maximum number of bytes that {@link #setProcessStateSummary} accepts.
652      *
653      * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])}
654      */
655     static final int MAX_STATE_DATA_SIZE = 128;
656 
657     /** All system services */
658     SystemServiceManager mSystemServiceManager;
659 
660     private Installer mInstaller;
661 
662     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
663 
664     @CompositeRWLock({"this", "mProcLock"})
665     final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
666 
667     public final IntentFirewall mIntentFirewall;
668 
669     public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler();
670 
671     /**
672      * The global lock for AMS, it's de-facto the ActivityManagerService object as of now.
673      */
674     final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this;
675 
676     /**
677      * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock}
678      * will be equivalent to the {@link #mGlobalLock}.
679      */
680     private static final boolean ENABLE_PROC_LOCK = true;
681 
682     /**
683      * The lock for process management.
684      *
685      * <p>
686      * This lock is widely used in conjunction with the {@link #mGlobalLock} at present,
687      * where it'll require any of the locks to read from a data class, and both of the locks
688      * to write into that data class.
689      *
690      * For the naming convention of function suffixes:
691      * <ul>
692      *    <li>-LOSP:    Locked with any Of global am Service or Process lock</li>
693      *    <li>-LSP:     Locked with both of global am Service and Process lock</li>
694      *    <li>-Locked:  Locked with global am service lock alone</li>
695      *    <li>-LPr:     Locked with Process lock alone</li>
696      * </ul>
697      * For the simplicity, the getters/setters of the fields in data classes usually don't end with
698      * the above suffixes even if they're guarded by the locks here.
699      * </p>
700      *
701      * <p>
702      * In terms of locking order, it should be right below to the {@link #mGlobalLock},
703      * and above everything else which used to be underneath the {@link #mGlobalLock}.
704      * As of today, the core components(services/providers/broadcasts) are still guarded by
705      * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock}
706      * while holding this lock.
707      * </p>
708      *
709      */
710     final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK
711             ? new ActivityManagerProcLock() : mGlobalLock;
712 
713     // Whether we should use SCHED_FIFO for UI and RenderThreads.
714     final boolean mUseFifoUiScheduling;
715 
716     // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
717     // For simplicity, since we statically declare the size of the array of BroadcastQueues,
718     // we still create this new offload queue, but never ever put anything on it.
719     final boolean mEnableOffloadQueue;
720 
721     /**
722      * Flag indicating if we should use {@link BroadcastQueueModernImpl} instead
723      * of the default {@link BroadcastQueueImpl}.
724      */
725     final boolean mEnableModernQueue;
726 
727     static final int BROADCAST_QUEUE_FG = 0;
728     static final int BROADCAST_QUEUE_BG = 1;
729     static final int BROADCAST_QUEUE_BG_OFFLOAD = 2;
730     static final int BROADCAST_QUEUE_FG_OFFLOAD = 3;
731 
732     @GuardedBy("this")
733     private final SparseArray<IUnsafeIntentStrictModeCallback>
734             mStrictModeCallbacks = new SparseArray<>();
735 
736     // Convenient for easy iteration over the queues. Foreground is first
737     // so that dispatch of foreground broadcasts gets precedence.
738     final BroadcastQueue[] mBroadcastQueues;
739 
740     @GuardedBy("this")
741     BroadcastStats mLastBroadcastStats;
742 
743     @GuardedBy("this")
744     BroadcastStats mCurBroadcastStats;
745 
746     TraceErrorLogger mTraceErrorLogger;
747 
broadcastQueueForIntent(Intent intent)748     BroadcastQueue broadcastQueueForIntent(Intent intent) {
749         return broadcastQueueForFlags(intent.getFlags(), intent);
750     }
751 
broadcastQueueForFlags(int flags)752     BroadcastQueue broadcastQueueForFlags(int flags) {
753         return broadcastQueueForFlags(flags, null);
754     }
755 
broadcastQueueForFlags(int flags, Object cookie)756     BroadcastQueue broadcastQueueForFlags(int flags, Object cookie) {
757         if (mEnableModernQueue) {
758             return mBroadcastQueues[0];
759         }
760 
761         if (isOnFgOffloadQueue(flags)) {
762             if (DEBUG_BROADCAST_BACKGROUND) {
763                 Slog.i(TAG_BROADCAST,
764                         "Broadcast intent " + cookie + " on foreground offload queue");
765             }
766             return mBroadcastQueues[BROADCAST_QUEUE_FG_OFFLOAD];
767         }
768 
769         if (isOnBgOffloadQueue(flags)) {
770             if (DEBUG_BROADCAST_BACKGROUND) {
771                 Slog.i(TAG_BROADCAST,
772                         "Broadcast intent " + cookie + " on background offload queue");
773             }
774             return mBroadcastQueues[BROADCAST_QUEUE_BG_OFFLOAD];
775         }
776 
777         final boolean isFg = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
778         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
779                 "Broadcast intent " + cookie + " on "
780                 + (isFg ? "foreground" : "background") + " queue");
781         return (isFg) ? mBroadcastQueues[BROADCAST_QUEUE_FG]
782                 : mBroadcastQueues[BROADCAST_QUEUE_BG];
783     }
784 
785     private volatile int mDeviceOwnerUid = INVALID_UID;
786 
787     /**
788      * Map userId to its companion app uids.
789      */
790     private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
791 
792     /**
793      * The profile owner UIDs.
794      */
795     private ArraySet<Integer> mProfileOwnerUids = null;
796 
797     final UserController mUserController;
798     @VisibleForTesting
799     public final PendingIntentController mPendingIntentController;
800 
801     final AppErrors mAppErrors;
802     final PackageWatchdog mPackageWatchdog;
803 
804     @GuardedBy("mDeliveryGroupPolicyIgnoredActions")
805     private final ArraySet<String> mDeliveryGroupPolicyIgnoredActions = new ArraySet();
806 
807     /**
808      * Uids of apps with current active camera sessions.  Access synchronized on
809      * the IntArray instance itself, and no other locks must be acquired while that
810      * one is held.
811      */
812     @GuardedBy("mActiveCameraUids")
813     final IntArray mActiveCameraUids = new IntArray(4);
814 
815     /**
816      * Helper class which strips out priority and proto arguments then calls the dump function with
817      * the appropriate arguments. If priority arguments are omitted, function calls the legacy
818      * dump command.
819      * If priority arguments are omitted all sections are dumped, otherwise sections are dumped
820      * according to their priority.
821      */
822     private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
823         @Override
824         public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
825                 boolean asProto) {
826             if (asProto) return;
827             doDump(fd, pw, new String[]{"activities"}, asProto);
828             doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
829         }
830 
831         @Override
832         public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
833             doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto);
834         }
835 
836         @Override
837         public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
838             doDump(fd, pw, args, asProto);
839         }
840     };
841 
842     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
843             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
844 
boostPriorityForLockedSection()845     static void boostPriorityForLockedSection() {
846         sThreadPriorityBooster.boost();
847     }
848 
resetPriorityAfterLockedSection()849     static void resetPriorityAfterLockedSection() {
850         sThreadPriorityBooster.reset();
851     }
852 
853     private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster(
854             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC);
855 
boostPriorityForProcLockedSection()856     static void boostPriorityForProcLockedSection() {
857         if (ENABLE_PROC_LOCK) {
858             sProcThreadPriorityBooster.boost();
859         } else {
860             sThreadPriorityBooster.boost();
861         }
862     }
863 
resetPriorityAfterProcLockedSection()864     static void resetPriorityAfterProcLockedSection() {
865         if (ENABLE_PROC_LOCK) {
866             sProcThreadPriorityBooster.reset();
867         } else {
868             sThreadPriorityBooster.reset();
869         }
870     }
871 
872     /**
873      * Process management.
874      */
875     final ProcessList mProcessList;
876 
877     /**
878      * The list of phantom processes.
879      * @see PhantomProcessRecord
880      */
881     final PhantomProcessList mPhantomProcessList;
882 
883     /**
884      * Tracking long-term execution of processes to look for abuse and other
885      * bad app behavior.
886      */
887     final ProcessStatsService mProcessStats;
888 
889     /**
890      * Non-persistent appId allowlist for background restrictions
891      */
892     @CompositeRWLock({"this", "mProcLock"})
893     private int[] mBackgroundAppIdAllowlist = new int[] {
894             BLUETOOTH_UID
895     };
896 
897     /**
898      * Broadcast actions that will always be deliverable to unlaunched/background apps
899      */
900     @GuardedBy("this")
901     private ArraySet<String> mBackgroundLaunchBroadcasts;
902 
903     /**
904      * When an app has restrictions on the other apps that can have associations with it,
905      * it appears here with a set of the allowed apps and also track debuggability of the app.
906      */
907     @GuardedBy("this")
908     private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations;
909 
910     @GuardedBy("this")
911     final ComponentAliasResolver mComponentAliasResolver;
912 
913     /**
914      * Tracks association information for a particular package along with debuggability.
915      * <p> Associations for a package A are allowed to package B if B is part of the
916      *     allowed associations for A or if A is debuggable.
917      */
918     private final class PackageAssociationInfo {
919         private final String mSourcePackage;
920         private final ArraySet<String> mAllowedPackageAssociations;
921         private boolean mIsDebuggable;
922 
PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)923         PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages,
924                 boolean isDebuggable) {
925             mSourcePackage = sourcePackage;
926             mAllowedPackageAssociations = allowedPackages;
927             mIsDebuggable = isDebuggable;
928         }
929 
930         /**
931          * Returns true if {@code mSourcePackage} is allowed association with
932          * {@code targetPackage}.
933          */
isPackageAssociationAllowed(String targetPackage)934         boolean isPackageAssociationAllowed(String targetPackage) {
935             return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage);
936         }
937 
isDebuggable()938         boolean isDebuggable() {
939             return mIsDebuggable;
940         }
941 
setDebuggable(boolean isDebuggable)942         void setDebuggable(boolean isDebuggable) {
943             mIsDebuggable = isDebuggable;
944         }
945 
getAllowedPackageAssociations()946         ArraySet<String> getAllowedPackageAssociations() {
947             return mAllowedPackageAssociations;
948         }
949     }
950 
951     /**
952      * These are the currently running processes for which we have a ProcessInfo.
953      * Note: needs to be static since the permission checking call chain is static.  This
954      * all probably should be refactored into a separate permission checking object.
955      */
956     @GuardedBy("sActiveProcessInfoSelfLocked")
957     static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>();
958 
959     /**
960      * All of the processes we currently have running organized by pid.
961      * The keys are the pid running the application.
962      *
963      * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock!
964      */
965     final PidMap mPidsSelfLocked = new PidMap();
966     static final class PidMap {
967         private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>();
968 
get(int pid)969         ProcessRecord get(int pid) {
970             return mPidMap.get(pid);
971         }
972 
size()973         int size() {
974             return mPidMap.size();
975         }
976 
valueAt(int index)977         ProcessRecord valueAt(int index) {
978             return mPidMap.valueAt(index);
979         }
980 
keyAt(int index)981         int keyAt(int index) {
982             return mPidMap.keyAt(index);
983         }
984 
indexOfKey(int key)985         int indexOfKey(int key) {
986             return mPidMap.indexOfKey(key);
987         }
988 
doAddInternal(int pid, ProcessRecord app)989         void doAddInternal(int pid, ProcessRecord app) {
990             mPidMap.put(pid, app);
991         }
992 
doRemoveInternal(int pid, ProcessRecord app)993         boolean doRemoveInternal(int pid, ProcessRecord app) {
994             final ProcessRecord existingApp = mPidMap.get(pid);
995             if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) {
996                 mPidMap.remove(pid);
997                 return true;
998             }
999             return false;
1000         }
1001     }
1002 
1003     private final PendingStartActivityUids mPendingStartActivityUids;
1004 
1005     /**
1006      * Puts the process record in the map.
1007      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
1008      * method.
1009      */
1010     @GuardedBy("this")
addPidLocked(ProcessRecord app)1011     void addPidLocked(ProcessRecord app) {
1012         final int pid = app.getPid();
1013         synchronized (mPidsSelfLocked) {
1014             mPidsSelfLocked.doAddInternal(pid, app);
1015         }
1016         synchronized (sActiveProcessInfoSelfLocked) {
1017             if (app.processInfo != null) {
1018                 sActiveProcessInfoSelfLocked.put(pid, app.processInfo);
1019             } else {
1020                 sActiveProcessInfoSelfLocked.remove(pid);
1021             }
1022         }
1023         mAtmInternal.onProcessMapped(pid, app.getWindowProcessController());
1024     }
1025 
1026     /**
1027      * Removes the process record from the map.
1028      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
1029      * method.
1030      */
1031     @GuardedBy("this")
removePidLocked(int pid, ProcessRecord app)1032     boolean removePidLocked(int pid, ProcessRecord app) {
1033         final boolean removed;
1034         synchronized (mPidsSelfLocked) {
1035             removed = mPidsSelfLocked.doRemoveInternal(pid, app);
1036         }
1037         if (removed) {
1038             synchronized (sActiveProcessInfoSelfLocked) {
1039                 sActiveProcessInfoSelfLocked.remove(pid);
1040             }
1041             mAtmInternal.onProcessUnMapped(pid);
1042         }
1043         return removed;
1044     }
1045 
1046     /**
1047      * All of the processes that have been forced to be important.  The key
1048      * is the pid of the caller who requested it (we hold a death
1049      * link on it).
1050      */
1051     abstract class ImportanceToken implements IBinder.DeathRecipient {
1052         final int pid;
1053         final IBinder token;
1054         final String reason;
1055 
ImportanceToken(int _pid, IBinder _token, String _reason)1056         ImportanceToken(int _pid, IBinder _token, String _reason) {
1057             pid = _pid;
1058             token = _token;
1059             reason = _reason;
1060         }
1061 
1062         @Override
toString()1063         public String toString() {
1064             return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
1065                     + " " + reason + " " + pid + " " + token + " }";
1066         }
1067 
dumpDebug(ProtoOutputStream proto, long fieldId)1068         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1069             final long pToken = proto.start(fieldId);
1070             proto.write(ImportanceTokenProto.PID, pid);
1071             if (token != null) {
1072                 proto.write(ImportanceTokenProto.TOKEN, token.toString());
1073             }
1074             proto.write(ImportanceTokenProto.REASON, reason);
1075             proto.end(pToken);
1076         }
1077     }
1078     @GuardedBy("this")
1079     final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
1080 
1081     /**
1082      * List of records for processes that someone had tried to start before the
1083      * system was ready.  We don't start them at that point, but ensure they
1084      * are started by the time booting is complete.
1085      */
1086     @GuardedBy("this")
1087     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
1088 
1089     /**
1090      * List of persistent applications that are in the process
1091      * of being started.
1092      */
1093     @GuardedBy("this")
1094     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
1095 
1096     private final ActivityMetricsLaunchObserver mActivityLaunchObserver =
1097             new ActivityMetricsLaunchObserver() {
1098         @Override
1099         public void onActivityLaunched(long id, ComponentName name, int temperature) {
1100             mAppProfiler.onActivityLaunched();
1101         }
1102     };
1103 
1104     private volatile boolean mBinderTransactionTrackingEnabled = false;
1105 
1106     /**
1107      * Fingerprints (hashCode()) of stack traces that we've
1108      * already logged DropBox entries for.  Guarded by itself.  If
1109      * something (rogue user app) forces this over
1110      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1111      */
1112     @GuardedBy("mAlreadyLoggedViolatedStacks")
1113     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1114     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1115 
1116     /**
1117      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
1118      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
1119      */
1120     @GuardedBy("this")
1121     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
1122 
1123     /**
1124      * Resolver for broadcast intents to registered receivers.
1125      * Holds BroadcastFilter (subclass of IntentFilter).
1126      */
1127     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1128             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1129         @Override
1130         protected boolean allowFilterResult(
1131                 BroadcastFilter filter, List<BroadcastFilter> dest) {
1132             IBinder target = filter.receiverList.receiver.asBinder();
1133             for (int i = dest.size() - 1; i >= 0; i--) {
1134                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1135                     return false;
1136                 }
1137             }
1138             return true;
1139         }
1140 
1141         @Override
1142         protected BroadcastFilter newResult(@NonNull Computer computer, BroadcastFilter filter,
1143                 int match, int userId, long customFlags) {
1144             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
1145                     || userId == filter.owningUserId) {
1146                 return super.newResult(computer, filter, match, userId, customFlags);
1147             }
1148             return null;
1149         }
1150 
1151         @Override
1152         protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) {
1153             return input;
1154         }
1155 
1156         @Override
1157         protected BroadcastFilter[] newArray(int size) {
1158             return new BroadcastFilter[size];
1159         }
1160 
1161         @Override
1162         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
1163             return packageName.equals(filter.packageName);
1164         }
1165     };
1166 
1167     /**
1168      * State of all active sticky broadcasts per user.  Keys are the action of the
1169      * sticky Intent, values are an ArrayList of all broadcasted intents with
1170      * that action (which should usually be one).  The SparseArray is keyed
1171      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1172      * for stickies that are sent to all users.
1173      */
1174     @GuardedBy("this")
1175     final SparseArray<ArrayMap<String, ArrayList<StickyBroadcast>>> mStickyBroadcasts =
1176             new SparseArray<>();
1177 
1178     @VisibleForTesting
1179     static final class StickyBroadcast {
1180         public Intent intent;
1181         public boolean deferUntilActive;
1182         public int originalCallingUid;
1183         /** The snapshot process state of the app who sent this broadcast */
1184         public int originalCallingAppProcessState;
1185 
create(Intent intent, boolean deferUntilActive, int originalCallingUid, int originalCallingAppProcessState)1186         public static StickyBroadcast create(Intent intent, boolean deferUntilActive,
1187                 int originalCallingUid, int originalCallingAppProcessState) {
1188             final StickyBroadcast b = new StickyBroadcast();
1189             b.intent = intent;
1190             b.deferUntilActive = deferUntilActive;
1191             b.originalCallingUid = originalCallingUid;
1192             b.originalCallingAppProcessState = originalCallingAppProcessState;
1193             return b;
1194         }
1195 
1196         @Override
toString()1197         public String toString() {
1198             return "{intent=" + intent + ", defer=" + deferUntilActive + ", originalCallingUid="
1199                     + originalCallingUid + ", originalCallingAppProcessState="
1200                     + originalCallingAppProcessState + "}";
1201         }
1202     }
1203 
1204     final ActiveServices mServices;
1205 
1206     final static class Association {
1207         final int mSourceUid;
1208         final String mSourceProcess;
1209         final int mTargetUid;
1210         final ComponentName mTargetComponent;
1211         final String mTargetProcess;
1212 
1213         int mCount;
1214         long mTime;
1215 
1216         int mNesting;
1217         long mStartTime;
1218 
1219         // states of the source process when the bind occurred.
1220         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1221         long mLastStateUptime;
1222         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1223                 - ActivityManager.MIN_PROCESS_STATE+1];
1224 
Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1225         Association(int sourceUid, String sourceProcess, int targetUid,
1226                 ComponentName targetComponent, String targetProcess) {
1227             mSourceUid = sourceUid;
1228             mSourceProcess = sourceProcess;
1229             mTargetUid = targetUid;
1230             mTargetComponent = targetComponent;
1231             mTargetProcess = targetProcess;
1232         }
1233     }
1234 
1235     /**
1236      * When service association tracking is enabled, this is all of the associations we
1237      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
1238      * -> association data.
1239      */
1240     @GuardedBy("this")
1241     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1242             mAssociations = new SparseArray<>();
1243     boolean mTrackingAssociations;
1244 
1245     /**
1246      * Backup/restore process management
1247      */
1248     @GuardedBy("this")
1249     final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>();
1250 
1251     final ContentProviderHelper mCpHelper;
1252 
1253     CoreSettingsObserver mCoreSettingsObserver;
1254 
1255     /**
1256      * All information we have collected about the runtime performance of
1257      * any user id that can impact battery performance.
1258      */
1259     final BatteryStatsService mBatteryStatsService;
1260 
1261     /**
1262      * Information about component usage
1263      */
1264     volatile UsageStatsManagerInternal mUsageStatsService;
1265 
1266     /**
1267      * Access to DeviceIdleController service.
1268      */
1269     DeviceIdleInternal mLocalDeviceIdleController;
1270 
1271     /**
1272      * Power-save allowlisted app-ids (not including except-idle-allowlisted ones).
1273      */
1274     @CompositeRWLock({"this", "mProcLock"})
1275     int[] mDeviceIdleAllowlist = new int[0];
1276 
1277     /**
1278      * Power-save allowlisted app-ids (including except-idle-allowlisted ones).
1279      */
1280     @CompositeRWLock({"this", "mProcLock"})
1281     int[] mDeviceIdleExceptIdleAllowlist = new int[0];
1282 
1283     /**
1284      * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1285      */
1286     @CompositeRWLock({"this", "mProcLock"})
1287     int[] mDeviceIdleTempAllowlist = new int[0];
1288 
1289     static final class PendingTempAllowlist {
1290         final int targetUid;
1291         final long duration;
1292         final String tag;
1293         final int type;
1294         final @ReasonCode int reasonCode;
1295         final int callingUid;
1296 
PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1297         PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag,
1298                 int type, int callingUid) {
1299             this.targetUid = targetUid;
1300             this.duration = duration;
1301             this.tag = tag;
1302             this.type = type;
1303             this.reasonCode = reasonCode;
1304             this.callingUid = callingUid;
1305         }
1306 
dumpDebug(ProtoOutputStream proto, long fieldId)1307         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1308             final long token = proto.start(fieldId);
1309             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID,
1310                     targetUid);
1311             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS,
1312                     duration);
1313             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag);
1314             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type);
1315             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE,
1316                     reasonCode);
1317             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID,
1318                     callingUid);
1319             proto.end(token);
1320         }
1321     }
1322 
1323     @CompositeRWLock({"this", "mProcLock"})
1324     final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this);
1325 
1326     public static final class FgsTempAllowListItem {
1327         final long mDuration;
1328         final @PowerExemptionManager.ReasonCode int mReasonCode;
1329         final String mReason;
1330         final int mCallingUid;
1331 
FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1332         FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode,
1333                 String reason, int callingUid) {
1334             mDuration = duration;
1335             mReasonCode = reasonCode;
1336             mReason = reason;
1337             mCallingUid = callingUid;
1338         }
1339 
dump(PrintWriter pw)1340         void dump(PrintWriter pw) {
1341             pw.print(" duration=" + mDuration +
1342                     " callingUid=" + UserHandle.formatUid(mCallingUid) +
1343                     " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) +
1344                     " reason=" + mReason);
1345         }
1346     }
1347 
1348     /**
1349      * The temp-allowlist that is allowed to start FGS from background.
1350      */
1351     @CompositeRWLock({"this", "mProcLock"})
1352     final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList =
1353             new FgsTempAllowList();
1354 
1355     static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem(
1356             Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID);
1357 
1358     /*
1359      * List of uids that are allowed to have while-in-use permission when FGS is started from
1360      * background.
1361      */
1362     private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList =
1363             new FgsTempAllowList();
1364 
1365     /**
1366      * Information about and control over application operations
1367      */
1368     final AppOpsService mAppOpsService;
1369     private AppOpsManager mAppOpsManager;
1370 
1371     /**
1372      * List of initialization arguments to pass to all processes when binding applications to them.
1373      * For example, references to the commonly used services.
1374      */
1375     ArrayMap<String, IBinder> mAppBindArgs;
1376     ArrayMap<String, IBinder> mIsolatedAppBindArgs;
1377 
1378     volatile boolean mProcessesReady = false;
1379     volatile boolean mSystemReady = false;
1380     volatile boolean mOnBattery = false;
1381     final int mFactoryTest;
1382     volatile boolean mBooting = false;
1383 
1384     @GuardedBy("this") boolean mCallFinishBooting = false;
1385     @GuardedBy("this") boolean mBootAnimationComplete = false;
1386 
1387     final Context mContext;
1388 
1389     /**
1390      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1391      * change at runtime. Use mContext for non-UI purposes.
1392      */
1393     final Context mUiContext;
1394 
1395     /**
1396      * Last time (in uptime) at which we checked for power usage.
1397      */
1398     @GuardedBy("mProcLock")
1399     long mLastPowerCheckUptime;
1400 
1401     /**
1402      * For some direct access we need to power manager.
1403      */
1404     PowerManagerInternal mLocalPowerManager;
1405 
1406     /**
1407      * State of external calls telling us if the device is awake or asleep.
1408      */
1409     AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE);
1410 
1411     /**
1412      * The uptime of the last time we performed idle maintenance.
1413      */
1414     @GuardedBy("mProcLock")
1415     long mLastIdleTime = SystemClock.uptimeMillis();
1416 
1417     /**
1418      * For reporting to battery stats the current top application.
1419      *
1420      * <p>It has its own lock to avoid from the need of double locking if using the global
1421      * ActivityManagerService lock and proc lock to guard it.</p>
1422      */
1423     @GuardedBy("mCurResumedAppLock")
1424     private String mCurResumedPackage = null;
1425 
1426     @GuardedBy("mCurResumedAppLock")
1427     private int mCurResumedUid = -1;
1428 
1429     /**
1430      * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}.
1431      */
1432     private final Object mCurResumedAppLock = new Object();
1433 
1434     /**
1435      * For reporting to battery stats the apps currently running foreground
1436      * service.  The ProcessMap is package/uid tuples; each of these contain
1437      * an array of the currently foreground processes.
1438      */
1439     @GuardedBy("this")
1440     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1441             = new ProcessMap<ArrayList<ProcessRecord>>();
1442 
1443     /**
1444      * The list of foreground service state change listeners.
1445      */
1446     @GuardedBy("this")
1447     final ArrayList<ForegroundServiceStateListener> mForegroundServiceStateListeners =
1448             new ArrayList<>();
1449 
1450     /**
1451      * The list of broadcast event listeners.
1452      */
1453     final CopyOnWriteArrayList<BroadcastEventListener> mBroadcastEventListeners =
1454             new CopyOnWriteArrayList<>();
1455 
1456     /**
1457      * The list of bind service event listeners.
1458      */
1459     final CopyOnWriteArrayList<BindServiceEventListener> mBindServiceEventListeners =
1460             new CopyOnWriteArrayList<>();
1461 
1462     /**
1463      * Set if the systemServer made a call to enterSafeMode.
1464      */
1465     @GuardedBy("this")
1466     boolean mSafeMode;
1467 
1468     @GuardedBy("this")
1469     private String mDebugApp = null;
1470 
1471     @GuardedBy("this")
1472     private boolean mWaitForDebugger = false;
1473 
1474     @GuardedBy("this")
1475     private boolean mSuspendUponWait = false;
1476 
1477     @GuardedBy("this")
1478     private boolean mDebugTransient = false;
1479 
1480     @GuardedBy("this")
1481     private String mOrigDebugApp = null;
1482 
1483     @GuardedBy("this")
1484     private boolean mOrigWaitForDebugger = false;
1485 
1486     @GuardedBy("this")
1487     boolean mAlwaysFinishActivities = false;
1488 
1489     @GuardedBy("mProcLock")
1490     private String mTrackAllocationApp = null;
1491 
1492     @GuardedBy("this")
1493     String mNativeDebuggingApp = null;
1494 
1495     final Injector mInjector;
1496 
1497     static final class ProcessChangeItem {
1498         static final int CHANGE_ACTIVITIES = 1<<0;
1499         static final int CHANGE_FOREGROUND_SERVICES = 1<<1;
1500         int changes;
1501         int uid;
1502         int pid;
1503         int processState;
1504         boolean foregroundActivities;
1505         int foregroundServiceTypes;
1506     }
1507 
1508     @GuardedBy("mOomAdjObserverLock")
1509     OomAdjObserver mCurOomAdjObserver;
1510 
1511     @GuardedBy("mOomAdjObserverLock")
1512     int mCurOomAdjUid;
1513 
1514     /**
1515      * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}.
1516      */
1517     final Object mOomAdjObserverLock = new Object();
1518 
1519     interface OomAdjObserver {
onOomAdjMessage(String msg)1520         void onOomAdjMessage(String msg);
1521     }
1522 
1523     final AnrHelper mAnrHelper = new AnrHelper(this);
1524 
1525     /** Set to true after the system has finished booting. */
1526     volatile boolean mBooted = false;
1527 
1528     /**
1529      * Current boot phase.
1530      */
1531     int mBootPhase;
1532 
1533     volatile boolean mDeterministicUidIdle = false;
1534 
1535     @VisibleForTesting
1536     public WindowManagerService mWindowManager;
1537     WindowManagerInternal mWmInternal;
1538     @VisibleForTesting
1539     public ActivityTaskManagerService mActivityTaskManager;
1540     @VisibleForTesting
1541     public ActivityTaskManagerInternal mAtmInternal;
1542     UriGrantsManagerInternal mUgmInternal;
1543     @VisibleForTesting
1544     public final ActivityManagerInternal mInternal;
1545     final ActivityThread mSystemThread;
1546 
1547     final UidObserverController mUidObserverController;
1548     private volatile IUidObserver mNetworkPolicyUidObserver;
1549 
1550     @GuardedBy("mUidNetworkBlockedReasons")
1551     private final SparseIntArray mUidNetworkBlockedReasons = new SparseIntArray();
1552 
1553     final AppRestrictionController mAppRestrictionController;
1554 
1555     /**
1556      * The collection of the MediaProjection tokens per UID, for the apps that are allowed to
1557      * start FGS with the type "mediaProjection"; this permission is granted via the request over
1558      * the call to {@link android.media.project.MediaProjectionManager#createScreenCaptureIntent()}.
1559      *
1560      * <p>Note, the "token" here is actually an instance of
1561      * {@link android.media.projection.IMediaProjection}.</p>
1562      */
1563     @GuardedBy("mMediaProjectionTokenMap")
1564     private final SparseArray<ArraySet<IBinder>> mMediaProjectionTokenMap = new SparseArray();
1565 
1566     private final class AppDeathRecipient implements IBinder.DeathRecipient {
1567         final ProcessRecord mApp;
1568         final int mPid;
1569         final IApplicationThread mAppThread;
1570 
AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1571         AppDeathRecipient(ProcessRecord app, int pid,
1572                 IApplicationThread thread) {
1573             if (DEBUG_ALL) Slog.v(
1574                 TAG, "New death recipient " + this
1575                  + " for thread " + thread.asBinder());
1576             mApp = app;
1577             mPid = pid;
1578             mAppThread = thread;
1579         }
1580 
1581         @Override
binderDied()1582         public void binderDied() {
1583             if (DEBUG_ALL) Slog.v(
1584                 TAG, "Death received in " + this
1585                 + " for thread " + mAppThread.asBinder());
1586             synchronized(ActivityManagerService.this) {
1587                 appDiedLocked(mApp, mPid, mAppThread, true, null);
1588             }
1589         }
1590     }
1591 
1592     static final int SHOW_ERROR_UI_MSG = 1;
1593     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1594     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1595     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1596     static final int SERVICE_TIMEOUT_MSG = 12;
1597     static final int UPDATE_TIME_ZONE = 13;
1598     static final int PROC_START_TIMEOUT_MSG = 20;
1599     static final int KILL_APPLICATION_MSG = 22;
1600     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1601     static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
1602     static final int CLEAR_DNS_CACHE_MSG = 28;
1603     static final int UPDATE_HTTP_PROXY_MSG = 29;
1604     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1605     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1606     static final int REPORT_MEM_USAGE_MSG = 33;
1607     static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1608     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1609     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1610     static final int ABORT_DUMPHEAP_MSG = 51;
1611     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1612     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1613     static final int IDLE_UIDS_MSG = 58;
1614     static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1615     static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1616     static final int SERVICE_FOREGROUND_TIMEOUT_ANR_MSG = 67;
1617     static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68;
1618     static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1619     static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70;
1620     static final int KILL_APP_ZYGOTE_MSG = 71;
1621     static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72;
1622     static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73;
1623     static final int DISPATCH_SENDING_BROADCAST_EVENT = 74;
1624     static final int DISPATCH_BINDING_SERVICE_EVENT = 75;
1625     static final int SERVICE_SHORT_FGS_TIMEOUT_MSG = 76;
1626     static final int SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG = 77;
1627     static final int SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG = 78;
1628     static final int UPDATE_CACHED_APP_HIGH_WATERMARK = 79;
1629     static final int ADD_UID_TO_OBSERVER_MSG = 80;
1630     static final int REMOVE_UID_FROM_OBSERVER_MSG = 81;
1631     static final int BIND_APPLICATION_TIMEOUT_MSG = 82;
1632 
1633     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1634 
1635     /**
1636      * Flag whether the current user is a "monkey", i.e. whether
1637      * the UI is driven by a UI automation tool.
1638      */
1639     private volatile boolean mUserIsMonkey;
1640 
1641     @VisibleForTesting
1642     public final ServiceThread mHandlerThread;
1643     final MainHandler mHandler;
1644     final Handler mUiHandler;
1645     final ServiceThread mProcStartHandlerThread;
1646     final ProcStartHandler mProcStartHandler;
1647 
1648     ActivityManagerConstants mConstants;
1649 
1650     // Encapsulates the global setting "hidden_api_blacklist_exemptions"
1651     final HiddenApiSettings mHiddenApiBlacklist;
1652 
1653     private final PlatformCompat mPlatformCompat;
1654 
1655     PackageManagerInternal mPackageManagerInt;
1656     PermissionManagerServiceInternal mPermissionManagerInt;
1657     private TestUtilityService mTestUtilityService;
1658 
1659     /**
1660      * Whether to force background check on all apps (for battery saver) or not.
1661      */
1662     @CompositeRWLock({"this", "mProcLock"})
1663     private boolean mForceBackgroundCheck;
1664 
1665     private static String sTheRealBuildSerial = Build.UNKNOWN;
1666 
1667     @GuardedBy("mProcLock")
1668     private ParcelFileDescriptor[] mLifeMonitorFds;
1669 
1670     static final HostingRecord sNullHostingRecord =
1671             new HostingRecord(HostingRecord.HOSTING_TYPE_EMPTY);
1672     /**
1673      * Used to notify activity lifecycle events.
1674      */
1675     @Nullable volatile ContentCaptureManagerInternal mContentCaptureService;
1676 
1677     /*
1678      * The default duration for the binder heavy hitter auto sampler
1679      */
1680     private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L;
1681 
1682     /**
1683      * The default throttling duration for the binder heavy hitter auto sampler
1684      */
1685     private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L;
1686 
1687     /**
1688      * The last time when the binder heavy hitter auto sampler started.
1689      */
1690     @GuardedBy("mProcLock")
1691     private long mLastBinderHeavyHitterAutoSamplerStart = 0L;
1692 
1693     final AppProfiler mAppProfiler;
1694 
1695     private static final int INDEX_NATIVE_PSS = 0;
1696     private static final int INDEX_NATIVE_SWAP_PSS = 1;
1697     private static final int INDEX_NATIVE_RSS = 2;
1698     private static final int INDEX_DALVIK_PSS = 3;
1699     private static final int INDEX_DALVIK_SWAP_PSS = 4;
1700     private static final int INDEX_DALVIK_RSS = 5;
1701     private static final int INDEX_OTHER_PSS = 6;
1702     private static final int INDEX_OTHER_SWAP_PSS = 7;
1703     private static final int INDEX_OTHER_RSS = 8;
1704     private static final int INDEX_TOTAL_PSS = 9;
1705     private static final int INDEX_TOTAL_SWAP_PSS = 10;
1706     private static final int INDEX_TOTAL_RSS = 11;
1707     private static final int INDEX_TOTAL_NATIVE_PSS = 12;
1708     private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 13;
1709     private static final int INDEX_TOTAL_MEMTRACK_GL = 14;
1710     private static final int INDEX_LAST = 15;
1711 
1712     /**
1713      * Used to notify activity lifecycle events.
1714      */
1715     @Nullable
1716     volatile ActivityManagerInternal.VoiceInteractionManagerProvider
1717             mVoiceInteractionManagerProvider;
1718 
1719     final class UiHandler extends Handler {
UiHandler()1720         public UiHandler() {
1721             super(com.android.server.UiThread.get().getLooper(), null, true);
1722         }
1723 
1724         @Override
handleMessage(Message msg)1725         public void handleMessage(Message msg) {
1726             switch (msg.what) {
1727                 case SHOW_ERROR_UI_MSG: {
1728                     mAppErrors.handleShowAppErrorUi(msg);
1729                     ensureBootCompleted();
1730                 } break;
1731                 case SHOW_NOT_RESPONDING_UI_MSG: {
1732                     mAppErrors.handleShowAnrUi(msg);
1733                     ensureBootCompleted();
1734                 } break;
1735                 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1736                     HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1737                     synchronized (mProcLock) {
1738                         ProcessRecord proc = (ProcessRecord) data.get("app");
1739                         if (proc == null) {
1740                             Slog.e(TAG, "App not found when showing strict mode dialog.");
1741                             break;
1742                         }
1743                         if (proc.mErrorState.getDialogController().hasViolationDialogs()) {
1744                             Slog.e(TAG, "App already has strict mode dialog: " + proc);
1745                             return;
1746                         }
1747                         AppErrorResult res = (AppErrorResult) data.get("result");
1748                         if (mAtmInternal.showStrictModeViolationDialog()) {
1749                             proc.mErrorState.getDialogController().showViolationDialogs(res);
1750                         } else {
1751                             // The device is asleep, so just pretend that the user
1752                             // saw a crash dialog and hit "force quit".
1753                             res.set(0);
1754                         }
1755                     }
1756                     ensureBootCompleted();
1757                 } break;
1758                 case WAIT_FOR_DEBUGGER_UI_MSG: {
1759                     synchronized (mProcLock) {
1760                         ProcessRecord app = (ProcessRecord) msg.obj;
1761                         if (msg.arg1 != 0) {
1762                             if (!app.hasWaitedForDebugger()) {
1763                                 app.mErrorState.getDialogController().showDebugWaitingDialogs();
1764                                 app.setWaitedForDebugger(true);
1765                             }
1766                         } else {
1767                             app.mErrorState.getDialogController().clearWaitingDialog();
1768                         }
1769                     }
1770                 } break;
1771                 case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1772                     mProcessList.dispatchProcessesChanged();
1773                     break;
1774                 }
1775                 case DISPATCH_PROCESS_DIED_UI_MSG: {
1776                     if (false) { // DO NOT SUBMIT WITH TRUE
1777                         maybeTriggerWatchdog();
1778                     }
1779                     final int pid = msg.arg1;
1780                     final int uid = msg.arg2;
1781                     mProcessList.dispatchProcessDied(pid, uid);
1782                     break;
1783                 }
1784                 case DISPATCH_OOM_ADJ_OBSERVER_MSG: {
1785                     dispatchOomAdjObserver((String) msg.obj);
1786                 } break;
1787                 case PUSH_TEMP_ALLOWLIST_UI_MSG: {
1788                     pushTempAllowlist();
1789                 } break;
1790                 case ADD_UID_TO_OBSERVER_MSG: {
1791                     mUidObserverController.addUidToObserverImpl((IBinder) msg.obj, msg.arg1);
1792                 } break;
1793                 case REMOVE_UID_FROM_OBSERVER_MSG: {
1794                     mUidObserverController.removeUidFromObserverImpl((IBinder) msg.obj, msg.arg1);
1795                 } break;
1796             }
1797         }
1798     }
1799 
1800     final class MainHandler extends Handler {
MainHandler(Looper looper)1801         public MainHandler(Looper looper) {
1802             super(looper, null, true);
1803         }
1804 
1805         @Override
handleMessage(Message msg)1806         public void handleMessage(Message msg) {
1807             switch (msg.what) {
1808             case GC_BACKGROUND_PROCESSES_MSG: {
1809                 synchronized (ActivityManagerService.this) {
1810                     mAppProfiler.performAppGcsIfAppropriateLocked();
1811                 }
1812             } break;
1813             case SERVICE_TIMEOUT_MSG: {
1814                 mServices.serviceTimeout((ProcessRecord) msg.obj);
1815             } break;
1816             case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1817                 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj);
1818             } break;
1819             case SERVICE_FOREGROUND_TIMEOUT_ANR_MSG: {
1820                 SomeArgs args = (SomeArgs) msg.obj;
1821                 mServices.serviceForegroundTimeoutANR((ProcessRecord) args.arg1,
1822                         (TimeoutRecord) args.arg2);
1823                 args.recycle();
1824             } break;
1825             case SERVICE_FOREGROUND_CRASH_MSG: {
1826                 SomeArgs args = (SomeArgs) msg.obj;
1827                 mServices.serviceForegroundCrash(
1828                         (ProcessRecord) args.arg1,
1829                         (String) args.arg2,
1830                         (ComponentName) args.arg3);
1831                 args.recycle();
1832             } break;
1833             case UPDATE_TIME_ZONE: {
1834                 synchronized (mProcLock) {
1835                     mProcessList.forEachLruProcessesLOSP(false, app -> {
1836                         final IApplicationThread thread = app.getThread();
1837                         if (thread != null) {
1838                             try {
1839                                 thread.updateTimeZone();
1840                             } catch (RemoteException ex) {
1841                                 Slog.w(TAG, "Failed to update time zone for: "
1842                                         + app.info.processName);
1843                             }
1844                             }
1845                         });
1846                     }
1847             } break;
1848             case CLEAR_DNS_CACHE_MSG: {
1849                 synchronized (mProcLock) {
1850                     mProcessList.clearAllDnsCacheLOSP();
1851                 }
1852             } break;
1853             case UPDATE_HTTP_PROXY_MSG: {
1854                 mProcessList.setAllHttpProxy();
1855             } break;
1856             case PROC_START_TIMEOUT_MSG: {
1857                 ProcessRecord app = (ProcessRecord) msg.obj;
1858                 synchronized (ActivityManagerService.this) {
1859                     handleProcessStartOrKillTimeoutLocked(app, /* isKillTimeout */ false);
1860                 }
1861             } break;
1862             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1863                 ProcessRecord app = (ProcessRecord) msg.obj;
1864                 synchronized (ActivityManagerService.this) {
1865                     mCpHelper.processContentProviderPublishTimedOutLocked(app);
1866                 }
1867             } break;
1868             case KILL_APPLICATION_MSG: {
1869                 synchronized (ActivityManagerService.this) {
1870                     final int appId = msg.arg1;
1871                     final int userId = msg.arg2;
1872                     SomeArgs args = (SomeArgs) msg.obj;
1873                     String pkg = (String) args.arg1;
1874                     String reason = (String) args.arg2;
1875                     int exitInfoReason = (int) args.arg3;
1876                     args.recycle();
1877                     forceStopPackageLocked(pkg, appId, false, false, true, false,
1878                             false, userId, reason, exitInfoReason);
1879                 }
1880             } break;
1881 
1882                 case KILL_APP_ZYGOTE_MSG: {
1883                     synchronized (ActivityManagerService.this) {
1884                         final AppZygote appZygote = (AppZygote) msg.obj;
1885                         mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */);
1886                     }
1887                 } break;
1888             case CHECK_EXCESSIVE_POWER_USE_MSG: {
1889                 checkExcessivePowerUsage();
1890                 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
1891                 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
1892                 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
1893             } break;
1894             case REPORT_MEM_USAGE_MSG: {
1895                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj;
1896                 Thread thread = new Thread() {
1897                     @Override public void run() {
1898                         mAppProfiler.reportMemUsage(memInfos);
1899                     }
1900                 };
1901                 thread.start();
1902                 break;
1903             }
1904             case UPDATE_TIME_PREFERENCE_MSG: {
1905                 // The user's time format preference might have changed.
1906                 // For convenience we re-use the Intent extra values.
1907                 synchronized (mProcLock) {
1908                     mProcessList.updateAllTimePrefsLOSP(msg.arg1);
1909                 }
1910                 break;
1911             }
1912             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1913                 final int uid = msg.arg1;
1914                 final byte[] firstPacket = (byte[]) msg.obj;
1915 
1916                 synchronized (mProcLock) {
1917                     synchronized (mPidsSelfLocked) {
1918                         for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1919                             final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1920                             final IApplicationThread thread = p.getThread();
1921                             if (p.uid == uid && thread != null) {
1922                                 try {
1923                                     thread.notifyCleartextNetwork(firstPacket);
1924                                 } catch (RemoteException ignored) {
1925                                 }
1926                             }
1927                         }
1928                     }
1929                 }
1930             } break;
1931             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1932                 mAppProfiler.handlePostDumpHeapNotification();
1933             } break;
1934             case ABORT_DUMPHEAP_MSG: {
1935                 mAppProfiler.handleAbortDumpHeap((String) msg.obj);
1936             } break;
1937             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
1938                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
1939                 try {
1940                     connection.shutdown();
1941                 } catch (RemoteException e) {
1942                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
1943                 }
1944                 // Only a UiAutomation can set this flag and now that
1945                 // it is finished we make sure it is reset to its default.
1946                 mUserIsMonkey = false;
1947             } break;
1948             case IDLE_UIDS_MSG: {
1949                 idleUids();
1950             } break;
1951             case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
1952                 synchronized (mProcLock) {
1953                     mProcessList.handleAllTrustStorageUpdateLOSP();
1954                 }
1955             } break;
1956                 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: {
1957                     handleBinderHeavyHitterAutoSamplerTimeOut();
1958                 } break;
1959                 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: {
1960                     synchronized (ActivityManagerService.this) {
1961                         ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false);
1962                     }
1963                 } break;
1964                 case DISPATCH_SENDING_BROADCAST_EVENT: {
1965                     mBroadcastEventListeners.forEach(l ->
1966                             l.onSendingBroadcast((String) msg.obj, msg.arg1));
1967                 } break;
1968                 case DISPATCH_BINDING_SERVICE_EVENT: {
1969                     mBindServiceEventListeners.forEach(l ->
1970                             l.onBindingService((String) msg.obj, msg.arg1));
1971                 } break;
1972                 case SERVICE_SHORT_FGS_TIMEOUT_MSG: {
1973                     mServices.onShortFgsTimeout((ServiceRecord) msg.obj);
1974                 } break;
1975                 case SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG: {
1976                     mServices.onShortFgsProcstateTimeout((ServiceRecord) msg.obj);
1977                 } break;
1978                 case SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG: {
1979                     mServices.onShortFgsAnrTimeout((ServiceRecord) msg.obj);
1980                 } break;
1981                 case UPDATE_CACHED_APP_HIGH_WATERMARK: {
1982                     mAppProfiler.mCachedAppsWatermarkData.updateCachedAppsSnapshot((long) msg.obj);
1983                 } break;
1984                 case BIND_APPLICATION_TIMEOUT_MSG: {
1985                     ProcessRecord app = (ProcessRecord) msg.obj;
1986 
1987                     final String anrMessage;
1988                     synchronized (app) {
1989                         anrMessage = "Process " + app + " failed to complete startup";
1990                     }
1991 
1992                     mAnrHelper.appNotResponding(app, TimeoutRecord.forAppStart(anrMessage));
1993                 } break;
1994             }
1995         }
1996     }
1997 
1998 
setSystemProcess()1999     public void setSystemProcess() {
2000         try {
2001             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2002                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2003             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2004             ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2005                     DUMP_FLAG_PRIORITY_HIGH);
2006             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2007             ServiceManager.addService("dbinfo", new DbBinder(this));
2008             mAppProfiler.setCpuInfoService();
2009             ServiceManager.addService("permission", new PermissionController(this));
2010             ServiceManager.addService("processinfo", new ProcessInfoService(this));
2011             ServiceManager.addService("cacheinfo", new CacheBinder(this));
2012 
2013             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2014                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2015             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2016 
2017             synchronized (this) {
2018                 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
2019                         false,
2020                         0,
2021                         false,
2022                         0,
2023                         null,
2024                         new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM));
2025                 app.setPersistent(true);
2026                 app.setPid(MY_PID);
2027                 app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
2028                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2029                 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM);
2030                 addPidLocked(app);
2031                 updateLruProcessLocked(app, false, null);
2032                 updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT);
2033             }
2034         } catch (PackageManager.NameNotFoundException e) {
2035             throw new RuntimeException(
2036                     "Unable to find android system package", e);
2037         }
2038 
2039         // Start watching app ops after we and the package manager are up and running.
2040         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2041                 new IAppOpsCallback.Stub() {
2042                     @Override public void opChanged(int op, int uid, String packageName) {
2043                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2044                             if (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
2045                                     != AppOpsManager.MODE_ALLOWED) {
2046                                 runInBackgroundDisabled(uid);
2047                             }
2048                         }
2049                     }
2050                 });
2051 
2052         final int[] cameraOp = {AppOpsManager.OP_CAMERA};
2053         mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
2054             @Override
2055             public void opActiveChanged(int op, int uid, String packageName, String attributionTag,
2056                     boolean active, @AttributionFlags int attributionFlags,
2057                     int attributionChainId) {
2058                 cameraActiveChanged(uid, active);
2059             }
2060         });
2061     }
2062 
setWindowManager(WindowManagerService wm)2063     public void setWindowManager(WindowManagerService wm) {
2064         synchronized (this) {
2065             mWindowManager = wm;
2066             mWmInternal = LocalServices.getService(WindowManagerInternal.class);
2067             mActivityTaskManager.setWindowManager(wm);
2068         }
2069     }
2070 
2071     /**
2072      * @param usageStatsManager shouldn't be null
2073      */
setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)2074     public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) {
2075         mUsageStatsService = usageStatsManager;
2076         mActivityTaskManager.setUsageStatsManager(usageStatsManager);
2077     }
2078 
2079     /**
2080      * Sets the internal content capture manager service.
2081      *
2082      * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock.
2083      */
setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2084     public void setContentCaptureManager(
2085             @Nullable ContentCaptureManagerInternal contentCaptureManager) {
2086         mContentCaptureService = contentCaptureManager;
2087     }
2088 
startObservingNativeCrashes()2089     public void startObservingNativeCrashes() {
2090         final NativeCrashListener ncl = new NativeCrashListener(this);
2091         ncl.start();
2092     }
2093 
2094     /**
2095      * Sets a policy for handling app ops.
2096      *
2097      * @param appOpsPolicy The policy.
2098      */
setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)2099     public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) {
2100         mAppOpsService.setAppOpsPolicy(appOpsPolicy);
2101     }
2102 
getAppOpsService()2103     public IAppOpsService getAppOpsService() {
2104         return mAppOpsService;
2105     }
2106 
2107     /**
2108      * Sets the internal voice interaction manager service.
2109      */
setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)2110     private void setVoiceInteractionManagerProvider(
2111             @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) {
2112         mVoiceInteractionManagerProvider = provider;
2113     }
2114 
2115     /**
2116      * Represents volatile states associated with a Dropbox entry.
2117      * <p>
2118      * These states, such as the process frozen state, can change quickly over time and thus
2119      * should be captured as soon as possible to ensure accurate state. If a state is undefined,
2120      * it means that the state was not read early and a fallback value can be used.
2121      * </p>
2122      */
2123     static class VolatileDropboxEntryStates {
2124         private final Boolean mIsProcessFrozen;
2125 
VolatileDropboxEntryStates(Boolean frozenState)2126         private VolatileDropboxEntryStates(Boolean frozenState) {
2127             this.mIsProcessFrozen = frozenState;
2128         }
2129 
withProcessFrozenState(boolean frozenState)2130         public static VolatileDropboxEntryStates withProcessFrozenState(boolean frozenState) {
2131             return new VolatileDropboxEntryStates(frozenState);
2132         }
2133 
emptyVolatileDropboxEnytyStates()2134         public static VolatileDropboxEntryStates emptyVolatileDropboxEnytyStates() {
2135             return new VolatileDropboxEntryStates(null);
2136         }
2137 
isProcessFrozen()2138         public Boolean isProcessFrozen() {
2139             return mIsProcessFrozen;
2140         }
2141     }
2142 
2143     static class MemBinder extends Binder {
2144         ActivityManagerService mActivityManagerService;
2145         private final PriorityDump.PriorityDumper mPriorityDumper =
2146                 new PriorityDump.PriorityDumper() {
2147             @Override
2148             public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args,
2149                     boolean asProto) {
2150                 dump(fd, pw, new String[] {"-a"}, asProto);
2151             }
2152 
2153             @Override
2154             public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
2155                 mActivityManagerService.dumpApplicationMemoryUsage(
2156                         fd, pw, "  ", args, false, null, asProto);
2157             }
2158         };
2159 
MemBinder(ActivityManagerService activityManagerService)2160         MemBinder(ActivityManagerService activityManagerService) {
2161             mActivityManagerService = activityManagerService;
2162         }
2163 
2164         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2165         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2166             try {
2167                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2168 
2169                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2170                         "meminfo", pw)) return;
2171                 PriorityDump.dump(mPriorityDumper, fd, pw, args);
2172             } finally {
2173                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2174             }
2175         }
2176     }
2177 
2178     static class GraphicsBinder extends Binder {
2179         ActivityManagerService mActivityManagerService;
GraphicsBinder(ActivityManagerService activityManagerService)2180         GraphicsBinder(ActivityManagerService activityManagerService) {
2181             mActivityManagerService = activityManagerService;
2182         }
2183 
2184         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2185         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2186             try {
2187                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2188 
2189                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2190                         "gfxinfo", pw)) return;
2191                 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2192             } finally {
2193                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2194             }
2195         }
2196     }
2197 
2198     static class DbBinder extends Binder {
2199         ActivityManagerService mActivityManagerService;
DbBinder(ActivityManagerService activityManagerService)2200         DbBinder(ActivityManagerService activityManagerService) {
2201             mActivityManagerService = activityManagerService;
2202         }
2203 
2204         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2205         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2206             try {
2207                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2208 
2209                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2210                         "dbinfo", pw)) return;
2211                 mActivityManagerService.dumpDbInfo(fd, pw, args);
2212             } finally {
2213                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2214             }
2215         }
2216     }
2217 
2218     static class CacheBinder extends Binder {
2219         ActivityManagerService mActivityManagerService;
2220 
CacheBinder(ActivityManagerService activityManagerService)2221         CacheBinder(ActivityManagerService activityManagerService) {
2222             mActivityManagerService = activityManagerService;
2223         }
2224 
2225         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2226         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2227             try {
2228                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2229 
2230                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2231                         "cacheinfo", pw)) {
2232                     return;
2233                 }
2234 
2235                 mActivityManagerService.dumpBinderCacheContents(fd, pw, args);
2236             } finally {
2237                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2238             }
2239         }
2240     }
2241 
2242     public static final class Lifecycle extends SystemService {
2243         private final ActivityManagerService mService;
2244         private static ActivityTaskManagerService sAtm;
2245 
Lifecycle(Context context)2246         public Lifecycle(Context context) {
2247             super(context);
2248             mService = new ActivityManagerService(context, sAtm);
2249         }
2250 
startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2251         public static ActivityManagerService startService(
2252                 SystemServiceManager ssm, ActivityTaskManagerService atm) {
2253             sAtm = atm;
2254             return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2255         }
2256 
2257         @Override
onStart()2258         public void onStart() {
2259             mService.start();
2260         }
2261 
2262         @Override
onBootPhase(int phase)2263         public void onBootPhase(int phase) {
2264             mService.mBootPhase = phase;
2265             if (phase == PHASE_SYSTEM_SERVICES_READY) {
2266                 mService.mBatteryStatsService.systemServicesReady();
2267                 mService.mServices.systemServicesReady();
2268             } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
2269                 mService.startBroadcastObservers();
2270             } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2271                 mService.mPackageWatchdog.onPackagesReady();
2272             }
2273         }
2274 
2275         @Override
onUserStopped(@onNull TargetUser user)2276         public void onUserStopped(@NonNull TargetUser user) {
2277             mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier());
2278         }
2279 
getService()2280         public ActivityManagerService getService() {
2281             return mService;
2282         }
2283     }
2284 
maybeLogUserspaceRebootEvent()2285     private void maybeLogUserspaceRebootEvent() {
2286         if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) {
2287             return;
2288         }
2289         final int userId = mUserController.getCurrentUserId();
2290         if (userId != UserHandle.USER_SYSTEM) {
2291             // Only log for user0.
2292             return;
2293         }
2294         // TODO(b/148767783): should we check all profiles under user0?
2295         UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId),
2296                 BackgroundThread.getExecutor());
2297     }
2298 
2299     /**
2300      * Encapsulates global settings related to hidden API enforcement behaviour, including tracking
2301      * the latest value via a content observer.
2302      */
2303     static class HiddenApiSettings extends ContentObserver
2304             implements DeviceConfig.OnPropertiesChangedListener {
2305 
2306         private final Context mContext;
2307         private boolean mBlacklistDisabled;
2308         private String mExemptionsStr;
2309         private List<String> mExemptions = Collections.emptyList();
2310         private int mLogSampleRate = -1;
2311         private int mStatslogSampleRate = -1;
2312         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
2313 
2314         /**
2315          * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
2316          * the range 0 to 0x10000 inclusive.
2317          *
2318          * @hide
2319          */
2320         public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE =
2321                 "hidden_api_access_log_sampling_rate";
2322 
2323         /**
2324          * Sampling rate for hidden API access event logging with statslog, as an integer in the
2325          * range 0 to 0x10000 inclusive.
2326          *
2327          * @hide
2328          */
2329         public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
2330                 "hidden_api_access_statslog_sampling_rate";
2331 
onPropertiesChanged(DeviceConfig.Properties properties)2332         public void onPropertiesChanged(DeviceConfig.Properties properties) {
2333             int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0);
2334             if (logSampleRate < 0 || logSampleRate > 0x10000) {
2335                 logSampleRate = -1;
2336             }
2337             if (logSampleRate != -1 && logSampleRate != mLogSampleRate) {
2338                 mLogSampleRate = logSampleRate;
2339                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
2340             }
2341 
2342             int statslogSampleRate =
2343                     properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
2344             if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) {
2345                 statslogSampleRate = -1;
2346             }
2347             if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) {
2348                 mStatslogSampleRate = statslogSampleRate;
2349                 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
2350             }
2351         }
2352 
HiddenApiSettings(Handler handler, Context context)2353         public HiddenApiSettings(Handler handler, Context context) {
2354             super(handler);
2355             mContext = context;
2356         }
2357 
registerObserver()2358         public void registerObserver() {
2359             mContext.getContentResolver().registerContentObserver(
2360                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
2361                     false,
2362                     this);
2363             mContext.getContentResolver().registerContentObserver(
2364                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
2365                     false,
2366                     this);
2367             DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT,
2368                     mContext.getMainExecutor(), this);
2369             update();
2370         }
2371 
update()2372         private void update() {
2373             String exemptions = Settings.Global.getString(mContext.getContentResolver(),
2374                     Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS);
2375             if (!TextUtils.equals(exemptions, mExemptionsStr)) {
2376                 mExemptionsStr = exemptions;
2377                 if ("*".equals(exemptions)) {
2378                     mBlacklistDisabled = true;
2379                     mExemptions = Collections.emptyList();
2380                 } else {
2381                     mBlacklistDisabled = false;
2382                     mExemptions = TextUtils.isEmpty(exemptions)
2383                             ? Collections.emptyList()
2384                             : Arrays.asList(exemptions.split(","));
2385                 }
2386                 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) {
2387                   Slog.e(TAG, "Failed to set API blacklist exemptions!");
2388                   // leave mExemptionsStr as is, so we don't try to send the same list again.
2389                   mExemptions = Collections.emptyList();
2390                 }
2391             }
2392             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
2393         }
2394 
getValidEnforcementPolicy(String settingsKey)2395         private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) {
2396             int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey,
2397                     ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT);
2398             if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) {
2399                 return policy;
2400             } else {
2401                 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
2402             }
2403         }
2404 
isDisabled()2405         boolean isDisabled() {
2406             return mBlacklistDisabled;
2407         }
2408 
getPolicy()2409         @HiddenApiEnforcementPolicy int getPolicy() {
2410             return mPolicy;
2411         }
2412 
onChange(boolean selfChange)2413         public void onChange(boolean selfChange) {
2414             update();
2415         }
2416     }
2417 
getAppOpsManager()2418     AppOpsManager getAppOpsManager() {
2419         if (mAppOpsManager == null) {
2420             mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
2421         }
2422         return mAppOpsManager;
2423     }
2424 
2425     /** Provides the basic functionality for unit tests. */
2426     @VisibleForTesting
ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread)2427     ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread) {
2428         this(injector, handlerThread, null);
2429     }
2430 
2431     /** Provides the basic functionality for unit tests. */
2432     @VisibleForTesting
ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread, @Nullable UserController userController)2433     ActivityManagerService(Injector injector, @NonNull ServiceThread handlerThread,
2434             @Nullable UserController userController) {
2435         mInjector = injector;
2436         mContext = mInjector.getContext();
2437         mUiContext = null;
2438         mAppErrors = null;
2439         mPackageWatchdog = null;
2440         mAppOpsService = mInjector.getAppOpsService(null /* recentAccessesFile */,
2441             null /* storageFile */, null /* handler */);
2442         mBatteryStatsService = mInjector.getBatteryStatsService();
2443         mHandler = new MainHandler(handlerThread.getLooper());
2444         mHandlerThread = handlerThread;
2445         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2446         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
2447         mPlatformCompat = null;
2448         mProcessList = injector.getProcessList(this);
2449         mProcessList.init(this, activeUids, mPlatformCompat);
2450         mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null);
2451         mPhantomProcessList = new PhantomProcessList(this);
2452         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids, handlerThread);
2453 
2454         mIntentFirewall = null;
2455         mProcessStats = new ProcessStatsService(this, mContext.getCacheDir());
2456         mCpHelper = new ContentProviderHelper(this, false);
2457         mServices = mInjector.getActiveServices(this);
2458         mSystemThread = null;
2459         mUiHandler = injector.getUiHandler(null /* service */);
2460         mUidObserverController = new UidObserverController(mUiHandler);
2461         mUserController = userController == null ? new UserController(this) : userController;
2462         mInjector.mUserController = mUserController;
2463         mPendingIntentController =
2464                 new PendingIntentController(handlerThread.getLooper(), mUserController, mConstants);
2465         mAppRestrictionController = new AppRestrictionController(mContext, this);
2466         mProcStartHandlerThread = null;
2467         mProcStartHandler = null;
2468         mHiddenApiBlacklist = null;
2469         mFactoryTest = FACTORY_TEST_OFF;
2470         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2471         mInternal = new LocalService();
2472         mPendingStartActivityUids = new PendingStartActivityUids();
2473         mUseFifoUiScheduling = false;
2474         mEnableOffloadQueue = false;
2475         mEnableModernQueue = false;
2476         mBroadcastQueues = new BroadcastQueue[0];
2477         mComponentAliasResolver = new ComponentAliasResolver(this);
2478     }
2479 
2480     // Note: This method is invoked on the main thread but may need to attach various
2481     // handlers to other threads.  So take care to be explicit about the looper.
ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2482     public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
2483         LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2484         mInjector = new Injector(systemContext);
2485         mContext = systemContext;
2486 
2487         mFactoryTest = FactoryTest.getMode();
2488         mSystemThread = ActivityThread.currentActivityThread();
2489         mUiContext = mSystemThread.getSystemUiContext();
2490 
2491         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2492 
2493         mHandlerThread = new ServiceThread(TAG,
2494                 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2495         mHandlerThread.start();
2496         mHandler = new MainHandler(mHandlerThread.getLooper());
2497         mUiHandler = mInjector.getUiHandler(this);
2498 
2499         mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2500                 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2501         mProcStartHandlerThread.start();
2502         mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper());
2503 
2504         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2505         final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2506         mPlatformCompat = (PlatformCompat) ServiceManager.getService(
2507                 Context.PLATFORM_COMPAT_SERVICE);
2508         mProcessList = mInjector.getProcessList(this);
2509         mProcessList.init(this, activeUids, mPlatformCompat);
2510         mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
2511                 new LowMemDetector(this));
2512         mPhantomProcessList = new PhantomProcessList(this);
2513         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2514 
2515         // Broadcast policy parameters
2516         final BroadcastConstants foreConstants = new BroadcastConstants(
2517                 Settings.Global.BROADCAST_FG_CONSTANTS);
2518         foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2519 
2520         final BroadcastConstants backConstants = new BroadcastConstants(
2521                 Settings.Global.BROADCAST_BG_CONSTANTS);
2522         backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2523 
2524         final BroadcastConstants offloadConstants = new BroadcastConstants(
2525                 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2526         offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2527         // by default, no "slow" policy in this queue
2528         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2529 
2530         mEnableOffloadQueue = SystemProperties.getBoolean(
2531                 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", true);
2532         mEnableModernQueue = foreConstants.MODERN_QUEUE_ENABLED;
2533 
2534         if (mEnableModernQueue) {
2535             mBroadcastQueues = new BroadcastQueue[1];
2536             mBroadcastQueues[0] = new BroadcastQueueModernImpl(this, mHandler,
2537                     foreConstants, backConstants);
2538         } else {
2539             mBroadcastQueues = new BroadcastQueue[4];
2540             mBroadcastQueues[BROADCAST_QUEUE_FG] = new BroadcastQueueImpl(this, mHandler,
2541                     "foreground", foreConstants, false, ProcessList.SCHED_GROUP_DEFAULT);
2542             mBroadcastQueues[BROADCAST_QUEUE_BG] = new BroadcastQueueImpl(this, mHandler,
2543                     "background", backConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
2544             mBroadcastQueues[BROADCAST_QUEUE_BG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
2545                     "offload_bg", offloadConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
2546             mBroadcastQueues[BROADCAST_QUEUE_FG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
2547                     "offload_fg", foreConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
2548         }
2549 
2550         mServices = new ActiveServices(this);
2551         mCpHelper = new ContentProviderHelper(this, true);
2552         mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2553         mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2554         mUidObserverController = new UidObserverController(mUiHandler);
2555 
2556         final File systemDir = SystemServiceManager.ensureSystemDir();
2557 
2558         // TODO: Move creation of battery stats service outside of activity manager service.
2559         mBatteryStatsService = BatteryStatsService.create(systemContext, systemDir,
2560                 BackgroundThread.getHandler(), this);
2561         mOnBattery = DEBUG_POWER ? true
2562                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2563         mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2564 
2565         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2566 
2567         mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops_accesses.xml"),
2568                 new File(systemDir, "appops.xml"), mHandler);
2569 
2570         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2571 
2572         mUserController = new UserController(this);
2573         mInjector.mUserController = mUserController;
2574 
2575         mPendingIntentController = new PendingIntentController(
2576                 mHandlerThread.getLooper(), mUserController, mConstants);
2577 
2578         mAppRestrictionController = new AppRestrictionController(mContext, this);
2579 
2580         mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;
2581 
2582         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2583         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2584 
2585         mActivityTaskManager = atm;
2586         mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2587                 DisplayThread.get().getLooper());
2588         mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2589 
2590         mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2591 
2592         Watchdog.getInstance().addMonitor(this);
2593         Watchdog.getInstance().addThread(mHandler);
2594 
2595         // bind background threads to little cores
2596         // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2597         // make sure we've already adjusted system_server's internal view of itself first
2598         updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT);
2599         try {
2600             Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2601                     Process.THREAD_GROUP_SYSTEM);
2602             Process.setThreadGroupAndCpuset(
2603                     mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
2604                     Process.THREAD_GROUP_SYSTEM);
2605         } catch (Exception e) {
2606             Slog.w(TAG, "Setting background thread cpuset failed");
2607         }
2608 
2609         mInternal = new LocalService();
2610         mPendingStartActivityUids = new PendingStartActivityUids();
2611         mTraceErrorLogger = new TraceErrorLogger();
2612         mComponentAliasResolver = new ComponentAliasResolver(this);
2613     }
2614 
setSystemServiceManager(SystemServiceManager mgr)2615     public void setSystemServiceManager(SystemServiceManager mgr) {
2616         mSystemServiceManager = mgr;
2617     }
2618 
setInstaller(Installer installer)2619     public void setInstaller(Installer installer) {
2620         mInstaller = installer;
2621     }
2622 
start()2623     private void start() {
2624         mBatteryStatsService.publish();
2625         mAppOpsService.publish();
2626         mProcessStats.publish();
2627         Slog.d("AppOps", "AppOpsService published");
2628         LocalServices.addService(ActivityManagerInternal.class, mInternal);
2629         LocalManagerRegistry.addManager(ActivityManagerLocal.class,
2630                 (ActivityManagerLocal) mInternal);
2631         mActivityTaskManager.onActivityManagerInternalAdded();
2632         mPendingIntentController.onActivityManagerInternalAdded();
2633         mAppProfiler.onActivityManagerInternalAdded();
2634         CriticalEventLog.init();
2635     }
2636 
initPowerManagement()2637     public void initPowerManagement() {
2638         mActivityTaskManager.onInitPowerManagement();
2639         mBatteryStatsService.initPowerManagement();
2640         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2641     }
2642 
getBackgroundLaunchBroadcasts()2643     private ArraySet<String> getBackgroundLaunchBroadcasts() {
2644         if (mBackgroundLaunchBroadcasts == null) {
2645             mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2646         }
2647         return mBackgroundLaunchBroadcasts;
2648     }
2649 
2650     /**
2651      * Ensures that the given package name has an explicit set of allowed associations.
2652      * If it does not, give it an empty set.
2653      */
requireAllowedAssociationsLocked(String packageName)2654     void requireAllowedAssociationsLocked(String packageName) {
2655         ensureAllowedAssociations();
2656         if (mAllowedAssociations.get(packageName) == null) {
2657             mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName,
2658                     new ArraySet<>(), /* isDebuggable = */ false));
2659         }
2660     }
2661 
2662     /**
2663      * Returns true if the package {@code pkg1} running under user handle {@code uid1} is
2664      * allowed association with the package {@code pkg2} running under user handle {@code uid2}.
2665      * <p> If either of the packages are running as  part of the core system, then the
2666      * association is implicitly allowed.
2667      */
validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2668     boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) {
2669         ensureAllowedAssociations();
2670         // Interactions with the system uid are always allowed, since that is the core system
2671         // that everyone needs to be able to interact with. Also allow reflexive associations
2672         // within the same uid.
2673         if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID
2674                 || UserHandle.getAppId(uid2) == SYSTEM_UID) {
2675             return true;
2676         }
2677 
2678         // Check for association on both source and target packages.
2679         PackageAssociationInfo pai = mAllowedAssociations.get(pkg1);
2680         if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) {
2681             return false;
2682         }
2683         pai = mAllowedAssociations.get(pkg2);
2684         if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) {
2685             return false;
2686         }
2687         // If no explicit associations are provided in the manifest, then assume the app is
2688         // allowed associations with any package.
2689         return true;
2690     }
2691 
2692     /** Sets up allowed associations for system prebuilt packages from system config (if needed). */
ensureAllowedAssociations()2693     private void ensureAllowedAssociations() {
2694         if (mAllowedAssociations == null) {
2695             ArrayMap<String, ArraySet<String>> allowedAssociations =
2696                     SystemConfig.getInstance().getAllowedAssociations();
2697             mAllowedAssociations = new ArrayMap<>(allowedAssociations.size());
2698             PackageManagerInternal pm = getPackageManagerInternal();
2699             for (int i = 0; i < allowedAssociations.size(); i++) {
2700                 final String pkg = allowedAssociations.keyAt(i);
2701                 final ArraySet<String> asc = allowedAssociations.valueAt(i);
2702 
2703                 // Query latest debuggable flag from package-manager.
2704                 boolean isDebuggable = false;
2705                 try {
2706                     ApplicationInfo ai = AppGlobals.getPackageManager()
2707                             .getApplicationInfo(pkg, MATCH_ALL, 0);
2708                     if (ai != null) {
2709                         isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2710                     }
2711                 } catch (RemoteException e) {
2712                     /* ignore */
2713                 }
2714                 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable));
2715             }
2716         }
2717     }
2718 
2719     /** Updates allowed associations for app info (specifically, based on debuggability).  */
updateAssociationForApp(ApplicationInfo appInfo)2720     private void updateAssociationForApp(ApplicationInfo appInfo) {
2721         ensureAllowedAssociations();
2722         PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName);
2723         if (pai != null) {
2724             pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
2725         }
2726     }
2727 
2728     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)2729     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2730             throws RemoteException {
2731         if (code == SYSPROPS_TRANSACTION) {
2732             // We need to tell all apps about the system property change.
2733             ArrayList<IBinder> procs = new ArrayList<IBinder>();
2734             synchronized (mProcLock) {
2735                 final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
2736                         mProcessList.getProcessNamesLOSP().getMap();
2737                 final int numOfNames = pmap.size();
2738                 for (int ip = 0; ip < numOfNames; ip++) {
2739                     SparseArray<ProcessRecord> apps = pmap.valueAt(ip);
2740                     final int numOfApps = apps.size();
2741                     for (int ia = 0; ia < numOfApps; ia++) {
2742                         ProcessRecord app = apps.valueAt(ia);
2743                         final IApplicationThread thread = app.getThread();
2744                         if (thread != null) {
2745                             procs.add(thread.asBinder());
2746                         }
2747                     }
2748                 }
2749             }
2750 
2751             int N = procs.size();
2752             for (int i=0; i<N; i++) {
2753                 Parcel data2 = Parcel.obtain();
2754                 try {
2755                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2756                             Binder.FLAG_ONEWAY);
2757                 } catch (RemoteException e) {
2758                 }
2759                 data2.recycle();
2760             }
2761         }
2762         try {
2763             return super.onTransact(code, data, reply, flags);
2764         } catch (RuntimeException e) {
2765             // The activity manager only throws certain exceptions intentionally, so let's
2766             // log all others.
2767             if (!(e instanceof SecurityException
2768                     || e instanceof IllegalArgumentException
2769                     || e instanceof IllegalStateException)) {
2770                 Slog.wtf(TAG, "Activity Manager Crash."
2771                         + " UID:" + Binder.getCallingUid()
2772                         + " PID:" + Binder.getCallingPid()
2773                         + " TRANS:" + code, e);
2774             }
2775             throw e;
2776         }
2777     }
2778 
updateCpuStats()2779     void updateCpuStats() {
2780         mAppProfiler.updateCpuStats();
2781     }
2782 
updateCpuStatsNow()2783     void updateCpuStatsNow() {
2784         mAppProfiler.updateCpuStatsNow();
2785     }
2786 
2787     @Override
batteryNeedsCpuUpdate()2788     public void batteryNeedsCpuUpdate() {
2789         updateCpuStatsNow();
2790     }
2791 
2792     @Override
batteryPowerChanged(boolean onBattery)2793     public void batteryPowerChanged(boolean onBattery) {
2794         // When plugging in, update the CPU stats first before changing
2795         // the plug state.
2796         updateCpuStatsNow();
2797         synchronized (mProcLock) {
2798             mOnBattery = DEBUG_POWER ? true : onBattery;
2799             mOomAdjProfiler.batteryPowerChanged(onBattery);
2800         }
2801     }
2802 
2803     @Override
batteryStatsReset()2804     public void batteryStatsReset() {
2805         mOomAdjProfiler.reset();
2806     }
2807 
2808     @Override
batterySendBroadcast(Intent intent)2809     public void batterySendBroadcast(Intent intent) {
2810         synchronized (this) {
2811             broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null,
2812                     null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
2813                     Binder.getCallingPid(), UserHandle.USER_ALL);
2814         }
2815     }
2816 
2817     /**
2818      * Initialize the application bind args. These are passed to each
2819      * process when the bindApplication() IPC is sent to the process. They're
2820      * lazily setup to make sure the services are running when they're asked for.
2821      */
getCommonServicesLocked(boolean isolated)2822     private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
2823         // Isolated processes won't get this optimization, so that we don't
2824         // violate the rules about which services they have access to.
2825         if (isolated) {
2826             if (mIsolatedAppBindArgs == null) {
2827                 mIsolatedAppBindArgs = new ArrayMap<>(1);
2828                 addServiceToMap(mIsolatedAppBindArgs, "package");
2829                 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr");
2830             }
2831             return mIsolatedAppBindArgs;
2832         }
2833 
2834         if (mAppBindArgs == null) {
2835             mAppBindArgs = new ArrayMap<>();
2836 
2837             // Add common services.
2838             // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too.
2839             // Enable the check in ApplicationThread.bindApplication() to make sure.
2840             addServiceToMap(mAppBindArgs, "package");
2841             addServiceToMap(mAppBindArgs, "permissionmgr");
2842             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
2843             addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE);
2844             addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE);
2845             addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE);
2846             addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE);
2847             addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE);
2848             addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
2849             addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
2850             addServiceToMap(mAppBindArgs, "graphicsstats");
2851             addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
2852             addServiceToMap(mAppBindArgs, "content");
2853             addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
2854             addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
2855             addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
2856             addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
2857             addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
2858             addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
2859             addServiceToMap(mAppBindArgs, "mount");
2860             addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE);
2861         }
2862         return mAppBindArgs;
2863     }
2864 
addServiceToMap(ArrayMap<String, IBinder> map, String name)2865     private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) {
2866         final IBinder service = ServiceManager.getService(name);
2867         if (service != null) {
2868             map.put(name, service);
2869             if (false) {
2870                 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache.");
2871             }
2872         }
2873     }
2874 
2875     @Override
setFocusedRootTask(int taskId)2876     public void setFocusedRootTask(int taskId) {
2877         mActivityTaskManager.setFocusedRootTask(taskId);
2878     }
2879 
2880     /** Sets the task stack listener that gets callbacks when a task stack changes. */
2881     @Override
registerTaskStackListener(ITaskStackListener listener)2882     public void registerTaskStackListener(ITaskStackListener listener) {
2883         mActivityTaskManager.registerTaskStackListener(listener);
2884     }
2885 
2886     /**
2887      * Unregister a task stack listener so that it stops receiving callbacks.
2888      */
2889     @Override
unregisterTaskStackListener(ITaskStackListener listener)2890     public void unregisterTaskStackListener(ITaskStackListener listener) {
2891         mActivityTaskManager.unregisterTaskStackListener(listener);
2892     }
2893 
2894     @GuardedBy("this")
updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2895     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2896             ProcessRecord client) {
2897         mProcessList.updateLruProcessLocked(app, activityChange, client);
2898     }
2899 
2900     @GuardedBy("this")
removeLruProcessLocked(ProcessRecord app)2901     final void removeLruProcessLocked(ProcessRecord app) {
2902         mProcessList.removeLruProcessLocked(app);
2903     }
2904 
2905     @GuardedBy("this")
getProcessRecordLocked(String processName, int uid)2906     final ProcessRecord getProcessRecordLocked(String processName, int uid) {
2907         return mProcessList.getProcessRecordLocked(processName, uid);
2908     }
2909 
2910     @GuardedBy(anyOf = {"this", "mProcLock"})
getProcessNamesLOSP()2911     final ProcessMap<ProcessRecord> getProcessNamesLOSP() {
2912         return mProcessList.getProcessNamesLOSP();
2913     }
2914 
notifyPackageUse(String packageName, int reason)2915     void notifyPackageUse(String packageName, int reason) {
2916         getPackageManagerInternal().notifyPackageUse(packageName, reason);
2917     }
2918 
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2919     boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
2920             String processName, String abiOverride, int uid, Runnable crashHandler) {
2921         synchronized(this) {
2922             ApplicationInfo info = new ApplicationInfo();
2923             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
2924             // For isolated processes, the former contains the parent's uid and the latter the
2925             // actual uid of the isolated process.
2926             // In the special case introduced by this method (which is, starting an isolated
2927             // process directly from the SystemServer without an actual parent app process) the
2928             // closest thing to a parent's uid is SYSTEM_UID.
2929             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
2930             // the |isolated| logic in the ProcessRecord constructor.
2931             info.uid = SYSTEM_UID;
2932             info.processName = processName;
2933             info.className = entryPoint;
2934             info.packageName = "android";
2935             info.seInfoUser = SELinuxUtil.COMPLETE_STR;
2936             info.targetSdkVersion = Build.VERSION.SDK_INT;
2937             ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */,
2938                     false /* knownToBeDead */, 0 /* intentFlags */,
2939                     sNullHostingRecord  /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY,
2940                     true /* allowWhileBooting */, true /* isolated */,
2941                     uid, false /* isSdkSandbox */, 0 /* sdkSandboxUid */,
2942                     null /* sdkSandboxClientAppPackage */,
2943                     abiOverride, entryPoint, entryPointArgs, crashHandler);
2944             return proc != null;
2945         }
2946     }
2947 
2948     @GuardedBy("this")
startSdkSandboxProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid, String sdkSandboxClientAppPackage)2949     final ProcessRecord startSdkSandboxProcessLocked(String processName,
2950             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2951             HostingRecord hostingRecord, int zygotePolicyFlags, int sdkSandboxUid,
2952             String sdkSandboxClientAppPackage) {
2953         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
2954                 hostingRecord, zygotePolicyFlags, false /* allowWhileBooting */,
2955                 false /* isolated */, 0 /* isolatedUid */,
2956                 true /* isSdkSandbox */, sdkSandboxUid, sdkSandboxClientAppPackage,
2957                 null /* ABI override */, null /* entryPoint */,
2958                 null /* entryPointArgs */, null /* crashHandler */);
2959     }
2960 
2961     @GuardedBy("this")
startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)2962     final ProcessRecord startProcessLocked(String processName,
2963             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2964             HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
2965             boolean isolated) {
2966         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
2967                 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
2968                 false /* isSdkSandbox */, 0 /* sdkSandboxClientAppUid */,
2969                 null /* sdkSandboxClientAppPackage */,
2970                 null /* ABI override */, null /* entryPoint */,
2971                 null /* entryPointArgs */, null /* crashHandler */);
2972     }
2973 
isAllowedWhileBooting(ApplicationInfo ai)2974     boolean isAllowedWhileBooting(ApplicationInfo ai) {
2975         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2976     }
2977 
2978     /**
2979      * Update battery stats on the activity' usage.
2980      * @param activity
2981      * @param uid
2982      * @param userId
2983      * @param resumed
2984      */
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)2985     void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) {
2986         if (DEBUG_SWITCH) {
2987             Slog.d(TAG_SWITCH,
2988                     "updateBatteryStats: comp=" + activity + "res=" + resumed);
2989         }
2990         mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(),
2991                 activity.getShortClassName(), uid, userId, resumed);
2992     }
2993 
2994     /**
2995      * Update UsageStas on the activity's usage.
2996      * @param activity
2997      * @param userId
2998      * @param event
2999      * @param appToken ActivityRecord's appToken.
3000      * @param taskRoot Task's root
3001      */
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)3002     public void updateActivityUsageStats(ComponentName activity, int userId, int event,
3003             IBinder appToken, ComponentName taskRoot, ActivityId activityId) {
3004         if (DEBUG_SWITCH) {
3005             Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp="
3006                     + activity + " hash=" + appToken.hashCode() + " event=" + event);
3007         }
3008         if (mUsageStatsService != null) {
3009             mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot);
3010             if (event == Event.ACTIVITY_RESUMED) {
3011                 // Report component usage as an activity is an app component
3012                 mUsageStatsService.reportEvent(
3013                         activity.getPackageName(), userId, Event.APP_COMPONENT_USED);
3014             }
3015         }
3016         ContentCaptureManagerInternal contentCaptureService = mContentCaptureService;
3017         if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED
3018                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED
3019                 || event == Event.ACTIVITY_DESTROYED)) {
3020             contentCaptureService.notifyActivityEvent(userId, activity, event, activityId);
3021         }
3022         // Currently we have move most of logic to the client side. When the activity lifecycle
3023         // event changed, the client side will notify the VoiceInteractionManagerService. But
3024         // when the application process died, the VoiceInteractionManagerService will miss the
3025         // activity lifecycle event changed, so we still need ACTIVITY_DESTROYED event here to
3026         // know if the activity has been destroyed.
3027         if (mVoiceInteractionManagerProvider != null && event == Event.ACTIVITY_DESTROYED) {
3028             mVoiceInteractionManagerProvider.notifyActivityDestroyed(appToken);
3029         }
3030     }
3031 
3032     /**
3033      * Update UsageStats on this package's usage.
3034      * @param packageName
3035      * @param userId
3036      * @param event
3037      */
updateActivityUsageStats(String packageName, int userId, int event)3038     public void updateActivityUsageStats(String packageName, int userId, int event) {
3039         if (DEBUG_SWITCH) {
3040             Slog.d(TAG_SWITCH, "updateActivityUsageStats: package="
3041                     + packageName + " event=" + event);
3042         }
3043         if (mUsageStatsService != null) {
3044             mUsageStatsService.reportEvent(packageName, userId, event);
3045         }
3046     }
3047 
3048     /**
3049      * Update Usages on this foreground service's usage.
3050      * @param service
3051      * @param userId
3052      * @param started
3053      */
updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3054     void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) {
3055         if (DEBUG_SWITCH) {
3056             Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp="
3057                     + service + " started=" + started);
3058         }
3059         if (mUsageStatsService != null) {
3060             mUsageStatsService.reportEvent(service, userId,
3061                     started ? UsageEvents.Event.FOREGROUND_SERVICE_START
3062                             : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null);
3063         }
3064     }
3065 
compatibilityInfoForPackage(ApplicationInfo ai)3066     CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
3067         return mAtmInternal.compatibilityInfoForPackage(ai);
3068     }
3069 
3070     /**
3071      * Enforces that the uid that calls a method is not an
3072      * {@link UserHandle#isIsolated(int) isolated} uid.
3073      *
3074      * @param caller the name of the method being called.
3075      * @throws SecurityException if the calling uid is an isolated uid.
3076      */
enforceNotIsolatedCaller(String caller)3077     /* package */ void enforceNotIsolatedCaller(String caller) {
3078         if (UserHandle.isIsolated(Binder.getCallingUid())) {
3079             throw new SecurityException("Isolated process not allowed to call " + caller);
3080         }
3081     }
3082 
3083     /**
3084      * Enforces that the uid that calls a method is not an
3085      * {@link UserHandle#isIsolated(int) isolated} uid or an
3086      * {@link Process#isSdkSandboxUid(int) SDK sandbox} uid.
3087      *
3088      * @param caller the name of the method being called.
3089      * @throws SecurityException if the calling uid is an isolated uid or SDK sandbox uid.
3090      */
enforceNotIsolatedOrSdkSandboxCaller(String caller)3091     void enforceNotIsolatedOrSdkSandboxCaller(String caller) {
3092         enforceNotIsolatedCaller(caller);
3093 
3094         if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
3095             throw new SecurityException("SDK sandbox process not allowed to call " + caller);
3096         }
3097     }
3098 
3099     /**
3100      * If the caller is an {@link Process#isSdkSandboxUid(int) SDK sandbox uid}, enforces that the
3101      * SDK sandbox has permission to start or bind to a given service.
3102      *
3103      * @param intent the intent used to start or bind to the service.
3104      * @throws IllegalStateException if {@link SdkSandboxManagerLocal} cannot be resolved.
3105      * @throws SecurityException if the SDK sandbox is not allowed to bind to this service.
3106      */
enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent)3107     private void enforceAllowedToStartOrBindServiceIfSdkSandbox(Intent intent) {
3108         if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
3109             SdkSandboxManagerLocal sdkSandboxManagerLocal =
3110                     LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
3111             if (sdkSandboxManagerLocal != null) {
3112                 sdkSandboxManagerLocal.enforceAllowedToStartOrBindService(intent);
3113             } else {
3114                 throw new IllegalStateException("SdkSandboxManagerLocal not found when checking"
3115                         + " whether SDK sandbox uid may start or bind to a service.");
3116             }
3117         }
3118     }
3119 
3120     /**
3121      * Enforces that the uid of the caller matches the uid of the package.
3122      *
3123      * @param packageName the name of the package to match uid against.
3124      * @param callingUid the uid of the caller.
3125      * @throws SecurityException if the calling uid doesn't match uid of the package.
3126      */
enforceCallingPackage(String packageName, int callingUid)3127     private void enforceCallingPackage(String packageName, int callingUid) {
3128         final int userId = UserHandle.getUserId(callingUid);
3129         final int packageUid = getPackageManagerInternal().getPackageUid(packageName,
3130                 /*flags=*/ 0, userId);
3131         if (packageUid != callingUid) {
3132             throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3133         }
3134     }
3135 
3136     @Override
setPackageScreenCompatMode(String packageName, int mode)3137     public void setPackageScreenCompatMode(String packageName, int mode) {
3138         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
3139     }
3140 
hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid)3141     private boolean hasUsageStatsPermission(String callingPackage, int callingUid, int callingPid) {
3142         final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS,
3143                 callingUid, callingPackage, null, false, "", false).getOpMode();
3144         if (mode == AppOpsManager.MODE_DEFAULT) {
3145             return checkPermission(Manifest.permission.PACKAGE_USAGE_STATS, callingPid, callingUid)
3146                     == PackageManager.PERMISSION_GRANTED;
3147         }
3148         return mode == AppOpsManager.MODE_ALLOWED;
3149     }
3150 
hasUsageStatsPermission(String callingPackage)3151     private boolean hasUsageStatsPermission(String callingPackage) {
3152         return hasUsageStatsPermission(callingPackage,
3153                 Binder.getCallingUid(), Binder.getCallingPid());
3154     }
3155 
enforceUsageStatsPermission(String callingPackage, int callingUid, int callingPid, String operation)3156     private void enforceUsageStatsPermission(String callingPackage,
3157             int callingUid, int callingPid, String operation) {
3158         if (!hasUsageStatsPermission(callingPackage, callingUid, callingPid)) {
3159             final String errorMsg = "Permission denial for <" + operation + "> from pid="
3160                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3161                     + " which requires PACKAGE_USAGE_STATS permission";
3162             throw new SecurityException(errorMsg);
3163         }
3164     }
3165 
3166     @Override
getPackageProcessState(String packageName, String callingPackage)3167     public int getPackageProcessState(String packageName, String callingPackage) {
3168         if (!hasUsageStatsPermission(callingPackage)) {
3169             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
3170                     "getPackageProcessState");
3171         }
3172 
3173         final int[] procState = {PROCESS_STATE_NONEXISTENT};
3174         synchronized (mProcLock) {
3175             mProcessList.forEachLruProcessesLOSP(false, proc -> {
3176                 if (procState[0] > proc.mState.getSetProcState()) {
3177                     if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null
3178                                 && proc.getPkgDeps().contains(packageName))) {
3179                         procState[0] = proc.mState.getSetProcState();
3180                     }
3181                 }
3182             });
3183         }
3184         return procState[0];
3185     }
3186 
3187     @Override
setProcessMemoryTrimLevel(String process, int userId, int level)3188     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
3189             throws RemoteException {
3190         if (!isCallerShell()) {
3191             throw new SecurityException("Only shell can call it");
3192         }
3193         synchronized (this) {
3194             final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel");
3195             if (app == null) {
3196                 throw new IllegalArgumentException("Unknown process: " + process);
3197             }
3198             final IApplicationThread thread = app.getThread();
3199             if (thread == null) {
3200                 throw new IllegalArgumentException("Process has no app thread");
3201             }
3202             if (app.mProfile.getTrimMemoryLevel() >= level) {
3203                 throw new IllegalArgumentException(
3204                         "Unable to set a higher trim level than current level");
3205             }
3206             if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
3207                     app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) {
3208                 throw new IllegalArgumentException("Unable to set a background trim level "
3209                     + "on a foreground process");
3210             }
3211             thread.scheduleTrimMemory(level);
3212             synchronized (mProcLock) {
3213                 app.mProfile.setTrimMemoryLevel(level);
3214             }
3215             return true;
3216         }
3217     }
3218 
dispatchOomAdjObserver(String msg)3219     void dispatchOomAdjObserver(String msg) {
3220         OomAdjObserver observer;
3221         synchronized (mOomAdjObserverLock) {
3222             observer = mCurOomAdjObserver;
3223         }
3224 
3225         if (observer != null) {
3226             observer.onOomAdjMessage(msg);
3227         }
3228     }
3229 
setOomAdjObserver(int uid, OomAdjObserver observer)3230     void setOomAdjObserver(int uid, OomAdjObserver observer) {
3231         synchronized (mOomAdjObserverLock) {
3232             mCurOomAdjUid = uid;
3233             mCurOomAdjObserver = observer;
3234         }
3235     }
3236 
clearOomAdjObserver()3237     void clearOomAdjObserver() {
3238         synchronized (mOomAdjObserverLock) {
3239             mCurOomAdjUid = -1;
3240             mCurOomAdjObserver = null;
3241         }
3242     }
3243 
reportUidInfoMessageLocked(String tag, String msg, int uid)3244     void reportUidInfoMessageLocked(String tag, String msg, int uid) {
3245         Slog.i(TAG, msg);
3246         synchronized (mOomAdjObserverLock) {
3247             if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) {
3248                 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3249             }
3250         }
3251     }
3252 
3253     /**
3254      * @deprecated use {@link #startActivityWithFeature} instead
3255      */
3256     @Deprecated
3257     @Override
startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3258     public int startActivity(IApplicationThread caller, String callingPackage,
3259             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3260             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
3261         return mActivityTaskManager.startActivity(caller, callingPackage, null, intent,
3262                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3263     }
3264 
3265     @Override
startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3266     public int startActivityWithFeature(IApplicationThread caller, String callingPackage,
3267             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
3268             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
3269             Bundle bOptions) {
3270         return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent,
3271                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3272     }
3273 
3274     /**
3275      * @deprecated use {@link #startActivityAsUserWithFeature} instead
3276      */
3277     @Deprecated
3278     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3279     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3280             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3281             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3282         return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType,
3283                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId);
3284     }
3285 
3286     @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)3287     public final int startActivityAsUserWithFeature(IApplicationThread caller,
3288             String callingPackage, String callingFeatureId, Intent intent, String resolvedType,
3289             IBinder resultTo, String resultWho, int requestCode, int startFlags,
3290             ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3291         return mActivityTaskManager.startActivityAsUser(caller, callingPackage,
3292                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
3293                     startFlags, profilerInfo, bOptions, userId);
3294     }
3295 
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)3296     WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3297             @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
3298             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
3299             Bundle bOptions, int userId) {
3300             return mActivityTaskManager.startActivityAndWait(caller, callingPackage,
3301                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
3302                     startFlags, profilerInfo, bOptions, userId);
3303     }
3304 
3305     @Override
startActivityFromRecents(int taskId, Bundle bOptions)3306     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
3307         return mActivityTaskManager.startActivityFromRecents(taskId, bOptions);
3308     }
3309 
3310     /**
3311      * This is the internal entry point for handling Activity.finish().
3312      *
3313      * @param token The Binder token referencing the Activity we want to finish.
3314      * @param resultCode Result code, if any, from this Activity.
3315      * @param resultData Result data (Intent), if any, from this Activity.
3316      * @param finishTask Whether to finish the task associated with this Activity.
3317      *
3318      * @return Returns true if the activity successfully finished, or false if it is still running.
3319      */
3320     @Override
finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3321     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
3322             int finishTask) {
3323         return ActivityClient.getInstance().finishActivity(token, resultCode, resultData,
3324                 finishTask);
3325     }
3326 
3327     @Override
setRequestedOrientation(IBinder token, int requestedOrientation)3328     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
3329         ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation);
3330     }
3331 
3332     @Override
finishHeavyWeightApp()3333     public final void finishHeavyWeightApp() {
3334         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3335                 != PackageManager.PERMISSION_GRANTED) {
3336             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3337                     + Binder.getCallingPid()
3338                     + ", uid=" + Binder.getCallingUid()
3339                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3340             Slog.w(TAG, msg);
3341             throw new SecurityException(msg);
3342         }
3343         mAtmInternal.finishHeavyWeightApp();
3344     }
3345 
3346     @Override
crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)3347     public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId,
3348             String message, boolean force, int exceptionTypeId) {
3349         crashApplicationWithTypeWithExtras(uid, initialPid, packageName, userId, message,
3350                 force, exceptionTypeId, null);
3351     }
3352 
3353     @Override
crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId, @Nullable Bundle extras)3354     public void crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName,
3355             int userId, String message, boolean force, int exceptionTypeId,
3356             @Nullable Bundle extras) {
3357         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3358                 != PackageManager.PERMISSION_GRANTED) {
3359             String msg = "Permission Denial: crashApplication() from pid="
3360                     + Binder.getCallingPid()
3361                     + ", uid=" + Binder.getCallingUid()
3362                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3363             Slog.w(TAG, msg);
3364             throw new SecurityException(msg);
3365         }
3366 
3367         synchronized(this) {
3368             mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId,
3369                     message, force, exceptionTypeId, extras);
3370         }
3371     }
3372 
3373     /**
3374      * Main function for removing an existing process from the activity manager
3375      * as a result of that process going away.  Clears out all connections
3376      * to the process.
3377      */
3378     @GuardedBy("this")
handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3379     final void handleAppDiedLocked(ProcessRecord app, int pid,
3380             boolean restarting, boolean allowRestart, boolean fromBinderDied) {
3381         boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1,
3382                 false /*replacingPid*/, fromBinderDied);
3383         if (!kept && !restarting) {
3384             removeLruProcessLocked(app);
3385             if (pid > 0) {
3386                 ProcessList.remove(pid);
3387             }
3388         }
3389 
3390         mAppProfiler.onAppDiedLocked(app);
3391 
3392         mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
3393             Slog.w(TAG, "Crash of app " + app.processName
3394                     + " running instrumentation " + app.getActiveInstrumentation().mClass);
3395             Bundle info = new Bundle();
3396             info.putString("shortMsg", "Process crashed.");
3397             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3398         });
3399     }
3400 
3401     @GuardedBy(anyOf = {"this", "mProcLock"})
getRecordForAppLOSP(IApplicationThread thread)3402     ProcessRecord getRecordForAppLOSP(IApplicationThread thread) {
3403         if (thread == null) {
3404             return null;
3405         }
3406         return getRecordForAppLOSP(thread.asBinder());
3407     }
3408 
3409     @GuardedBy(anyOf = {"this", "mProcLock"})
getRecordForAppLOSP(IBinder threadBinder)3410     ProcessRecord getRecordForAppLOSP(IBinder threadBinder) {
3411         if (threadBinder == null) {
3412             return null;
3413         }
3414 
3415         ProcessRecord record = mProcessList.getLRURecordForAppLOSP(threadBinder);
3416         if (record != null) return record;
3417 
3418         // Validation: if it isn't in the LRU list, it shouldn't exist, but let's double-check that.
3419         final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
3420                 mProcessList.getProcessNamesLOSP().getMap();
3421         for (int i = pmap.size()-1; i >= 0; i--) {
3422             final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
3423             for (int j = procs.size()-1; j >= 0; j--) {
3424                 final ProcessRecord proc = procs.valueAt(j);
3425                 final IApplicationThread procThread = proc.getThread();
3426                 if (procThread != null && procThread.asBinder() == threadBinder) {
3427                     if (!proc.isPendingFinishAttach()) {
3428                         Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
3429                                 + proc);
3430                     }
3431                     return proc;
3432                 }
3433             }
3434         }
3435 
3436         return null;
3437     }
3438 
3439     @GuardedBy("this")
appDiedLocked(ProcessRecord app, String reason)3440     final void appDiedLocked(ProcessRecord app, String reason) {
3441         appDiedLocked(app, app.getPid(), app.getThread(), false, reason);
3442     }
3443 
3444     @GuardedBy("this")
appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3445     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
3446             boolean fromBinderDied, String reason) {
3447         // First check if this ProcessRecord is actually active for the pid.
3448         final ProcessRecord curProc;
3449         synchronized (mPidsSelfLocked) {
3450             curProc = mPidsSelfLocked.get(pid);
3451         }
3452         if (curProc != app) {
3453             if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) {
3454                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
3455             }
3456             return;
3457         }
3458 
3459         mBatteryStatsService.noteProcessDied(app.info.uid, pid);
3460 
3461         if (!app.isKilled()) {
3462             if (!fromBinderDied) {
3463                 killProcessQuiet(pid);
3464                 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER,
3465                         ApplicationExitInfo.SUBREASON_UNKNOWN, reason);
3466             }
3467             app.killProcessGroupIfNecessaryLocked(true);
3468             synchronized (mProcLock) {
3469                 app.setKilled(true);
3470             }
3471         }
3472 
3473         // Clean up already done if the process has been re-started.
3474         IApplicationThread appThread;
3475         final int setAdj = app.mState.getSetAdj();
3476         final int setProcState = app.mState.getSetProcState();
3477         if (app.getPid() == pid && (appThread = app.getThread()) != null
3478                 && appThread.asBinder() == thread.asBinder()) {
3479             boolean doLowMem = app.getActiveInstrumentation() == null;
3480             boolean doOomAdj = doLowMem;
3481             if (!app.isKilledByAm()) {
3482                 reportUidInfoMessageLocked(TAG,
3483                         "Process " + app.processName + " (pid " + pid + ") has died: "
3484                         + ProcessList.makeOomAdjString(setAdj, true) + " "
3485                         + ProcessList.makeProcStateString(setProcState), app.info.uid);
3486                 mAppProfiler.setAllowLowerMemLevelLocked(true);
3487             } else {
3488                 // Note that we always want to do oom adj to update our state with the
3489                 // new number of procs.
3490                 mAppProfiler.setAllowLowerMemLevelLocked(false);
3491                 doLowMem = false;
3492             }
3493             EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState);
3494             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3495                 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
3496             handleAppDiedLocked(app, pid, false, true, fromBinderDied);
3497 
3498             if (doOomAdj) {
3499                 updateOomAdjLocked(OOM_ADJ_REASON_PROCESS_END);
3500             }
3501             if (doLowMem) {
3502                 mAppProfiler.doLowMemReportIfNeededLocked(app);
3503             }
3504         } else if (app.getPid() != pid) {
3505             // A new process has already been started.
3506             reportUidInfoMessageLocked(TAG,
3507                     "Process " + app.processName + " (pid " + pid
3508                             + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid);
3509 
3510             EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName,
3511                     setAdj, setProcState);
3512         } else if (DEBUG_PROCESSES) {
3513             Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
3514                     + thread.asBinder());
3515         }
3516 
3517         // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal
3518         // for pulling memory stats of other running processes when this process died.
3519         if (!hasMemcg()) {
3520             FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime());
3521         }
3522     }
3523 
3524     @Override
clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3525     public boolean clearApplicationUserData(final String packageName, boolean keepState,
3526             final IPackageDataObserver observer, int userId) {
3527         return clearApplicationUserData(packageName, keepState, /*isRestore=*/ false, observer,
3528                 userId);
3529     }
3530 
clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)3531     private boolean clearApplicationUserData(final String packageName, boolean keepState,
3532             boolean isRestore, final IPackageDataObserver observer, int userId) {
3533         enforceNotIsolatedCaller("clearApplicationUserData");
3534         int uid = Binder.getCallingUid();
3535         int pid = Binder.getCallingPid();
3536         final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false,
3537                 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
3538 
3539         final ApplicationInfo appInfo;
3540         final boolean isInstantApp;
3541 
3542         final long callingId = Binder.clearCallingIdentity();
3543         try {
3544             IPackageManager pm = AppGlobals.getPackageManager();
3545             boolean permitted = true;
3546             // Instant packages are not protected
3547             if (getPackageManagerInternal().isPackageDataProtected(
3548                     resolvedUserId, packageName)) {
3549                 if (ActivityManager.checkUidPermission(android.Manifest.permission.MANAGE_USERS,
3550                         uid) == PERMISSION_GRANTED) {
3551                     // The caller has the MANAGE_USERS permission, tell them what's going on.
3552                     throw new SecurityException(
3553                             "Cannot clear data for a protected package: " + packageName);
3554                 } else {
3555                     permitted = false; // fall through and throw the SecurityException below.
3556                 }
3557             }
3558 
3559             ApplicationInfo applicationInfo = null;
3560             if (permitted) {
3561                 try {
3562                     applicationInfo = pm.getApplicationInfo(packageName,
3563                             MATCH_UNINSTALLED_PACKAGES, resolvedUserId);
3564                 } catch (RemoteException e) {
3565                     /* ignore */
3566                 }
3567                 permitted = (applicationInfo != null && applicationInfo.uid == uid) // own uid data
3568                         || (checkComponentPermission(permission.CLEAR_APP_USER_DATA,
3569                                 pid, uid, -1, true) == PackageManager.PERMISSION_GRANTED);
3570             }
3571 
3572             if (!permitted) {
3573                 throw new SecurityException("PID " + pid + " does not have permission "
3574                         + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
3575                         + " of package " + packageName);
3576             }
3577             appInfo = applicationInfo;
3578 
3579             final boolean hasInstantMetadata = getPackageManagerInternal()
3580                     .hasInstantApplicationMetadata(packageName, resolvedUserId);
3581             final boolean isUninstalledAppWithoutInstantMetadata =
3582                     (appInfo == null && !hasInstantMetadata);
3583             isInstantApp = (appInfo != null && appInfo.isInstantApp())
3584                     || hasInstantMetadata;
3585             final boolean canAccessInstantApps = checkComponentPermission(
3586                     permission.ACCESS_INSTANT_APPS, pid, uid, -1, true)
3587                     == PackageManager.PERMISSION_GRANTED;
3588 
3589             if (isUninstalledAppWithoutInstantMetadata || (isInstantApp
3590                         && !canAccessInstantApps)) {
3591                 Slog.w(TAG, "Invalid packageName: " + packageName);
3592                 if (observer != null) {
3593                     try {
3594                         observer.onRemoveCompleted(packageName, false);
3595                     } catch (RemoteException e) {
3596                         Slog.i(TAG, "Observer no longer exists.");
3597                     }
3598                 }
3599                 return false;
3600             }
3601 
3602             synchronized (this) {
3603                 if (appInfo != null) {
3604                     forceStopPackageLocked(packageName, appInfo.uid, "clear data");
3605                     mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId);
3606                 }
3607             }
3608 
3609             final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
3610                 @Override
3611                 public void onRemoveCompleted(String packageName, boolean succeeded)
3612                         throws RemoteException {
3613                     if (appInfo != null) {
3614                         synchronized (ActivityManagerService.this) {
3615                             finishForceStopPackageLocked(packageName, appInfo.uid);
3616                         }
3617                     }
3618 
3619                     if (succeeded) {
3620                         final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3621                                 Uri.fromParts("package", packageName, null /* fragment */));
3622                         intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3623                                 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3624                         intent.putExtra(Intent.EXTRA_UID,
3625                                 (appInfo != null) ? appInfo.uid : INVALID_UID);
3626                         intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId);
3627                         if (isRestore) {
3628                             intent.putExtra(Intent.EXTRA_IS_RESTORE, true);
3629                         }
3630                         if (isInstantApp) {
3631                             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
3632                         }
3633                         final int[] visibilityAllowList = mPackageManagerInt.getVisibilityAllowList(
3634                                 packageName, resolvedUserId);
3635 
3636                         broadcastIntentInPackage("android", null /* featureId */,
3637                                 SYSTEM_UID, uid, pid, intent, null /* resolvedType */,
3638                                 null /* resultToApp */, null /* resultTo */, 0 /* resultCode */,
3639                                 null /* resultData */, null /* resultExtras */,
3640                                 isInstantApp ? permission.ACCESS_INSTANT_APPS : null,
3641                                 null /* bOptions */, false /* serialized */, false /* sticky */,
3642                                 resolvedUserId, BackgroundStartPrivileges.NONE,
3643                                 visibilityAllowList);
3644                     }
3645 
3646                     if (observer != null) {
3647                         observer.onRemoveCompleted(packageName, succeeded);
3648                     }
3649                 }
3650             };
3651 
3652             try {
3653                 // Clear application user data
3654                 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId);
3655 
3656                 if (appInfo != null) {
3657                     // Restore already established notification state and permission grants,
3658                     // so it told us to keep those intact -- it's about to emplace app data
3659                     // that is appropriate for those bits of system state.
3660                     if (!keepState) {
3661                         // Remove all permissions granted from/to this package
3662                         mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId,
3663                                 true, false);
3664 
3665                         // Reset notification state
3666                         INotificationManager inm = NotificationManager.getService();
3667                         inm.clearData(packageName, appInfo.uid, uid == appInfo.uid);
3668                     }
3669 
3670                     // Clear its scheduled jobs
3671                     JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
3672                     // Clearing data is a user-initiated action.
3673                     js.cancelJobsForUid(appInfo.uid, /* includeProxiedJobs */ true,
3674                             JobParameters.STOP_REASON_USER,
3675                             JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data");
3676 
3677                     // Clear its pending alarms
3678                     AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class);
3679                     ami.removeAlarmsForUid(appInfo.uid);
3680                 }
3681             } catch (RemoteException e) {
3682             }
3683         } finally {
3684             Binder.restoreCallingIdentity(callingId);
3685         }
3686         return true;
3687     }
3688 
3689     @Override
killBackgroundProcesses(final String packageName, int userId)3690     public void killBackgroundProcesses(final String packageName, int userId) {
3691         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3692                 != PackageManager.PERMISSION_GRANTED &&
3693                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3694                         != PackageManager.PERMISSION_GRANTED) {
3695             String msg = "Permission Denial: killBackgroundProcesses() from pid="
3696                     + Binder.getCallingPid()
3697                     + ", uid=" + Binder.getCallingUid()
3698                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3699             Slog.w(TAG, msg);
3700             throw new SecurityException(msg);
3701         }
3702         final boolean hasKillAllPermission = checkCallingPermission(
3703                 android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES) == PERMISSION_GRANTED;
3704         final int callingUid = Binder.getCallingUid();
3705         final int callingAppId = UserHandle.getAppId(callingUid);
3706 
3707         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid,
3708                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
3709         final int[] userIds = mUserController.expandUserId(userId);
3710 
3711         final long callingId = Binder.clearCallingIdentity();
3712         try {
3713             IPackageManager pm = AppGlobals.getPackageManager();
3714             for (int targetUserId : userIds) {
3715                 int appId = -1;
3716                 try {
3717                     appId = UserHandle.getAppId(
3718                             pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
3719                                     targetUserId));
3720                 } catch (RemoteException e) {
3721                 }
3722                 if (appId == -1 || (!hasKillAllPermission && appId != callingAppId)) {
3723                     Slog.w(TAG, "Invalid packageName: " + packageName);
3724                     return;
3725                 }
3726                 synchronized (this) {
3727                     synchronized (mProcLock) {
3728                         mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId,
3729                                 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED,
3730                                 ApplicationExitInfo.SUBREASON_KILL_BACKGROUND, "kill background");
3731                     }
3732                 }
3733             }
3734         } finally {
3735             Binder.restoreCallingIdentity(callingId);
3736         }
3737     }
3738 
3739     @Override
killAllBackgroundProcesses()3740     public void killAllBackgroundProcesses() {
3741         if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES)
3742                 != PackageManager.PERMISSION_GRANTED) {
3743             final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3744                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3745                     + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES;
3746             Slog.w(TAG, msg);
3747             throw new SecurityException(msg);
3748         }
3749 
3750         final long callingId = Binder.clearCallingIdentity();
3751         try {
3752             synchronized (this) {
3753                 // Allow memory level to go down (the flag needs to be set before updating oom adj)
3754                 // because this method is also used to simulate low memory.
3755                 mAppProfiler.setAllowLowerMemLevelLocked(true);
3756                 synchronized (mProcLock) {
3757                     mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */,
3758                             UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ,
3759                             ApplicationExitInfo.REASON_USER_REQUESTED,
3760                             ApplicationExitInfo.SUBREASON_KILL_BACKGROUND,
3761                             "kill all background");
3762                 }
3763 
3764                 mAppProfiler.doLowMemReportIfNeededLocked(null);
3765             }
3766         } finally {
3767             Binder.restoreCallingIdentity(callingId);
3768         }
3769     }
3770 
3771     /**
3772      * Kills all background processes, except those matching any of the
3773      * specified properties.
3774      *
3775      * @param minTargetSdk the target SDK version at or above which to preserve
3776      *                     processes, or {@code -1} to ignore the target SDK
3777      * @param maxProcState the process state at or below which to preserve
3778      *                     processes, or {@code -1} to ignore the process state
3779      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3780     void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
3781         if (checkCallingPermission(android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES)
3782                 != PackageManager.PERMISSION_GRANTED) {
3783             final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
3784                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3785                     + " requires " + android.Manifest.permission.KILL_ALL_BACKGROUND_PROCESSES;
3786             Slog.w(TAG, msg);
3787             throw new SecurityException(msg);
3788         }
3789 
3790         final long callingId = Binder.clearCallingIdentity();
3791         try {
3792             synchronized (this) {
3793                 synchronized (mProcLock) {
3794                     mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState);
3795                 }
3796             }
3797         } finally {
3798             Binder.restoreCallingIdentity(callingId);
3799         }
3800     }
3801 
3802     @Override
stopAppForUser(final String packageName, int userId)3803     public void stopAppForUser(final String packageName, int userId) {
3804         if (checkCallingPermission(MANAGE_ACTIVITY_TASKS)
3805                 != PackageManager.PERMISSION_GRANTED) {
3806             String msg = "Permission Denial: stopAppForUser() from pid="
3807                     + Binder.getCallingPid()
3808                     + ", uid=" + Binder.getCallingUid()
3809                     + " requires " + MANAGE_ACTIVITY_TASKS;
3810             Slog.w(TAG, msg);
3811             throw new SecurityException(msg);
3812         }
3813 
3814         final int callingPid = Binder.getCallingPid();
3815         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
3816                 userId, true, ALLOW_FULL_ONLY, "stopAppForUser", null);
3817         final long callingId = Binder.clearCallingIdentity();
3818         try {
3819             stopAppForUserInternal(packageName, userId);
3820         } finally {
3821             Binder.restoreCallingIdentity(callingId);
3822         }
3823     }
3824 
3825     @Override
registerForegroundServiceObserver(IForegroundServiceObserver callback)3826     public boolean registerForegroundServiceObserver(IForegroundServiceObserver callback) {
3827         final int callingUid = Binder.getCallingUid();
3828         final int permActivityTasks = checkCallingPermission(MANAGE_ACTIVITY_TASKS);
3829         final int permAcrossUsersFull = checkCallingPermission(INTERACT_ACROSS_USERS_FULL);
3830         if (permActivityTasks != PackageManager.PERMISSION_GRANTED
3831                 || permAcrossUsersFull != PERMISSION_GRANTED) {
3832             String msg = "Permission Denial: registerForegroundServiceObserver() from pid="
3833                     + Binder.getCallingPid()
3834                     + ", uid=" + callingUid
3835                     + " requires " + MANAGE_ACTIVITY_TASKS
3836                     + " and " + INTERACT_ACROSS_USERS_FULL;
3837             Slog.w(TAG, msg);
3838             throw new SecurityException(msg);
3839         }
3840 
3841         synchronized (this) {
3842             return mServices.registerForegroundServiceObserverLocked(callingUid, callback);
3843         }
3844     }
3845 
3846     @Override
forceStopPackage(final String packageName, int userId)3847     public void forceStopPackage(final String packageName, int userId) {
3848         forceStopPackage(packageName, userId, /*flags=*/ 0);
3849     }
3850 
3851     @Override
forceStopPackageEvenWhenStopping(final String packageName, int userId)3852     public void forceStopPackageEvenWhenStopping(final String packageName, int userId) {
3853         forceStopPackage(packageName, userId, ActivityManager.FLAG_OR_STOPPED);
3854     }
3855 
forceStopPackage(final String packageName, int userId, int userRunningFlags)3856     private void forceStopPackage(final String packageName, int userId, int userRunningFlags) {
3857         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3858                 != PackageManager.PERMISSION_GRANTED) {
3859             String msg = "Permission Denial: forceStopPackage() from pid="
3860                     + Binder.getCallingPid()
3861                     + ", uid=" + Binder.getCallingUid()
3862                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3863             Slog.w(TAG, msg);
3864             throw new SecurityException(msg);
3865         }
3866         final int callingPid = Binder.getCallingPid();
3867         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
3868                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
3869         final long callingId = Binder.clearCallingIdentity();
3870         try {
3871             IPackageManager pm = AppGlobals.getPackageManager();
3872             synchronized (this) {
3873                 int[] users = userId == UserHandle.USER_ALL
3874                         ? mUserController.getUsers() : new int[] { userId };
3875                 for (int user : users) {
3876                     if (getPackageManagerInternal().isPackageStateProtected(
3877                             packageName, user)) {
3878                         Slog.w(TAG, "Ignoring request to force stop protected package "
3879                                 + packageName + " u" + user);
3880                         return;
3881                     }
3882 
3883                     int pkgUid = -1;
3884                     try {
3885                         pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
3886                                 user);
3887                     } catch (RemoteException e) {
3888                     }
3889                     if (pkgUid == -1) {
3890                         Slog.w(TAG, "Invalid packageName: " + packageName);
3891                         continue;
3892                     }
3893                     try {
3894                         pm.setPackageStoppedState(packageName, true, user);
3895                     } catch (RemoteException e) {
3896                     } catch (IllegalArgumentException e) {
3897                         Slog.w(TAG, "Failed trying to unstop package "
3898                                 + packageName + ": " + e);
3899                     }
3900                     if (mUserController.isUserRunning(user, userRunningFlags)) {
3901                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
3902                         finishForceStopPackageLocked(packageName, pkgUid);
3903                     }
3904                 }
3905             }
3906         } finally {
3907             Binder.restoreCallingIdentity(callingId);
3908         }
3909     }
3910 
3911     @Override
addPackageDependency(String packageName)3912     public void addPackageDependency(String packageName) {
3913         int callingPid = Binder.getCallingPid();
3914         if (callingPid == myPid()) {
3915             //  Yeah, um, no.
3916             return;
3917         }
3918         final int callingUid = Binder.getCallingUid();
3919         final int callingUserId = UserHandle.getUserId(callingUid);
3920         if (getPackageManagerInternal().filterAppAccess(packageName, callingUid, callingUserId)) {
3921             Slog.w(TAG, "Failed trying to add dependency on non-existing package: " + packageName);
3922             return;
3923         }
3924         ProcessRecord proc;
3925         synchronized (mPidsSelfLocked) {
3926             proc = mPidsSelfLocked.get(Binder.getCallingPid());
3927         }
3928         if (proc != null) {
3929             ArraySet<String> pkgDeps = proc.getPkgDeps();
3930             synchronized (this) {
3931                 synchronized (mProcLock) {
3932                     if (pkgDeps == null) {
3933                         proc.setPkgDeps(pkgDeps = new ArraySet<String>(1));
3934                     }
3935                     pkgDeps.add(packageName);
3936                 }
3937             }
3938         }
3939     }
3940 
3941     /*
3942      * The pkg name and app id have to be specified.
3943      */
3944     @Override
killApplication(String pkg, int appId, int userId, String reason, int exitInfoReason)3945     public void killApplication(String pkg, int appId, int userId, String reason,
3946             int exitInfoReason) {
3947         if (pkg == null) {
3948             return;
3949         }
3950         // Make sure the uid is valid.
3951         if (appId < 0) {
3952             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
3953             return;
3954         }
3955         int callerUid = Binder.getCallingUid();
3956         // Only the system server can kill an application
3957         if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
3958             // Post an aysnc message to kill the application
3959             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3960             msg.arg1 = appId;
3961             msg.arg2 = userId;
3962             SomeArgs args = SomeArgs.obtain();
3963             args.arg1 = pkg;
3964             args.arg2 = reason;
3965             args.arg3 = exitInfoReason;
3966             msg.obj = args;
3967             mHandler.sendMessage(msg);
3968         } else {
3969             throw new SecurityException(callerUid + " cannot kill pkg: " +
3970                     pkg);
3971         }
3972     }
3973 
3974     @Override
closeSystemDialogs(String reason)3975     public void closeSystemDialogs(String reason) {
3976         mAtmInternal.closeSystemDialogs(reason);
3977     }
3978 
3979     @Override
getProcessMemoryInfo(int[] pids)3980     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3981         enforceNotIsolatedCaller("getProcessMemoryInfo");
3982 
3983         final long now = SystemClock.uptimeMillis();
3984         final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME;
3985 
3986         final int callingPid = Binder.getCallingPid();
3987         final int callingUid = Binder.getCallingUid();
3988         final int callingUserId = UserHandle.getUserId(callingUid);
3989         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
3990                 callingUid) == PackageManager.PERMISSION_GRANTED;
3991         // Check REAL_GET_TASKS to see if they are allowed to access other uids
3992         final boolean allUids = mAtmInternal.isGetTasksAllowed(
3993                 "getProcessMemoryInfo", callingPid, callingUid);
3994 
3995         // Check if the caller is actually instrumented and from shell, if it's true, we may lift
3996         // the throttle of PSS info sampling.
3997         boolean isCallerInstrumentedFromShell = false;
3998         synchronized (mProcLock) {
3999             synchronized (mPidsSelfLocked) {
4000                 ProcessRecord caller = mPidsSelfLocked.get(callingPid);
4001                 if (caller != null) {
4002                     final ActiveInstrumentation instr = caller.getActiveInstrumentation();
4003                     isCallerInstrumentedFromShell = instr != null
4004                             && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID);
4005                 }
4006             }
4007         }
4008 
4009         final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4010         for (int i=pids.length-1; i>=0; i--) {
4011             final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo();
4012             final ProcessRecord proc;
4013             final int oomAdj;
4014             final ProcessProfileRecord profile;
4015             synchronized (mAppProfiler.mProfilerLock) {
4016                 synchronized (mPidsSelfLocked) {
4017                     proc = mPidsSelfLocked.get(pids[i]);
4018                     if (proc != null) {
4019                         profile = proc.mProfile;
4020                         oomAdj = profile.getSetAdj();
4021                     } else {
4022                         profile = null;
4023                         oomAdj = 0;
4024                     }
4025                 }
4026             }
4027             final int targetUid = (proc != null) ? proc.uid : -1;
4028             final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1;
4029 
4030             if (callingUid != targetUid) {
4031                 if (!allUids) {
4032                     continue; // Not allowed to see other UIDs.
4033                 }
4034 
4035                 if (!allUsers && (targetUserId != callingUserId)) {
4036                     continue; // Not allowed to see other users.
4037                 }
4038             }
4039             if (proc != null) {
4040                 synchronized (mAppProfiler.mProfilerLock) {
4041                     if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null
4042                             && !isCallerInstrumentedFromShell) {
4043                         // It hasn't been long enough that we want to take another sample; return
4044                         // the last one.
4045                         mi.set(profile.getLastMemInfo());
4046                         continue;
4047                     }
4048                 }
4049             }
4050             final long startTime = SystemClock.currentThreadTimeMillis();
4051             final Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
4052             Debug.getMemoryInfo(pids[i], memInfo);
4053             final long duration = SystemClock.currentThreadTimeMillis() - startTime;
4054             mi.set(memInfo);
4055             if (proc != null) {
4056                 synchronized (mAppProfiler.mProfilerLock) {
4057                     profile.setLastMemInfo(memInfo);
4058                     profile.setLastMemInfoTime(SystemClock.uptimeMillis());
4059                     if (profile.getThread() != null && profile.getSetAdj() == oomAdj) {
4060                         // Record this for posterity if the process has been stable.
4061                         profile.addPss(mi.getTotalPss(),
4062                                 mi.getTotalUss(), mi.getTotalRss(), false,
4063                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration);
4064                         proc.getPkgList().forEachPackageProcessStats(holder -> {
4065                             final ProcessState state = holder.state;
4066                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
4067                                     proc.info.uid,
4068                                     state != null ? state.getName() : proc.processName,
4069                                     state != null ? state.getPackage() : proc.info.packageName,
4070                                     mi.getTotalPss(),
4071                                     mi.getTotalUss(),
4072                                     mi.getTotalRss(),
4073                                     ProcessStats.ADD_PSS_EXTERNAL_SLOW,
4074                                     duration,
4075                                     holder.appVersion,
4076                                     profile.getCurrentHostingComponentTypes(),
4077                                     profile.getHistoricalHostingComponentTypes());
4078                         });
4079                     }
4080                 }
4081             }
4082         }
4083         return infos;
4084     }
4085 
4086     @Override
getProcessPss(int[] pids)4087     public long[] getProcessPss(int[] pids) {
4088         enforceNotIsolatedCaller("getProcessPss");
4089 
4090         final int callingPid = Binder.getCallingPid();
4091         final int callingUid = Binder.getCallingUid();
4092         final int userId = UserHandle.getUserId(callingUid);
4093         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4094                 callingUid) == PackageManager.PERMISSION_GRANTED;
4095         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4096         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4097                 "getProcessPss", callingPid, callingUid);
4098 
4099         final long[] pss = new long[pids.length];
4100         for (int i=pids.length-1; i>=0; i--) {
4101             ProcessRecord proc;
4102             int oomAdj;
4103             synchronized (mProcLock) {
4104                 synchronized (mPidsSelfLocked) {
4105                     proc = mPidsSelfLocked.get(pids[i]);
4106                     oomAdj = proc != null ? proc.mState.getSetAdj() : 0;
4107                 }
4108             }
4109             if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) {
4110                 // The caller is not allow to get information about this other process...
4111                 // just leave it empty.
4112                 continue;
4113             }
4114             final long[] tmpUss = new long[3];
4115             final long startTime = SystemClock.currentThreadTimeMillis();
4116             final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null);
4117             final long duration = SystemClock.currentThreadTimeMillis() - startTime;
4118             if (proc != null) {
4119                 final ProcessProfileRecord profile = proc.mProfile;
4120                 synchronized (mAppProfiler.mProfilerLock) {
4121                     if (profile.getThread() != null && profile.getSetAdj() == oomAdj) {
4122                         // Record this for posterity if the process has been stable.
4123                         profile.addPss(pi, tmpUss[0], tmpUss[2], false,
4124                                 ProcessStats.ADD_PSS_EXTERNAL, duration);
4125                         proc.getPkgList().forEachPackageProcessStats(holder -> {
4126                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
4127                                     proc.info.uid,
4128                                     holder.state.getName(),
4129                                     holder.state.getPackage(),
4130                                     pi,
4131                                     tmpUss[0],
4132                                     tmpUss[2],
4133                                     ProcessStats.ADD_PSS_EXTERNAL,
4134                                     duration,
4135                                     holder.appVersion,
4136                                     profile.getCurrentHostingComponentTypes(),
4137                                     profile.getHistoricalHostingComponentTypes());
4138                         });
4139                     }
4140                 }
4141             }
4142         }
4143         return pss;
4144     }
4145 
4146     @Override
killApplicationProcess(String processName, int uid)4147     public void killApplicationProcess(String processName, int uid) {
4148         if (processName == null) {
4149             return;
4150         }
4151 
4152         int callerUid = Binder.getCallingUid();
4153         // Only the system server can kill an application
4154         if (callerUid == SYSTEM_UID) {
4155             synchronized (this) {
4156                 ProcessRecord app = getProcessRecordLocked(processName, uid);
4157                 IApplicationThread thread;
4158                 if (app != null && (thread = app.getThread()) != null) {
4159                     try {
4160                         thread.scheduleSuicide();
4161                     } catch (RemoteException e) {
4162                         // If the other end already died, then our work here is done.
4163                     }
4164                 } else {
4165                     Slog.w(TAG, "Process/uid not found attempting kill of "
4166                             + processName + " / " + uid);
4167                 }
4168             }
4169         } else {
4170             throw new SecurityException(callerUid + " cannot kill app process: " +
4171                     processName);
4172         }
4173     }
4174 
4175     @GuardedBy("this")
forceStopPackageLocked(final String packageName, int uid, String reason)4176     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
4177         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
4178                 false, true, false, false, UserHandle.getUserId(uid), reason);
4179     }
4180 
4181     @GuardedBy("this")
finishForceStopPackageLocked(final String packageName, int uid)4182     private void finishForceStopPackageLocked(final String packageName, int uid) {
4183         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4184                 Uri.fromParts("package", packageName, null));
4185         if (!mProcessesReady) {
4186             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4187                     | Intent.FLAG_RECEIVER_FOREGROUND);
4188         }
4189         final int userId = UserHandle.getUserId(uid);
4190         final int[] broadcastAllowList =
4191                 getPackageManagerInternal().getVisibilityAllowList(packageName, userId);
4192         intent.putExtra(Intent.EXTRA_UID, uid);
4193         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4194         broadcastIntentLocked(null /* callerApp */, null /* callerPackage */,
4195                 null /* callerFeatureId */, intent, null /* resolvedType */,
4196                 null /* resultToApp */, null /* resultTo */,
4197                 0 /* resultCode */, null /* resultData */, null /* resultExtras */,
4198                 null /* requiredPermissions */, null /* excludedPermissions */,
4199                 null /* excludedPackages */, OP_NONE, null /* bOptions */, false /* ordered */,
4200                 false /* sticky */, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
4201                 Binder.getCallingPid(), userId, BackgroundStartPrivileges.NONE,
4202                 broadcastAllowList, null /* filterExtrasForReceiver */);
4203     }
4204 
cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4205     private void cleanupDisabledPackageComponentsLocked(
4206             String packageName, int userId, String[] changedClasses) {
4207 
4208         Set<String> disabledClasses = null;
4209         boolean packageDisabled = false;
4210         IPackageManager pm = AppGlobals.getPackageManager();
4211 
4212         if (changedClasses == null) {
4213             // Nothing changed...
4214             return;
4215         }
4216 
4217         // Determine enable/disable state of the package and its components.
4218         int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4219         for (int i = changedClasses.length - 1; i >= 0; i--) {
4220             final String changedClass = changedClasses[i];
4221 
4222             if (changedClass.equals(packageName)) {
4223                 try {
4224                     // Entire package setting changed
4225                     enabled = pm.getApplicationEnabledSetting(packageName,
4226                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4227                 } catch (Exception e) {
4228                     // No such package/component; probably racing with uninstall.  In any
4229                     // event it means we have nothing further to do here.
4230                     return;
4231                 }
4232                 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4233                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4234                 if (packageDisabled) {
4235                     // Entire package is disabled.
4236                     // No need to continue to check component states.
4237                     disabledClasses = null;
4238                     break;
4239                 }
4240             } else {
4241                 try {
4242                     enabled = pm.getComponentEnabledSetting(
4243                             new ComponentName(packageName, changedClass),
4244                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4245                 } catch (Exception e) {
4246                     // As above, probably racing with uninstall.
4247                     return;
4248                 }
4249                 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4250                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
4251                     if (disabledClasses == null) {
4252                         disabledClasses = new ArraySet<>(changedClasses.length);
4253                     }
4254                     disabledClasses.add(changedClass);
4255                 }
4256             }
4257         }
4258 
4259         if (!packageDisabled && disabledClasses == null) {
4260             // Nothing to do here...
4261             return;
4262         }
4263 
4264         mAtmInternal.cleanupDisabledPackageComponents(
4265                 packageName, disabledClasses, userId, mBooted);
4266 
4267         // Clean-up disabled services.
4268         mServices.bringDownDisabledPackageServicesLocked(
4269                 packageName, disabledClasses, userId, false /* evenPersistent */,
4270                 false /* fullStop */, true /* doIt */);
4271 
4272         // Clean-up disabled providers.
4273         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4274         mCpHelper.getProviderMap().collectPackageProvidersLocked(
4275                 packageName, disabledClasses, true, false, userId, providers);
4276         for (int i = providers.size() - 1; i >= 0; i--) {
4277             mCpHelper.removeDyingProviderLocked(null, providers.get(i), true);
4278         }
4279 
4280         // Clean-up disabled broadcast receivers.
4281         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4282             mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4283                     packageName, disabledClasses, userId);
4284         }
4285 
4286     }
4287 
clearBroadcastQueueForUserLocked(int userId)4288     final boolean clearBroadcastQueueForUserLocked(int userId) {
4289         boolean didSomething = false;
4290         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4291             didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4292                     null, null, userId);
4293         }
4294         return didSomething;
4295     }
4296 
4297     @GuardedBy("this")
forceStopAppZygoteLocked(String packageName, int appId, int userId)4298     final void forceStopAppZygoteLocked(String packageName, int appId, int userId) {
4299         if (packageName == null) {
4300             return;
4301         }
4302         if (appId < 0) {
4303             appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName,
4304                     MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM));
4305         }
4306 
4307         mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */);
4308     }
4309 
stopAppForUserInternal(final String packageName, @UserIdInt final int userId)4310     void stopAppForUserInternal(final String packageName, @UserIdInt final int userId) {
4311         final int uid = getPackageManagerInternal().getPackageUid(packageName,
4312                 MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, userId);
4313         if (uid < 0) {
4314             Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId
4315                     + " but does not exist in that user");
4316             return;
4317         }
4318 
4319         // Policy: certain classes of app are not subject to user-invoked stop
4320         if (getPackageManagerInternal().isPackageStateProtected(packageName, userId)) {
4321             Slog.w(TAG, "Asked to stop " + packageName + "/u" + userId
4322                     + " but it is protected");
4323             return;
4324         }
4325 
4326         Slog.i(TAG, "Stopping app for user: " + packageName + "/" + userId);
4327 
4328         // A specific subset of the work done in forceStopPackageLocked(), because we are
4329         // intentionally not rendering the app nonfunctional; we're just halting its current
4330         // execution.
4331         final int appId = UserHandle.getAppId(uid);
4332         synchronized (this) {
4333             synchronized (mProcLock) {
4334                 mAtmInternal.onForceStopPackage(packageName, true, false, userId);
4335 
4336                 mProcessList.killPackageProcessesLSP(packageName, appId, userId,
4337                         ProcessList.INVALID_ADJ, true, false, true,
4338                         false, true /* setRemoved */, false,
4339                         ApplicationExitInfo.REASON_USER_REQUESTED,
4340                         ApplicationExitInfo.SUBREASON_STOP_APP,
4341                         "fully stop " + packageName + "/" + userId + " by user request");
4342             }
4343 
4344             mServices.bringDownDisabledPackageServicesLocked(
4345                     packageName, null, userId, false, true, true);
4346 
4347             if (mBooted) {
4348                 mAtmInternal.resumeTopActivities(true);
4349             }
4350         }
4351     }
4352 
4353     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reasonString)4354     final boolean forceStopPackageLocked(String packageName, int appId,
4355             boolean callerWillRestart, boolean purgeCache, boolean doit,
4356             boolean evenPersistent, boolean uninstalling, int userId, String reasonString) {
4357 
4358         int reason = packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED
4359                 : ApplicationExitInfo.REASON_USER_REQUESTED;
4360         return forceStopPackageLocked(packageName, appId, callerWillRestart, purgeCache, doit,
4361                 evenPersistent, uninstalling, userId, reasonString, reason);
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, int reason)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             int reason) {
4370         int i;
4371 
4372         if (userId == UserHandle.USER_ALL && packageName == null) {
4373             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
4374         }
4375 
4376         if (appId < 0 && packageName != null) {
4377             appId = UserHandle.getAppId(getPackageManagerInternal().getPackageUid(packageName,
4378                     MATCH_DEBUG_TRIAGED_MISSING | MATCH_ANY_USER, UserHandle.USER_SYSTEM));
4379         }
4380 
4381         boolean didSomething;
4382         if (doit) {
4383             if (packageName != null) {
4384                 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
4385                         + " user=" + userId + ": " + reasonString);
4386             } else {
4387                 Slog.i(TAG, "Force stopping u" + userId + ": " + reasonString);
4388             }
4389 
4390             mAppErrors.resetProcessCrashTime(packageName == null, appId, userId);
4391         }
4392 
4393         synchronized (mProcLock) {
4394             // Notify first that the package is stopped, so its process won't be restarted
4395             // unexpectedly if there is an activity of the package without attached process
4396             // becomes visible when killing its other processes with visible activities.
4397             didSomething = mAtmInternal.onForceStopPackage(
4398                     packageName, doit, evenPersistent, userId);
4399             int subReason;
4400             if (reason == ApplicationExitInfo.REASON_USER_REQUESTED) {
4401                 subReason = ApplicationExitInfo.SUBREASON_FORCE_STOP;
4402             } else {
4403                 subReason = ApplicationExitInfo.SUBREASON_UNKNOWN;
4404             }
4405 
4406             didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId,
4407                     ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit,
4408                     evenPersistent, true /* setRemoved */, uninstalling,
4409                     reason,
4410                     subReason,
4411                     (packageName == null ? ("stop user " + userId) : ("stop " + packageName))
4412                     + " due to " + reasonString);
4413         }
4414 
4415         if (mServices.bringDownDisabledPackageServicesLocked(
4416                 packageName, null /* filterByClasses */, userId, evenPersistent, true, doit)) {
4417             if (!doit) {
4418                 return true;
4419             }
4420             didSomething = true;
4421         }
4422 
4423         if (packageName == null) {
4424             // Remove all sticky broadcasts from this user.
4425             mStickyBroadcasts.remove(userId);
4426         }
4427 
4428         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4429         if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit,
4430                 evenPersistent, userId, providers)) {
4431             if (!doit) {
4432                 return true;
4433             }
4434             didSomething = true;
4435         }
4436         for (i = providers.size() - 1; i >= 0; i--) {
4437             mCpHelper.removeDyingProviderLocked(null, providers.get(i), true);
4438         }
4439 
4440         // Remove transient permissions granted from/to this package/user
4441         mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false);
4442 
4443         if (doit) {
4444             for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
4445                 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4446                         packageName, null, userId);
4447             }
4448         }
4449 
4450         if (packageName == null || uninstalling) {
4451             didSomething |= mPendingIntentController.removePendingIntentsForPackage(
4452                     packageName, userId, appId, doit);
4453         }
4454 
4455         if (doit) {
4456             if (purgeCache && packageName != null) {
4457                 AttributeCache ac = AttributeCache.instance();
4458                 if (ac != null) {
4459                     ac.removePackage(packageName);
4460                 }
4461             }
4462             if (mBooted) {
4463                 mAtmInternal.resumeTopActivities(true /* scheduleIdle */);
4464             }
4465         }
4466 
4467         return didSomething;
4468     }
4469 
4470     @GuardedBy("this")
handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout)4471     void handleProcessStartOrKillTimeoutLocked(ProcessRecord app, boolean isKillTimeout) {
4472         final int pid = app.getPid();
4473         boolean gone = isKillTimeout || removePidLocked(pid, app);
4474 
4475         if (gone) {
4476             if (isKillTimeout) {
4477                 // It's still alive... maybe blocked at uninterruptible sleep ?
4478                 final ProcessRecord successor = app.mSuccessor;
4479                 if (successor == null) {
4480                     // There might be a race, nothing to do here.
4481                     return;
4482                 }
4483                 Slog.wtf(TAG, app.toString() + " " + app.getDyingPid()
4484                         + " refused to die while trying to launch " + successor
4485                         + ", cancelling the process start");
4486 
4487                 // It doesn't make sense to proceed with launching the new instance while the old
4488                 // instance is still alive, abort the launch.
4489                 app.mSuccessorStartRunnable = null;
4490                 app.mSuccessor = null;
4491                 successor.mPredecessor = null;
4492 
4493                 // We're going to cleanup the successor process record, which wasn't started at all.
4494                 app = successor;
4495             } else {
4496                 final String msg = "Process " + app + " failed to attach";
4497                 Slog.w(TAG, msg);
4498                 EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName);
4499                 if (app.getActiveInstrumentation() != null) {
4500                     final Bundle info = new Bundle();
4501                     info.putString("shortMsg", "failed to attach");
4502                     info.putString("longMsg", msg);
4503                     finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4504                 }
4505             }
4506             synchronized (mProcLock) {
4507                 mProcessList.removeProcessNameLocked(app.processName, app.uid);
4508                 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
4509                 // Take care of any launching providers waiting for this process.
4510                 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true);
4511                 // Take care of any services that are waiting for the process.
4512                 mServices.processStartTimedOutLocked(app);
4513                 // Take care of any broadcasts waiting for the process.
4514                 for (BroadcastQueue queue : mBroadcastQueues) {
4515                     queue.onApplicationTimeoutLocked(app);
4516                 }
4517                 if (!isKillTimeout) {
4518                     mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
4519                     app.killLocked("start timeout",
4520                             ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
4521                     removeLruProcessLocked(app);
4522                 }
4523                 if (app.isolated) {
4524                     mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
4525                     mProcessList.mAppExitInfoTracker.mIsolatedUidRecords.removeIsolatedUid(
4526                             app.uid, app.info.uid);
4527                     getPackageManagerInternal().removeIsolatedUid(app.uid);
4528                 }
4529             }
4530             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4531             if (!isKillTimeout && backupTarget != null && backupTarget.app.getPid() == pid) {
4532                 Slog.w(TAG, "Unattached app died before backup, skipping");
4533                 final int userId = app.userId;
4534                 final String packageName = app.info.packageName;
4535                 mHandler.post(new Runnable() {
4536                 @Override
4537                     public void run() {
4538                         try {
4539                             IBackupManager bm = IBackupManager.Stub.asInterface(
4540                                     ServiceManager.getService(Context.BACKUP_SERVICE));
4541                             bm.agentDisconnectedForUser(userId, packageName);
4542                         } catch (RemoteException e) {
4543                             // Can't happen; the backup manager is local
4544                         }
4545                     }
4546                 });
4547             }
4548         } else {
4549             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
4550         }
4551     }
4552 
4553     @GuardedBy("this")
attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4554     private void attachApplicationLocked(@NonNull IApplicationThread thread,
4555             int pid, int callingUid, long startSeq) {
4556 
4557         // Find the application record that is being attached...  either via
4558         // the pid if we are running in multiple processes, or just pull the
4559         // next app record if we are emulating process with anonymous threads.
4560         ProcessRecord app;
4561         long startTime = SystemClock.uptimeMillis();
4562         long bindApplicationTimeMillis;
4563         if (pid != MY_PID && pid >= 0) {
4564             synchronized (mPidsSelfLocked) {
4565                 app = mPidsSelfLocked.get(pid);
4566             }
4567             if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) {
4568                 String processName = null;
4569                 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4570                 if (pending != null) {
4571                     processName = pending.processName;
4572                 }
4573                 final String msg = "attachApplicationLocked process:" + processName
4574                         + " startSeq:" + startSeq
4575                         + " pid:" + pid
4576                         + " belongs to another existing app:" + app.processName
4577                         + " startSeq:" + app.getStartSeq();
4578                 Slog.wtf(TAG, msg);
4579                 // SafetyNet logging for b/131105245.
4580                 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg);
4581                 // If there is already an app occupying that pid that hasn't been cleaned up
4582                 cleanUpApplicationRecordLocked(app, pid, false, false, -1,
4583                         true /*replacingPid*/, false /* fromBinderDied */);
4584                 removePidLocked(pid, app);
4585                 app = null;
4586             }
4587         } else {
4588             app = null;
4589         }
4590 
4591         // It's possible that process called attachApplication before we got a chance to
4592         // update the internal state.
4593         if (app == null && startSeq > 0) {
4594             final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4595             if (pending != null && pending.getStartUid() == callingUid
4596                     && pending.getStartSeq() == startSeq
4597                     && mProcessList.handleProcessStartedLocked(pending, pid,
4598                         pending.isUsingWrapper(), startSeq, true)) {
4599                 app = pending;
4600             }
4601         }
4602 
4603         if (app == null) {
4604             Slog.w(TAG, "No pending application record for pid " + pid
4605                     + " (IApplicationThread " + thread + "); dropping process");
4606             EventLogTags.writeAmDropProcess(pid);
4607             if (pid > 0 && pid != MY_PID) {
4608                 killProcessQuiet(pid);
4609                 //TODO: killProcessGroup(app.info.uid, pid);
4610                 // We can't log the app kill info for this process since we don't
4611                 // know who it is, so just skip the logging.
4612             } else {
4613                 try {
4614                     thread.scheduleExit();
4615                 } catch (Exception e) {
4616                     // Ignore exceptions.
4617                 }
4618             }
4619             return;
4620         }
4621 
4622         // If this application record is still attached to a previous
4623         // process, clean it up now.
4624         if (app.getThread() != null) {
4625             handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */);
4626         }
4627 
4628         // Tell the process all about itself.
4629 
4630         if (DEBUG_ALL) Slog.v(
4631                 TAG, "Binding process pid " + pid + " to record " + app);
4632 
4633         final String processName = app.processName;
4634         try {
4635             AppDeathRecipient adr = new AppDeathRecipient(
4636                     app, pid, thread);
4637             thread.asBinder().linkToDeath(adr, 0);
4638             app.setDeathRecipient(adr);
4639         } catch (RemoteException e) {
4640             app.resetPackageList(mProcessStats);
4641             mProcessList.startProcessLocked(app,
4642                     new HostingRecord(HostingRecord.HOSTING_TYPE_LINK_FAIL, processName),
4643                     ZYGOTE_POLICY_FLAG_EMPTY);
4644             return;
4645         }
4646 
4647         EventLogTags.writeAmProcBound(app.userId, pid, app.processName);
4648 
4649         synchronized (mProcLock) {
4650             mOomAdjuster.setAttachingProcessStatesLSP(app);
4651             clearProcessForegroundLocked(app);
4652             app.setDebugging(false);
4653             app.setKilledByAm(false);
4654             app.setKilled(false);
4655             // We carefully use the same state that PackageManager uses for
4656             // filtering, since we use this flag to decide if we need to install
4657             // providers when user is unlocked later
4658             app.setUnlocked(StorageManager.isUserKeyUnlocked(app.userId));
4659         }
4660 
4661         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4662         List<ProviderInfo> providers = normalMode
4663                                             ? mCpHelper.generateApplicationProvidersLocked(app)
4664                                             : null;
4665 
4666         if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) {
4667             Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
4668             msg.obj = app;
4669             mHandler.sendMessageDelayed(msg,
4670                     ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS);
4671         }
4672 
4673         checkTime(startTime, "attachApplicationLocked: before bindApplication");
4674 
4675         if (!normalMode) {
4676             Slog.i(TAG, "Launching preboot mode app: " + app);
4677         }
4678 
4679         if (DEBUG_ALL) Slog.v(
4680             TAG, "New app record " + app
4681             + " thread=" + thread.asBinder() + " pid=" + pid);
4682         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4683         try {
4684             int testMode = ApplicationThreadConstants.DEBUG_OFF;
4685             if (mDebugApp != null && mDebugApp.equals(processName)) {
4686                 if (mWaitForDebugger) {
4687                     if (mSuspendUponWait) {
4688                         testMode = ApplicationThreadConstants.DEBUG_SUSPEND;
4689                     } else {
4690                         testMode = ApplicationThreadConstants.DEBUG_WAIT;
4691                     }
4692                 } else {
4693                     testMode = ApplicationThreadConstants.DEBUG_ON;
4694                 }
4695                 app.setDebugging(true);
4696                 if (mDebugTransient) {
4697                     mDebugApp = mOrigDebugApp;
4698                     mWaitForDebugger = mOrigWaitForDebugger;
4699                 }
4700             }
4701 
4702             boolean enableTrackAllocation = false;
4703             synchronized (mProcLock) {
4704                 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
4705                     enableTrackAllocation = true;
4706                     mTrackAllocationApp = null;
4707                 }
4708             }
4709 
4710             // If the app is being launched for restore or full backup, set it up specially
4711             boolean isRestrictedBackupMode = false;
4712             if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) {
4713                 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID
4714                         && ((backupTarget.backupMode == BackupRecord.RESTORE_FULL)
4715                                 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL));
4716             }
4717 
4718             final ActiveInstrumentation instr = app.getActiveInstrumentation();
4719 
4720             if (instr != null) {
4721                 notifyPackageUse(instr.mClass.getPackageName(),
4722                                  PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
4723             }
4724             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s",
4725                     processName, app.getWindowProcessController().getConfiguration());
4726             ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info;
4727             app.setCompat(compatibilityInfoForPackage(appInfo));
4728 
4729             ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr);
4730 
4731             // We deprecated Build.SERIAL and it is not accessible to
4732             // Instant Apps and target APIs higher than O MR1. Since access to the serial
4733             // is now behind a permission we push down the value.
4734             final String buildSerial = (!appInfo.isInstantApp()
4735                     && appInfo.targetSdkVersion < Build.VERSION_CODES.P)
4736                             ? sTheRealBuildSerial : Build.UNKNOWN;
4737 
4738             // Figure out whether the app needs to run in autofill compat mode.
4739             AutofillOptions autofillOptions = null;
4740             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
4741                 final AutofillManagerInternal afm = LocalServices.getService(
4742                         AutofillManagerInternal.class);
4743                 if (afm != null) {
4744                     autofillOptions = afm.getAutofillOptions(
4745                             app.info.packageName, app.info.longVersionCode, app.userId);
4746                 }
4747             }
4748             ContentCaptureOptions contentCaptureOptions = null;
4749             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
4750                 final ContentCaptureManagerInternal ccm =
4751                         LocalServices.getService(ContentCaptureManagerInternal.class);
4752                 if (ccm != null) {
4753                     contentCaptureOptions = ccm.getOptionsForPackage(app.userId,
4754                             app.info.packageName);
4755                 }
4756             }
4757             SharedMemory serializedSystemFontMap = null;
4758             final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class);
4759             if (fm != null) {
4760                 serializedSystemFontMap = fm.getSerializedSystemFontMap();
4761             }
4762 
4763             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
4764             bindApplicationTimeMillis = SystemClock.uptimeMillis();
4765             mAtmInternal.preBindApplication(app.getWindowProcessController());
4766             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
4767             if (mPlatformCompat != null) {
4768                 mPlatformCompat.resetReporting(app.info);
4769             }
4770             final ProviderInfoList providerList = ProviderInfoList.fromList(providers);
4771             if (app.getIsolatedEntryPoint() != null) {
4772                 // This is an isolated process which should just call an entry point instead of
4773                 // being bound to an application.
4774                 thread.runIsolatedEntryPoint(
4775                         app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs());
4776             } else if (instr2 != null) {
4777                 thread.bindApplication(processName, appInfo,
4778                         app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,
4779                         providerList,
4780                         instr2.mClass,
4781                         profilerInfo, instr2.mArguments,
4782                         instr2.mWatcher,
4783                         instr2.mUiAutomationConnection, testMode,
4784                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
4785                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
4786                         new Configuration(app.getWindowProcessController().getConfiguration()),
4787                         app.getCompat(), getCommonServicesLocked(app.isolated),
4788                         mCoreSettingsObserver.getCoreSettingsLocked(),
4789                         buildSerial, autofillOptions, contentCaptureOptions,
4790                         app.getDisabledCompatChanges(), serializedSystemFontMap,
4791                         app.getStartElapsedTime(), app.getStartUptime());
4792             } else {
4793                 thread.bindApplication(processName, appInfo,
4794                         app.sdkSandboxClientAppVolumeUuid, app.sdkSandboxClientAppPackage,
4795                         providerList, null, profilerInfo, null, null, null, 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             }
4805 
4806             Message msg = mHandler.obtainMessage(BIND_APPLICATION_TIMEOUT_MSG);
4807             msg.obj = app;
4808             mHandler.sendMessageDelayed(msg, BIND_APPLICATION_TIMEOUT);
4809             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4810 
4811             if (profilerInfo != null) {
4812                 profilerInfo.closeFd();
4813                 profilerInfo = null;
4814             }
4815 
4816             app.setBindApplicationTime(bindApplicationTimeMillis);
4817 
4818             // Make app active after binding application or client may be running requests (e.g
4819             // starting activities) before it is ready.
4820             synchronized (mProcLock) {
4821                 app.makeActive(thread, mProcessStats);
4822                 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
4823             }
4824             app.setPendingFinishAttach(true);
4825 
4826             updateLruProcessLocked(app, false, null);
4827             checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
4828 
4829             updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN);
4830             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
4831 
4832             final long now = SystemClock.uptimeMillis();
4833             synchronized (mAppProfiler.mProfilerLock) {
4834                 app.mProfile.setLastRequestedGc(now);
4835                 app.mProfile.setLastLowMemory(now);
4836             }
4837 
4838             // Remove this record from the list of starting applications.
4839             mPersistentStartingProcesses.remove(app);
4840             if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) {
4841                 Slog.v(TAG_PROCESSES, "Attach application locked removing on hold: " + app);
4842             }
4843             mProcessesOnHold.remove(app);
4844 
4845             if (!mConstants.mEnableWaitForFinishAttachApplication) {
4846                 finishAttachApplicationInner(startSeq, callingUid, pid);
4847             }
4848         } catch (Exception e) {
4849             // We need kill the process group here. (b/148588589)
4850             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
4851             app.resetPackageList(mProcessStats);
4852             app.unlinkDeathRecipient();
4853             app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4854                     true);
4855             handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */);
4856             return;
4857         }
4858     }
4859 
4860     @Override
attachApplication(IApplicationThread thread, long startSeq)4861     public final void attachApplication(IApplicationThread thread, long startSeq) {
4862         if (thread == null) {
4863             throw new SecurityException("Invalid application interface");
4864         }
4865         synchronized (this) {
4866             int callingPid = Binder.getCallingPid();
4867             final int callingUid = Binder.getCallingUid();
4868             final long origId = Binder.clearCallingIdentity();
4869             attachApplicationLocked(thread, callingPid, callingUid, startSeq);
4870             Binder.restoreCallingIdentity(origId);
4871         }
4872     }
4873 
finishAttachApplicationInner(long startSeq, int uid, int pid)4874     private void finishAttachApplicationInner(long startSeq, int uid, int pid) {
4875         final long startTime = SystemClock.uptimeMillis();
4876         // Find the application record that is being attached...  either via
4877         // the pid if we are running in multiple processes, or just pull the
4878         // next app record if we are emulating process with anonymous threads.
4879         final ProcessRecord app;
4880         synchronized (mPidsSelfLocked) {
4881             app = mPidsSelfLocked.get(pid);
4882         }
4883 
4884         if (app != null && app.getStartUid() == uid && app.getStartSeq() == startSeq) {
4885             mHandler.removeMessages(BIND_APPLICATION_TIMEOUT_MSG, app);
4886         } else {
4887             Slog.wtf(TAG, "Mismatched or missing ProcessRecord: " + app + ". Pid: " + pid
4888                     + ". Uid: " + uid);
4889             killProcess(pid);
4890             killProcessGroup(uid, pid);
4891             mProcessList.noteAppKill(pid, uid,
4892                     ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4893                     ApplicationExitInfo.SUBREASON_UNKNOWN,
4894                     "wrong startSeq");
4895             synchronized (this) {
4896                 app.killLocked("unexpected process record",
4897                         ApplicationExitInfo.REASON_OTHER, true);
4898             }
4899             return;
4900         }
4901 
4902         synchronized (this) {
4903             // Mark the finish attach application phase as completed
4904             app.setPendingFinishAttach(false);
4905 
4906             final boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4907             final String processName = app.processName;
4908             boolean badApp = false;
4909             boolean didSomething = false;
4910 
4911             // See if the top visible activity is waiting to run in this process...
4912             if (normalMode) {
4913                 try {
4914                     didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
4915                 } catch (Exception e) {
4916                     Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
4917                     badApp = true;
4918                 }
4919             }
4920 
4921             // Find any services that should be running in this process...
4922             if (!badApp) {
4923                 try {
4924                     didSomething |= mServices.attachApplicationLocked(app, processName);
4925                     checkTime(startTime, "finishAttachApplicationInner: "
4926                             + "after mServices.attachApplicationLocked");
4927                 } catch (Exception e) {
4928                     Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
4929                     badApp = true;
4930                 }
4931             }
4932 
4933             // Check if a next-broadcast receiver is in this process...
4934             if (!badApp) {
4935                 try {
4936                     for (BroadcastQueue queue : mBroadcastQueues) {
4937                         didSomething |= queue.onApplicationAttachedLocked(app);
4938                     }
4939                     checkTime(startTime, "finishAttachApplicationInner: "
4940                             + "after dispatching broadcasts");
4941                 } catch (BroadcastDeliveryFailedException e) {
4942                     // If the app died trying to launch the receiver we declare it 'bad'
4943                     Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
4944                     badApp = true;
4945                 }
4946             }
4947 
4948             // Check whether the next backup agent is in this process...
4949             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4950             if (!badApp && backupTarget != null && backupTarget.app == app) {
4951                 if (DEBUG_BACKUP) {
4952                     Slog.v(TAG_BACKUP,
4953                             "New app is backup target, launching agent for " + app);
4954                 }
4955 
4956                 notifyPackageUse(backupTarget.appInfo.packageName,
4957                         PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
4958                 try {
4959                     app.getThread().scheduleCreateBackupAgent(backupTarget.appInfo,
4960                             backupTarget.backupMode, backupTarget.userId,
4961                             backupTarget.backupDestination);
4962                 } catch (Exception e) {
4963                     Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
4964                     badApp = true;
4965                 }
4966             }
4967 
4968             if (badApp) {
4969                 app.killLocked("error during init",
4970                         ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
4971                 handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */);
4972                 return;
4973             }
4974 
4975             if (!didSomething) {
4976                 updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN);
4977                 checkTime(startTime, "finishAttachApplicationInner: after updateOomAdjLocked");
4978             }
4979 
4980             final HostingRecord hostingRecord = app.getHostingRecord();
4981             final String shortAction = getShortAction(hostingRecord.getAction());
4982             FrameworkStatsLog.write(
4983                     FrameworkStatsLog.PROCESS_START_TIME,
4984                     app.info.uid,
4985                     pid,
4986                     app.info.packageName,
4987                     FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD,
4988                     app.getStartElapsedTime(),
4989                     (int) (app.getBindApplicationTime() - app.getStartUptime()),
4990                     (int) (SystemClock.uptimeMillis() - app.getStartUptime()),
4991                     hostingRecord.getType(),
4992                     hostingRecord.getName(),
4993                     shortAction,
4994                     HostingRecord.getHostingTypeIdStatsd(hostingRecord.getType()),
4995                     HostingRecord.getTriggerTypeForStatsd(hostingRecord.getTriggerType()));
4996         }
4997     }
4998 
4999     @Override
finishAttachApplication(long startSeq)5000     public final void finishAttachApplication(long startSeq) {
5001         final int pid = Binder.getCallingPid();
5002         final int uid = Binder.getCallingUid();
5003 
5004         if (!mConstants.mEnableWaitForFinishAttachApplication) {
5005             Slog.i(TAG, "Flag disabled. Ignoring finishAttachApplication from uid: "
5006                     + uid + ". pid: " + pid);
5007             return;
5008         }
5009 
5010         if (pid == MY_PID && uid == SYSTEM_UID) {
5011             return;
5012         }
5013 
5014         final long origId = Binder.clearCallingIdentity();
5015         try {
5016             finishAttachApplicationInner(startSeq, uid, pid);
5017         } finally {
5018             Binder.restoreCallingIdentity(origId);
5019         }
5020     }
5021 
5022     /**
5023      * @return The last part of the string of an intent's action.
5024      */
getShortAction(@ullable String action)5025     static @Nullable String getShortAction(@Nullable String action) {
5026         String shortAction = action;
5027         if (action != null) {
5028             int index = action.lastIndexOf('.');
5029             if (index != -1 && index != action.length() - 1) {
5030                 shortAction = action.substring(index + 1);
5031             }
5032         }
5033         return shortAction;
5034     }
5035 
checkTime(long startTime, String where)5036     void checkTime(long startTime, String where) {
5037         long now = SystemClock.uptimeMillis();
5038         if ((now - startTime) > 50) {
5039             // If we are taking more than 50ms, log about it.
5040             Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where);
5041         }
5042     }
5043 
5044     @Override
showBootMessage(final CharSequence msg, final boolean always)5045     public void showBootMessage(final CharSequence msg, final boolean always) {
5046         if (Binder.getCallingUid() != myUid()) {
5047             throw new SecurityException();
5048         }
5049         mWindowManager.showBootMessage(msg, always);
5050     }
5051 
finishBooting()5052     final void finishBooting() {
5053         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
5054                 Trace.TRACE_TAG_ACTIVITY_MANAGER);
5055         t.traceBegin("FinishBooting");
5056 
5057         synchronized (this) {
5058             if (!mBootAnimationComplete) {
5059                 mCallFinishBooting = true;
5060                 return;
5061             }
5062             mCallFinishBooting = false;
5063         }
5064 
5065         // Let the ART runtime in zygote and system_server know that the boot completed.
5066         ZYGOTE_PROCESS.bootCompleted();
5067         VMRuntime.bootCompleted();
5068 
5069         IntentFilter pkgFilter = new IntentFilter();
5070         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
5071         pkgFilter.addDataScheme("package");
5072         mContext.registerReceiver(new BroadcastReceiver() {
5073             @Override
5074             public void onReceive(Context context, Intent intent) {
5075                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
5076                 if (pkgs != null) {
5077                     for (String pkg : pkgs) {
5078                         synchronized (ActivityManagerService.this) {
5079                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
5080                                     0, "query restart")) {
5081                                 setResultCode(Activity.RESULT_OK);
5082                                 return;
5083                             }
5084                         }
5085                     }
5086                 }
5087             }
5088         }, pkgFilter);
5089 
5090         // Inform checkpointing systems of success
5091         try {
5092             // This line is needed to CTS test for the correct exception handling
5093             // See b/138952436#comment36 for context
5094             Slog.i(TAG, "About to commit checkpoint");
5095             IStorageManager storageManager = InstallLocationUtils.getStorageManager();
5096             storageManager.commitChanges();
5097         } catch (Exception e) {
5098             PowerManager pm = (PowerManager)
5099                      mInjector.getContext().getSystemService(Context.POWER_SERVICE);
5100             pm.reboot("Checkpoint commit failed");
5101         }
5102 
5103         // Let system services know.
5104         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED);
5105 
5106         synchronized (this) {
5107             // Ensure that any processes we had put on hold are now started
5108             // up.
5109             final int NP = mProcessesOnHold.size();
5110             if (NP > 0) {
5111                 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold);
5112                 for (int ip = 0; ip < NP; ip++) {
5113                     if (DEBUG_PROCESSES) {
5114                         Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip));
5115                     }
5116                     mProcessList.startProcessLocked(procs.get(ip),
5117                             new HostingRecord(HostingRecord.HOSTING_TYPE_ON_HOLD),
5118                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
5119                 }
5120             }
5121             if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5122                 return;
5123             }
5124             // Start looking for apps that are abusing wake locks.
5125             Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
5126             mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
5127             // Check if we are performing userspace reboot before setting sys.boot_completed to
5128             // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys
5129             // .boot_completed is 1.
5130             if (InitProperties.userspace_reboot_in_progress().orElse(false)) {
5131                 UserspaceRebootLogger.noteUserspaceRebootSuccess();
5132             }
5133             // Tell anyone interested that we are done booting!
5134             SystemProperties.set("sys.boot_completed", "1");
5135             SystemProperties.set("dev.bootcomplete", "1");
5136             mUserController.onBootComplete(
5137                     new IIntentReceiver.Stub() {
5138                         @Override
5139                         public void performReceive(Intent intent, int resultCode,
5140                                 String data, Bundle extras, boolean ordered,
5141                                 boolean sticky, int sendingUser) {
5142                             synchronized (mProcLock) {
5143                                 mAppProfiler.requestPssAllProcsLPr(
5144                                         SystemClock.uptimeMillis(), true, false);
5145                             }
5146                         }
5147                     });
5148             maybeLogUserspaceRebootEvent();
5149             mUserController.scheduleStartProfiles();
5150         }
5151         // UART is on if init's console service is running, send a warning notification.
5152         showConsoleNotificationIfActive();
5153         showMteOverrideNotificationIfActive();
5154 
5155         t.traceEnd();
5156     }
5157 
showConsoleNotificationIfActive()5158     private void showConsoleNotificationIfActive() {
5159         if (!SystemProperties.get("init.svc.console").equals("running")) {
5160             return;
5161         }
5162         String title = mContext
5163                 .getString(com.android.internal.R.string.console_running_notification_title);
5164         String message = mContext
5165                 .getString(com.android.internal.R.string.console_running_notification_message);
5166         Notification notification =
5167                 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
5168                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5169                         .setWhen(0)
5170                         .setOngoing(true)
5171                         .setTicker(title)
5172                         .setDefaults(0)  // please be quiet
5173                         .setColor(mContext.getColor(
5174                                 com.android.internal.R.color
5175                                         .system_notification_accent_color))
5176                         .setContentTitle(title)
5177                         .setContentText(message)
5178                         .setVisibility(Notification.VISIBILITY_PUBLIC)
5179                         .build();
5180 
5181         NotificationManager notificationManager =
5182                 mContext.getSystemService(NotificationManager.class);
5183         notificationManager.notifyAsUser(
5184                 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL);
5185 
5186     }
5187 
showMteOverrideNotificationIfActive()5188     private void showMteOverrideNotificationIfActive() {
5189         String bootctl = SystemProperties.get("arm64.memtag.bootctl");
5190         // If MTE is on, there is one in three cases:
5191         // * a fullmte build: ro.arm64.memtag.bootctl_supported is not set
5192         // * memtag: arm64.memtag.bootctl contains "memtag"
5193         // * memtag-once
5194         // In the condition below we detect memtag-once by exclusion.
5195         if (Arrays.asList(bootctl.split(",")).contains("memtag")
5196             || !SystemProperties.getBoolean("ro.arm64.memtag.bootctl_supported", false)
5197             || !com.android.internal.os.Zygote.nativeSupportsMemoryTagging()) {
5198             return;
5199         }
5200         String title = mContext
5201                 .getString(com.android.internal.R.string.mte_override_notification_title);
5202         String message = mContext
5203                 .getString(com.android.internal.R.string.mte_override_notification_message);
5204         Notification notification =
5205                 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
5206                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5207                         .setOngoing(true)
5208                         .setTicker(title)
5209                         .setDefaults(0)  // please be quiet
5210                         .setColor(mContext.getColor(
5211                                 com.android.internal.R.color
5212                                         .system_notification_accent_color))
5213                         .setContentTitle(title)
5214                         .setContentText(message)
5215                         .setVisibility(Notification.VISIBILITY_PUBLIC)
5216                         .build();
5217 
5218         NotificationManager notificationManager =
5219                 mContext.getSystemService(NotificationManager.class);
5220         notificationManager.notifyAsUser(
5221                 null, SystemMessage.NOTE_MTE_OVERRIDE_ENABLED, notification, UserHandle.ALL);
5222     }
5223 
5224     @Override
bootAnimationComplete()5225     public void bootAnimationComplete() {
5226         if (DEBUG_ALL) Slog.d(TAG, "bootAnimationComplete: Callers=" + Debug.getCallers(4));
5227 
5228         final boolean callFinishBooting;
5229         synchronized (this) {
5230             callFinishBooting = mCallFinishBooting;
5231             mBootAnimationComplete = true;
5232         }
5233         if (callFinishBooting) {
5234             finishBooting();
5235         }
5236     }
5237 
ensureBootCompleted()5238     final void ensureBootCompleted() {
5239         boolean booting;
5240         boolean enableScreen;
5241         synchronized (this) {
5242             booting = mBooting;
5243             mBooting = false;
5244             enableScreen = !mBooted;
5245             mBooted = true;
5246         }
5247 
5248         if (booting) {
5249             finishBooting();
5250         }
5251 
5252         if (enableScreen) {
5253             mAtmInternal.enableScreenAfterBoot(mBooted);
5254         }
5255     }
5256 
5257     /**
5258      * @deprecated Use {@link #getIntentSenderWithFeature} instead
5259      */
5260     @Deprecated
5261     @Override
getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5262     public IIntentSender getIntentSender(int type,
5263             String packageName, IBinder token, String resultWho,
5264             int requestCode, Intent[] intents, String[] resolvedTypes,
5265             int flags, Bundle bOptions, int userId) {
5266         return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode,
5267                 intents, resolvedTypes, flags, bOptions, userId);
5268     }
5269 
5270     @Override
getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5271     public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId,
5272             IBinder token, String resultWho, int requestCode, Intent[] intents,
5273             String[] resolvedTypes, int flags, Bundle bOptions, int userId) {
5274         enforceNotIsolatedCaller("getIntentSender");
5275 
5276         return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho,
5277                 requestCode, intents, resolvedTypes, flags, bOptions, userId,
5278                 Binder.getCallingUid());
5279     }
5280 
5281     /**
5282      * System-internal callers can invoke this with owningUid being the app's own identity
5283      * rather than the public API's behavior of always assigning ownership to the actual
5284      * caller identity.  This will create an IntentSender as though the package/userid/uid app
5285      * were the caller, so that the ultimate PendingIntent is triggered with only the app's
5286      * capabilities and not the system's.  Used in cases like notification groups where
5287      * the OS must synthesize a PendingIntent on an app's behalf.
5288      */
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)5289     public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName,
5290             String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents,
5291             String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) {
5292         // NOTE: The service lock isn't held in this method because nothing in the method requires
5293         // the service lock to be held.
5294 
5295         // Refuse possible leaked file descriptors
5296         if (intents != null) {
5297             if (intents.length < 1) {
5298                 throw new IllegalArgumentException("Intents array length must be >= 1");
5299             }
5300             for (int i=0; i<intents.length; i++) {
5301                 Intent intent = intents[i];
5302                 if (intent != null) {
5303                     if (intent.hasFileDescriptors()) {
5304                         throw new IllegalArgumentException("File descriptors passed in Intent");
5305                     }
5306                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
5307                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5308                         throw new IllegalArgumentException(
5309                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5310                     }
5311                     boolean isActivityResultType =
5312                             type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT;
5313                     if (PendingIntent.isNewMutableDisallowedImplicitPendingIntent(flags, intent,
5314                             isActivityResultType)) {
5315                         boolean isChangeEnabled = CompatChanges.isChangeEnabled(
5316                                         PendingIntent.BLOCK_MUTABLE_IMPLICIT_PENDING_INTENT,
5317                                         packageName, UserHandle.of(userId));
5318                         String resolvedType = resolvedTypes == null
5319                                 || i >= resolvedTypes.length ? null : resolvedTypes[i];
5320                         ActivityManagerUtils.logUnsafeIntentEvent(
5321                                 UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__NEW_MUTABLE_IMPLICIT_PENDING_INTENT_RETRIEVED,
5322                                 owningUid, intent, resolvedType, isChangeEnabled);
5323                         if (isChangeEnabled) {
5324                             String msg = packageName + ": Targeting U+ (version "
5325                                     + Build.VERSION_CODES.UPSIDE_DOWN_CAKE + " and above) disallows"
5326                                     + " creating or retrieving a PendingIntent with FLAG_MUTABLE,"
5327                                     + " an implicit Intent within and without FLAG_NO_CREATE and"
5328                                     + " FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for"
5329                                     + " security reasons. To retrieve an already existing"
5330                                     + " PendingIntent, use FLAG_NO_CREATE, however, to create a"
5331                                     + " new PendingIntent with an implicit Intent use"
5332                                     + " FLAG_IMMUTABLE.";
5333                             throw new IllegalArgumentException(msg);
5334                         }
5335                     }
5336                     intents[i] = new Intent(intent);
5337                 }
5338             }
5339             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
5340                 throw new IllegalArgumentException(
5341                         "Intent array length does not match resolvedTypes length");
5342             }
5343         }
5344         if (bOptions != null) {
5345             if (bOptions.hasFileDescriptors()) {
5346                 throw new IllegalArgumentException("File descriptors passed in options");
5347             }
5348         }
5349 
5350         int origUserId = userId;
5351         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId,
5352                 type == ActivityManager.INTENT_SENDER_BROADCAST,
5353                 ALLOW_NON_FULL, "getIntentSender", null);
5354         if (origUserId == UserHandle.USER_CURRENT) {
5355             // We don't want to evaluate this until the pending intent is
5356             // actually executed.  However, we do want to always do the
5357             // security checking for it above.
5358             userId = UserHandle.USER_CURRENT;
5359         }
5360         try {
5361             if (owningUid != 0 && owningUid != SYSTEM_UID) {
5362                 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
5363                         MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(owningUid));
5364                 if (!UserHandle.isSameApp(owningUid, uid)) {
5365                     String msg = "Permission Denial: getIntentSender() from pid="
5366                             + Binder.getCallingPid()
5367                             + ", uid=" + owningUid
5368                             + ", (need uid=" + uid + ")"
5369                             + " is not allowed to send as package " + packageName;
5370                     Slog.w(TAG, msg);
5371                     throw new SecurityException(msg);
5372                 }
5373             }
5374 
5375             if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5376                 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid,
5377                         userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5378                         bOptions);
5379             }
5380             return mPendingIntentController.getIntentSender(type, packageName, featureId,
5381                     owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes,
5382                     flags, bOptions);
5383         } catch (RemoteException e) {
5384             throw new SecurityException(e);
5385         }
5386     }
5387 
5388     @Override
sendIntentSender(IApplicationThread caller, IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5389     public int sendIntentSender(IApplicationThread caller, IIntentSender target,
5390             IBinder allowlistToken, int code, Intent intent, String resolvedType,
5391             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
5392         if (target instanceof PendingIntentRecord) {
5393             final PendingIntentRecord originalRecord = (PendingIntentRecord) target;
5394 
5395             // In multi-display scenarios, there can be background users who execute the
5396             // PendingIntent. In these scenarios, we don't want to use the foreground user as the
5397             // current user.
5398             final PendingIntentRecord.Key originalKey = originalRecord.key;
5399             final UserManagerInternal umInternal =
5400                     LocalServices.getService(UserManagerInternal.class);
5401             final int callingUserId = UserHandle.getCallingUserId();
5402             if (UserManager.isVisibleBackgroundUsersEnabled()
5403                     && originalKey.userId == UserHandle.USER_CURRENT
5404                     && callingUserId != UserHandle.USER_SYSTEM
5405                     && umInternal.isUserVisible(callingUserId)) {
5406                 EventLogTags.writeAmIntentSenderRedirectUser(callingUserId);
5407                 final PendingIntentRecord.Key key = new PendingIntentRecord.Key(originalKey.type,
5408                         originalKey.packageName, originalKey.featureId, originalKey.activity,
5409                         originalKey.who, originalKey.requestCode, originalKey.allIntents,
5410                         originalKey.allResolvedTypes, originalKey.flags, originalKey.options,
5411                         callingUserId);
5412 
5413                 final PendingIntentRecord newRecord = new PendingIntentRecord(
5414                         originalRecord.controller, key, originalRecord.uid);
5415 
5416                 return newRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken,
5417                         finishedReceiver, requiredPermission, options);
5418             }
5419 
5420             return originalRecord.sendWithResult(caller, code, intent, resolvedType, allowlistToken,
5421                     finishedReceiver, requiredPermission, options);
5422         } else {
5423             if (intent == null) {
5424                 // Weird case: someone has given us their own custom IIntentSender, and now
5425                 // they have someone else trying to send to it but of course this isn't
5426                 // really a PendingIntent, so there is no base Intent, and the caller isn't
5427                 // supplying an Intent... but we never want to dispatch a null Intent to
5428                 // a receiver, so um...  let's make something up.
5429                 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
5430                 intent = new Intent(Intent.ACTION_MAIN);
5431             }
5432             try {
5433                 if (allowlistToken != null) {
5434                     final int callingUid = Binder.getCallingUid();
5435                     final String packageName;
5436                     final long token = Binder.clearCallingIdentity();
5437                     try {
5438                         packageName = AppGlobals.getPackageManager().getNameForUid(callingUid);
5439                     } finally {
5440                         Binder.restoreCallingIdentity(token);
5441                     }
5442                     Slog.wtf(TAG, "Send a non-null allowlistToken to a non-PI target."
5443                             + " Calling package: " + packageName + "; intent: " + intent
5444                             + "; options: " + options);
5445                 }
5446                 target.send(code, intent, resolvedType, null, null,
5447                         requiredPermission, options);
5448             } catch (RemoteException e) {
5449             }
5450             // Platform code can rely on getting a result back when the send is done, but if
5451             // this intent sender is from outside of the system we can't rely on it doing that.
5452             // So instead we don't give it the result receiver, and instead just directly
5453             // report the finish immediately.
5454             if (finishedReceiver != null) {
5455                 try {
5456                     finishedReceiver.performReceive(intent, 0,
5457                             null, null, false, false, UserHandle.getCallingUserId());
5458                 } catch (RemoteException e) {
5459                 }
5460             }
5461             return 0;
5462         }
5463     }
5464 
5465     @Override
cancelIntentSender(IIntentSender sender)5466     public void cancelIntentSender(IIntentSender sender) {
5467         mPendingIntentController.cancelIntentSender(sender);
5468     }
5469 
5470     @Override
registerIntentSenderCancelListenerEx( IIntentSender sender, IResultReceiver receiver)5471     public boolean registerIntentSenderCancelListenerEx(
5472             IIntentSender sender, IResultReceiver receiver) {
5473         return mPendingIntentController.registerIntentSenderCancelListener(sender, receiver);
5474     }
5475 
5476     @Override
unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5477     public void unregisterIntentSenderCancelListener(IIntentSender sender,
5478             IResultReceiver receiver) {
5479         mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver);
5480     }
5481 
5482     @Override
getInfoForIntentSender(IIntentSender sender)5483     public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) {
5484         if (sender instanceof PendingIntentRecord) {
5485             final PendingIntentRecord res = (PendingIntentRecord) sender;
5486             final String packageName = res.key.packageName;
5487             final int uid = res.uid;
5488             final boolean shouldFilter = getPackageManagerInternal().filterAppAccess(
5489                     packageName, Binder.getCallingUid(), UserHandle.getUserId(uid));
5490             return new PendingIntentInfo(
5491                     shouldFilter ? null : packageName,
5492                     shouldFilter ? INVALID_UID : uid,
5493                     (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0,
5494                     res.key.type);
5495         } else {
5496             return new PendingIntentInfo(null, INVALID_UID, false,
5497                     ActivityManager.INTENT_SENDER_UNKNOWN);
5498         }
5499     }
5500 
5501     @Override
isIntentSenderTargetedToPackage(IIntentSender pendingResult)5502     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5503         if (!(pendingResult instanceof PendingIntentRecord)) {
5504             return false;
5505         }
5506         try {
5507             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5508             if (res.key.allIntents == null) {
5509                 return false;
5510             }
5511             for (int i=0; i<res.key.allIntents.length; i++) {
5512                 Intent intent = res.key.allIntents[i];
5513                 if (intent.getPackage() != null && intent.getComponent() != null) {
5514                     return false;
5515                 }
5516             }
5517             return true;
5518         } catch (ClassCastException e) {
5519         }
5520         return false;
5521     }
5522 
5523     @Override
isIntentSenderAnActivity(IIntentSender pendingResult)5524     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
5525         if (!(pendingResult instanceof PendingIntentRecord)) {
5526             return false;
5527         }
5528         try {
5529             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5530             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
5531                 return true;
5532             }
5533             return false;
5534         } catch (ClassCastException e) {
5535         }
5536         return false;
5537     }
5538 
5539     @Override
getIntentForIntentSender(IIntentSender pendingResult)5540     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
5541         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5542                 "getIntentForIntentSender()");
5543         if (!(pendingResult instanceof PendingIntentRecord)) {
5544             return null;
5545         }
5546         try {
5547             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5548             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
5549         } catch (ClassCastException e) {
5550         }
5551         return null;
5552     }
5553 
5554     @Override
queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5555     public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender(
5556             IIntentSender pendingResult, int matchFlags) {
5557         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5558                 "queryIntentComponentsForIntentSender()");
5559         Objects.requireNonNull(pendingResult);
5560         final PendingIntentRecord res;
5561         try {
5562             res = (PendingIntentRecord) pendingResult;
5563         } catch (ClassCastException e) {
5564             return null;
5565         }
5566         final Intent intent = res.key.requestIntent;
5567         if (intent == null) {
5568             return null;
5569         }
5570         final int userId = res.key.userId;
5571         final int uid = res.uid;
5572         final String resolvedType = res.key.requestResolvedType;
5573         switch (res.key.type) {
5574             case ActivityManager.INTENT_SENDER_ACTIVITY:
5575                 return new ParceledListSlice<>(mPackageManagerInt.queryIntentActivities(
5576                         intent, resolvedType, matchFlags, uid, userId));
5577             case ActivityManager.INTENT_SENDER_SERVICE:
5578             case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE:
5579                 return new ParceledListSlice<>(mPackageManagerInt.queryIntentServices(
5580                         intent, matchFlags, uid, userId));
5581             case ActivityManager.INTENT_SENDER_BROADCAST:
5582                 return new ParceledListSlice<>(mPackageManagerInt.queryIntentReceivers(
5583                         intent, resolvedType, matchFlags, uid, userId, false));
5584             default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT
5585                 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type);
5586         }
5587     }
5588 
5589     @Override
getTagForIntentSender(IIntentSender pendingResult, String prefix)5590     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
5591         if (!(pendingResult instanceof PendingIntentRecord)) {
5592             return null;
5593         }
5594         try {
5595             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5596             synchronized (this) {
5597                 return getTagForIntentSenderLocked(res, prefix);
5598             }
5599         } catch (ClassCastException e) {
5600         }
5601         return null;
5602     }
5603 
getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5604     String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
5605         final Intent intent = res.key.requestIntent;
5606         if (intent != null) {
5607             if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
5608                     || res.lastTagPrefix.equals(prefix))) {
5609                 return res.lastTag;
5610             }
5611             res.lastTagPrefix = prefix;
5612             final StringBuilder sb = new StringBuilder(128);
5613             if (prefix != null) {
5614                 sb.append(prefix);
5615             }
5616             if (intent.getAction() != null) {
5617                 sb.append(intent.getAction());
5618             } else if (intent.getComponent() != null) {
5619                 intent.getComponent().appendShortString(sb);
5620             } else {
5621                 sb.append("?");
5622             }
5623             return res.lastTag = sb.toString();
5624         }
5625         return null;
5626     }
5627 
5628     @Override
setProcessLimit(int max)5629     public void setProcessLimit(int max) {
5630         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5631                 "setProcessLimit()");
5632         synchronized (this) {
5633             mConstants.setOverrideMaxCachedProcesses(max);
5634             trimApplicationsLocked(true, OOM_ADJ_REASON_PROCESS_END);
5635         }
5636     }
5637 
5638     @Override
getProcessLimit()5639     public int getProcessLimit() {
5640         synchronized (this) {
5641             return mConstants.getOverrideMaxCachedProcesses();
5642         }
5643     }
5644 
importanceTokenDied(ImportanceToken token)5645     void importanceTokenDied(ImportanceToken token) {
5646         synchronized (ActivityManagerService.this) {
5647             ProcessRecord pr = null;
5648             synchronized (mPidsSelfLocked) {
5649                 ImportanceToken cur
5650                     = mImportantProcesses.get(token.pid);
5651                 if (cur != token) {
5652                     return;
5653                 }
5654                 mImportantProcesses.remove(token.pid);
5655                 pr = mPidsSelfLocked.get(token.pid);
5656                 if (pr == null) {
5657                     return;
5658                 }
5659                 pr.mState.setForcingToImportant(null);
5660                 clearProcessForegroundLocked(pr);
5661             }
5662             updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
5663         }
5664     }
5665 
5666     @Override
setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5667     public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
5668         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5669                 "setProcessImportant()");
5670         synchronized(this) {
5671             boolean changed = false;
5672 
5673             ProcessRecord pr = null;
5674             synchronized (mPidsSelfLocked) {
5675                 pr = mPidsSelfLocked.get(pid);
5676                 if (pr == null && isForeground) {
5677                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5678                     return;
5679                 }
5680                 ImportanceToken oldToken = mImportantProcesses.get(pid);
5681                 if (oldToken != null) {
5682                     oldToken.token.unlinkToDeath(oldToken, 0);
5683                     mImportantProcesses.remove(pid);
5684                     if (pr != null) {
5685                         pr.mState.setForcingToImportant(null);
5686                     }
5687                     changed = true;
5688                 }
5689                 if (isForeground && token != null) {
5690                     ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
5691                         @Override
5692                         public void binderDied() {
5693                             importanceTokenDied(this);
5694                         }
5695                     };
5696                     try {
5697                         token.linkToDeath(newToken, 0);
5698                         mImportantProcesses.put(pid, newToken);
5699                         pr.mState.setForcingToImportant(newToken);
5700                         changed = true;
5701                     } catch (RemoteException e) {
5702                         // If the process died while doing this, we will later
5703                         // do the cleanup with the process death link.
5704                     }
5705                 }
5706             }
5707 
5708             if (changed) {
5709                 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
5710             }
5711         }
5712     }
5713 
isAppForeground(int uid)5714     private boolean isAppForeground(int uid) {
5715         synchronized (mProcLock) {
5716             UidRecord uidRec = mProcessList.mActiveUids.get(uid);
5717             if (uidRec == null || uidRec.isIdle()) {
5718                 return false;
5719             }
5720             return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND;
5721         }
5722     }
5723 
isAppBad(final String processName, final int uid)5724     private boolean isAppBad(final String processName, final int uid) {
5725         return mAppErrors.isBadProcess(processName, uid);
5726     }
5727 
5728     // NOTE: this is an internal method used by the OnShellCommand implementation only and should
5729     // be guarded by permission checking.
getUidState(int uid)5730     int getUidState(int uid) {
5731         synchronized (mProcLock) {
5732             return mProcessList.getUidProcStateLOSP(uid);
5733         }
5734     }
5735 
5736     @GuardedBy("this")
getUidStateLocked(int uid)5737     int getUidStateLocked(int uid) {
5738         return mProcessList.getUidProcStateLOSP(uid);
5739     }
5740 
5741     @GuardedBy("this")
getUidProcessCapabilityLocked(int uid)5742     int getUidProcessCapabilityLocked(int uid) {
5743         return mProcessList.getUidProcessCapabilityLOSP(uid);
5744     }
5745 
5746     // =========================================================
5747     // PROCESS INFO
5748     // =========================================================
5749 
5750     static class ProcessInfoService extends IProcessInfoService.Stub {
5751         final ActivityManagerService mActivityManagerService;
ProcessInfoService(ActivityManagerService activityManagerService)5752         ProcessInfoService(ActivityManagerService activityManagerService) {
5753             mActivityManagerService = activityManagerService;
5754         }
5755 
5756         @Override
getProcessStatesFromPids( int[] pids, int[] states)5757         public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
5758             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5759                     /*in*/ pids, /*out*/ states, null);
5760         }
5761 
5762         @Override
getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5763         public void getProcessStatesAndOomScoresFromPids(
5764                 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5765             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5766                     /*in*/ pids, /*out*/ states, /*out*/ scores);
5767         }
5768     }
5769 
5770     /**
5771      * For each PID in the given input array, write the current process state
5772      * for that process into the states array, or -1 to indicate that no
5773      * process with the given PID exists. If scores array is provided, write
5774      * the oom score for the process into the scores array, with INVALID_ADJ
5775      * indicating the PID doesn't exist.
5776      */
getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5777     public void getProcessStatesAndOomScoresForPIDs(
5778             /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5779         if (scores != null) {
5780             enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
5781                     "getProcessStatesAndOomScoresForPIDs()");
5782         }
5783 
5784         if (pids == null) {
5785             throw new NullPointerException("pids");
5786         } else if (states == null) {
5787             throw new NullPointerException("states");
5788         } else if (pids.length != states.length) {
5789             throw new IllegalArgumentException("pids and states arrays have different lengths!");
5790         } else if (scores != null && pids.length != scores.length) {
5791             throw new IllegalArgumentException("pids and scores arrays have different lengths!");
5792         }
5793 
5794         synchronized (mProcLock) {
5795             synchronized (mPidsSelfLocked) {
5796                 int newestTimeIndex = -1;
5797                 long newestTime = Long.MIN_VALUE;
5798                 for (int i = 0; i < pids.length; i++) {
5799                     ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
5800                     if (pr != null) {
5801                         final long pendingTopTime =
5802                                 mPendingStartActivityUids.getPendingTopPidTime(pr.uid, pids[i]);
5803                         if (pendingTopTime != PendingStartActivityUids.INVALID_TIME) {
5804                             // The uid in mPendingStartActivityUids gets the TOP process state.
5805                             states[i] = PROCESS_STATE_TOP;
5806                             if (scores != null) {
5807                                 // The uid in mPendingStartActivityUids gets a better score.
5808                                 scores[i] = ProcessList.FOREGROUND_APP_ADJ - 1;
5809                             }
5810                             if (pendingTopTime > newestTime) {
5811                                 newestTimeIndex = i;
5812                                 newestTime = pendingTopTime;
5813                             }
5814                         } else {
5815                             states[i] = pr.mState.getCurProcState();
5816                             if (scores != null) {
5817                                 scores[i] = pr.mState.getCurAdj();
5818                             }
5819                         }
5820                     } else {
5821                         states[i] = PROCESS_STATE_NONEXISTENT;
5822                         if (scores != null) {
5823                             scores[i] = ProcessList.INVALID_ADJ;
5824                         }
5825                     }
5826                 }
5827                 // The uid with the newest timestamp in mPendingStartActivityUids gets the best
5828                 // score.
5829                 if (newestTimeIndex != -1) {
5830                     if (scores != null) {
5831                         scores[newestTimeIndex] = ProcessList.FOREGROUND_APP_ADJ - 2;
5832                     }
5833                 }
5834             }
5835         }
5836     }
5837 
5838     // =========================================================
5839     // PERMISSIONS
5840     // =========================================================
5841 
5842     static class PermissionController extends IPermissionController.Stub {
5843         ActivityManagerService mActivityManagerService;
PermissionController(ActivityManagerService activityManagerService)5844         PermissionController(ActivityManagerService activityManagerService) {
5845             mActivityManagerService = activityManagerService;
5846         }
5847 
5848         @Override
checkPermission(String permission, int pid, int uid)5849         public boolean checkPermission(String permission, int pid, int uid) {
5850             return mActivityManagerService.checkPermission(permission, pid,
5851                     uid) == PackageManager.PERMISSION_GRANTED;
5852         }
5853 
5854         @Override
noteOp(String op, int uid, String packageName)5855         public int noteOp(String op, int uid, String packageName) {
5856             // TODO moltmann: Allow to specify featureId
5857             return mActivityManagerService.mAppOpsService
5858                     .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null,
5859                             false, "", false).getOpMode();
5860         }
5861 
5862         @Override
getPackagesForUid(int uid)5863         public String[] getPackagesForUid(int uid) {
5864             return mActivityManagerService.mContext.getPackageManager()
5865                     .getPackagesForUid(uid);
5866         }
5867 
5868         @Override
isRuntimePermission(String permission)5869         public boolean isRuntimePermission(String permission) {
5870             try {
5871                 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
5872                         .getPermissionInfo(permission, 0);
5873                 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
5874                         == PermissionInfo.PROTECTION_DANGEROUS;
5875             } catch (NameNotFoundException nnfe) {
5876                 Slog.e(TAG, "No such permission: "+ permission, nnfe);
5877             }
5878             return false;
5879         }
5880 
5881         @Override
getPackageUid(String packageName, int flags)5882         public int getPackageUid(String packageName, int flags) {
5883             try {
5884                 return mActivityManagerService.mContext.getPackageManager()
5885                         .getPackageUid(packageName, flags);
5886             } catch (NameNotFoundException nnfe) {
5887                 return -1;
5888             }
5889         }
5890     }
5891 
5892     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
5893         @Override
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5894         public int checkComponentPermission(String permission, int pid, int uid,
5895                 int owningUid, boolean exported) {
5896             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
5897                     owningUid, exported);
5898         }
5899 
5900         @Override
getAMSLock()5901         public Object getAMSLock() {
5902             return ActivityManagerService.this;
5903         }
5904     }
5905 
5906     /**
5907      * Allows if {@code pid} is {@link #MY_PID}, then denies if the {@code pid} has been denied
5908      * provided non-{@code null} {@code permission} before. Otherwise calls into
5909      * {@link ActivityManager#checkComponentPermission(String, int, int, boolean)}.
5910      */
5911     @PackageManager.PermissionResult
5912     @PermissionMethod
checkComponentPermission(@ermissionName String permission, int pid, int uid, int owningUid, boolean exported)5913     public static int checkComponentPermission(@PermissionName String permission, int pid, int uid,
5914             int owningUid, boolean exported) {
5915         if (pid == MY_PID) {
5916             return PackageManager.PERMISSION_GRANTED;
5917         }
5918         // If there is an explicit permission being checked, and this is coming from a process
5919         // that has been denied access to that permission, then just deny.  Ultimately this may
5920         // not be quite right -- it means that even if the caller would have access for another
5921         // reason (such as being the owner of the component it is trying to access), it would still
5922         // fail.  This also means the system and root uids would be able to deny themselves
5923         // access to permissions, which...  well okay. ¯\_(ツ)_/¯
5924         if (permission != null) {
5925             synchronized (sActiveProcessInfoSelfLocked) {
5926                 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid);
5927                 if (procInfo != null && procInfo.deniedPermissions != null
5928                         && procInfo.deniedPermissions.contains(permission)) {
5929                     return PackageManager.PERMISSION_DENIED;
5930                 }
5931             }
5932         }
5933         return ActivityManager.checkComponentPermission(permission, uid,
5934                 owningUid, exported);
5935     }
5936 
enforceDebuggable(ProcessRecord proc)5937     private void enforceDebuggable(ProcessRecord proc) {
5938         if (!Build.IS_DEBUGGABLE && !proc.isDebuggable()) {
5939             throw new SecurityException("Process not debuggable: " + proc.info.packageName);
5940         }
5941     }
5942 
enforceDebuggable(ApplicationInfo info)5943     private void enforceDebuggable(ApplicationInfo info) {
5944         if (!Build.IS_DEBUGGABLE && (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
5945             throw new SecurityException("Process not debuggable: " + info.packageName);
5946         }
5947     }
5948 
5949     /**
5950      * As the only public entry point for permissions checking, this method
5951      * can enforce the semantic that requesting a check on a null global
5952      * permission is automatically denied.  (Internally a null permission
5953      * string is used when calling {@link #checkComponentPermission} in cases
5954      * when only uid-based security is needed.)
5955      *
5956      * This can be called with or without the global lock held.
5957      */
5958     @Override
5959     @PackageManager.PermissionResult
5960     @PermissionMethod
checkPermission(@ermissionName String permission, int pid, int uid)5961     public int checkPermission(@PermissionName String permission, int pid, int uid) {
5962         if (permission == null) {
5963             return PackageManager.PERMISSION_DENIED;
5964         }
5965         return checkComponentPermission(permission, pid, uid, -1, true);
5966     }
5967 
5968     /**
5969      * Binder IPC calls go through the public entry point.
5970      * This can be called with or without the global lock held.
5971      */
5972     @PackageManager.PermissionResult
5973     @PermissionMethod
checkCallingPermission(@ermissionName String permission)5974     int checkCallingPermission(@PermissionName String permission) {
5975         return checkPermission(permission,
5976                 Binder.getCallingPid(),
5977                 Binder.getCallingUid());
5978     }
5979 
5980     /**
5981      * This can be called with or without the global lock held.
5982      */
5983     @PermissionMethod
enforceCallingPermission(@ermissionName String permission, String func)5984     void enforceCallingPermission(@PermissionName String permission, String func) {
5985         if (checkCallingPermission(permission)
5986                 == PackageManager.PERMISSION_GRANTED) {
5987             return;
5988         }
5989 
5990         String msg = "Permission Denial: " + func + " from pid="
5991                 + Binder.getCallingPid()
5992                 + ", uid=" + Binder.getCallingUid()
5993                 + " requires " + permission;
5994         Slog.w(TAG, msg);
5995         throw new SecurityException(msg);
5996     }
5997 
5998     /**
5999      * This can be called with or without the global lock held.
6000      */
6001     @PermissionMethod(anyOf = true)
enforceCallingHasAtLeastOnePermission(String func, String... permissions)6002     private void enforceCallingHasAtLeastOnePermission(String func, String... permissions) {
6003         for (String permission : permissions) {
6004             if (checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
6005                 return;
6006             }
6007         }
6008 
6009         String msg = "Permission Denial: " + func + " from pid="
6010                 + Binder.getCallingPid()
6011                 + ", uid=" + Binder.getCallingUid()
6012                 + " requires one of " + Arrays.toString(permissions);
6013         Slog.w(TAG, msg);
6014         throw new SecurityException(msg);
6015     }
6016 
6017     /**
6018      * This can be called with or without the global lock held.
6019      */
6020     @PermissionMethod
enforcePermission(@ermissionName String permission, int pid, int uid, String func)6021     void enforcePermission(@PermissionName String permission, int pid, int uid, String func) {
6022         if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) {
6023             return;
6024         }
6025 
6026         String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid
6027                 + " requires " + permission;
6028         Slog.w(TAG, msg);
6029         throw new SecurityException(msg);
6030     }
6031 
isAppStartModeDisabled(int uid, String packageName)6032     public boolean isAppStartModeDisabled(int uid, String packageName) {
6033         synchronized (mProcLock) {
6034             return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false)
6035                     == ActivityManager.APP_START_MODE_DISABLED;
6036         }
6037     }
6038 
isInRestrictedBucket(int userId, String packageName, long nowElapsed)6039     private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) {
6040         return UsageStatsManager.STANDBY_BUCKET_RESTRICTED
6041                 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed);
6042     }
6043 
6044     // Unified app-op and target sdk check
6045     @GuardedBy(anyOf = {"this", "mProcLock"})
appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6046     int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
6047         // Apps that target O+ are always subject to background check
6048         if (packageTargetSdk >= Build.VERSION_CODES.O) {
6049             if (DEBUG_BACKGROUND_CHECK) {
6050                 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
6051             }
6052             return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6053         }
6054         // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery.
6055         if (mOnBattery // Short-circuit in common case.
6056                 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS
6057                 && isInRestrictedBucket(
6058                         UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) {
6059             if (DEBUG_BACKGROUND_CHECK) {
6060                 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket");
6061             }
6062             return ActivityManager.APP_START_MODE_DELAYED;
6063         }
6064         // Not in the RESTRICTED bucket so policy is based on AppOp check.
6065         int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND,
6066                 uid, packageName, null, "");
6067         if (DEBUG_BACKGROUND_CHECK) {
6068             Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
6069         }
6070         switch (appop) {
6071             case AppOpsManager.MODE_ALLOWED:
6072                 // If force-background-check is enabled, restrict all apps that aren't allowlisted.
6073                 if (mForceBackgroundCheck &&
6074                         !UserHandle.isCore(uid) &&
6075                         !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) {
6076                     if (DEBUG_BACKGROUND_CHECK) {
6077                         Slog.i(TAG, "Force background check: " +
6078                                 uid + "/" + packageName + " restricted");
6079                     }
6080                     return ActivityManager.APP_START_MODE_DELAYED;
6081                 }
6082                 return ActivityManager.APP_START_MODE_NORMAL;
6083             case AppOpsManager.MODE_IGNORED:
6084                 return ActivityManager.APP_START_MODE_DELAYED;
6085             default:
6086                 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6087         }
6088     }
6089 
6090     // Service launch is available to apps with run-in-background exemptions but
6091     // some other background operations are not.  If we're doing a check
6092     // of service-launch policy, allow those callers to proceed unrestricted.
6093     @GuardedBy(anyOf = {"this", "mProcLock"})
appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)6094     int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
6095         // Persistent app?
6096         if (mPackageManagerInt.isPackagePersistent(packageName)) {
6097             if (DEBUG_BACKGROUND_CHECK) {
6098                 Slog.i(TAG, "App " + uid + "/" + packageName
6099                         + " is persistent; not restricted in background");
6100             }
6101             return ActivityManager.APP_START_MODE_NORMAL;
6102         }
6103 
6104         // Non-persistent but background whitelisted?
6105         if (uidOnBackgroundAllowlistLOSP(uid)) {
6106             if (DEBUG_BACKGROUND_CHECK) {
6107                 Slog.i(TAG, "App " + uid + "/" + packageName
6108                         + " on background allowlist; not restricted in background");
6109             }
6110             return ActivityManager.APP_START_MODE_NORMAL;
6111         }
6112 
6113         // Is this app on the battery whitelist?
6114         if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) {
6115             if (DEBUG_BACKGROUND_CHECK) {
6116                 Slog.i(TAG, "App " + uid + "/" + packageName
6117                         + " on idle allowlist; not restricted in background");
6118             }
6119             return ActivityManager.APP_START_MODE_NORMAL;
6120         }
6121 
6122         // None of the service-policy criteria apply, so we apply the common criteria
6123         return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk);
6124     }
6125 
6126     @GuardedBy(anyOf = {"this", "mProcLock"})
getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6127     int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk,
6128             int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) {
6129         if (mInternal.isPendingTopUid(uid)) {
6130             return ActivityManager.APP_START_MODE_NORMAL;
6131         }
6132         UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
6133         if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
6134                 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
6135                 + (uidRec != null ? uidRec.isIdle() : false));
6136         if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) {
6137             boolean ephemeral;
6138             if (uidRec == null) {
6139                 ephemeral = getPackageManagerInternal().isPackageEphemeral(
6140                         UserHandle.getUserId(uid), packageName);
6141             } else {
6142                 ephemeral = uidRec.isEphemeral();
6143             }
6144 
6145             if (ephemeral) {
6146                 // We are hard-core about ephemeral apps not running in the background.
6147                 return ActivityManager.APP_START_MODE_DISABLED;
6148             } else {
6149                 if (disabledOnly) {
6150                     // The caller is only interested in whether app starts are completely
6151                     // disabled for the given package (that is, it is an instant app).  So
6152                     // we don't need to go further, which is all just seeing if we should
6153                     // apply a "delayed" mode for a regular app.
6154                     return ActivityManager.APP_START_MODE_NORMAL;
6155                 }
6156                 final int startMode = (alwaysRestrict)
6157                         ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk)
6158                         : appServicesRestrictedInBackgroundLOSP(uid, packageName,
6159                                 packageTargetSdk);
6160                 if (DEBUG_BACKGROUND_CHECK) {
6161                     Slog.d(TAG, "checkAllowBackground: uid=" + uid
6162                             + " pkg=" + packageName + " startMode=" + startMode
6163                             + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false)
6164                             + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true));
6165                 }
6166                 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
6167                     // This is an old app that has been forced into a "compatible as possible"
6168                     // mode of background check.  To increase compatibility, we will allow other
6169                     // foreground apps to cause its services to start.
6170                     if (callingPid >= 0) {
6171                         ProcessRecord proc;
6172                         synchronized (mPidsSelfLocked) {
6173                             proc = mPidsSelfLocked.get(callingPid);
6174                         }
6175                         if (proc != null && !ActivityManager.isProcStateBackground(
6176                                 proc.mState.getCurProcState())) {
6177                             // Whoever is instigating this is in the foreground, so we will allow it
6178                             // to go through.
6179                             return ActivityManager.APP_START_MODE_NORMAL;
6180                         }
6181                     }
6182                 }
6183                 return startMode;
6184             }
6185         }
6186         return ActivityManager.APP_START_MODE_NORMAL;
6187     }
6188 
6189     /**
6190      * @return whether a UID is in the system, user or temp doze allowlist.
6191      */
6192     @GuardedBy(anyOf = {"this", "mProcLock"})
isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)6193     boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) {
6194         final int appId = UserHandle.getAppId(uid);
6195 
6196         final int[] allowlist = allowExceptIdleToo
6197                 ? mDeviceIdleExceptIdleAllowlist
6198                 : mDeviceIdleAllowlist;
6199 
6200         return Arrays.binarySearch(allowlist, appId) >= 0
6201                 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0
6202                 || mPendingTempAllowlist.get(uid) != null;
6203     }
6204 
6205     /**
6206      * Is the uid allowlisted to start FGS?
6207      * @param uid
6208      * @return a TempAllowListEntry if the uid is allowed.
6209      *         null if the uid is not allowed.
6210      */
6211     @Nullable
6212     @GuardedBy(anyOf = {"this", "mProcLock"})
isAllowlistedForFgsStartLOSP(int uid)6213     FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) {
6214         if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) {
6215             return FAKE_TEMP_ALLOW_LIST_ITEM;
6216         }
6217         final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid);
6218         return entry == null ? null : entry.second;
6219     }
6220 
6221     private static class GetBackgroundStartPrivilegesFunctor implements Consumer<ProcessRecord> {
6222         private BackgroundStartPrivileges mBackgroundStartPrivileges =
6223                 BackgroundStartPrivileges.NONE;
6224         private int mUid;
6225 
prepare(int uid)6226         void prepare(int uid) {
6227             mUid = uid;
6228             mBackgroundStartPrivileges = BackgroundStartPrivileges.NONE;
6229         }
6230 
6231         @NonNull
getResult()6232         BackgroundStartPrivileges getResult() {
6233             return mBackgroundStartPrivileges;
6234         }
6235 
accept(ProcessRecord pr)6236         public void accept(ProcessRecord pr) {
6237             if (pr.uid == mUid) {
6238                 mBackgroundStartPrivileges =
6239                         mBackgroundStartPrivileges.merge(pr.getBackgroundStartPrivileges());
6240             }
6241         }
6242     }
6243 
6244     private final GetBackgroundStartPrivilegesFunctor mGetBackgroundStartPrivilegesFunctor =
6245             new GetBackgroundStartPrivilegesFunctor();
6246 
6247     /**
6248      * Returns the current complete {@link BackgroundStartPrivileges} of the UID.
6249      */
6250     @NonNull
getBackgroundStartPrivileges(int uid)6251     private BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) {
6252         synchronized (mProcLock) {
6253             final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
6254             if (uidRecord == null) {
6255                 return BackgroundStartPrivileges.NONE;
6256             }
6257             mGetBackgroundStartPrivilegesFunctor.prepare(uid);
6258             uidRecord.forEachProcess(mGetBackgroundStartPrivilegesFunctor);
6259             return mGetBackgroundStartPrivilegesFunctor.getResult();
6260         }
6261     }
6262 
6263     /**
6264      * Returns true if the reasonCode is included in the base set of reasons an app may be
6265      * allowed to schedule a
6266      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}.
6267      * This is a shortcut and <b>DOES NOT</b> include all reasons.
6268      * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases.
6269      */
doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode)6270     static boolean doesReasonCodeAllowSchedulingUserInitiatedJobs(int reasonCode) {
6271         switch (reasonCode) {
6272             case REASON_PROC_STATE_PERSISTENT:
6273             case REASON_PROC_STATE_PERSISTENT_UI:
6274             case REASON_PROC_STATE_TOP:
6275             case REASON_PROC_STATE_BTOP:
6276             case REASON_UID_VISIBLE:
6277             case REASON_SYSTEM_UID:
6278             case REASON_START_ACTIVITY_FLAG:
6279             case REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD:
6280             case REASON_SYSTEM_ALERT_WINDOW_PERMISSION:
6281             case REASON_COMPANION_DEVICE_MANAGER:
6282             case REASON_BACKGROUND_ACTIVITY_PERMISSION:
6283             case REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION:
6284                 return true;
6285         }
6286         return false;
6287     }
6288 
6289     /**
6290      * Returns true if the ProcessRecord has some conditions that allow the app to schedule a
6291      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}.
6292      * This is a shortcut and <b>DOES NOT</b> include all reasons.
6293      * Use {@link #canScheduleUserInitiatedJobs(int, int, String)} to cover all cases.
6294      */
6295     @GuardedBy(anyOf = {"this", "mProcLock"})
isProcessInStateToScheduleUserInitiatedJobsLocked( @ullable ProcessRecord pr, long nowElapsed)6296     private boolean isProcessInStateToScheduleUserInitiatedJobsLocked(
6297             @Nullable ProcessRecord pr, long nowElapsed) {
6298         if (pr == null) {
6299             return false;
6300         }
6301 
6302         final BackgroundStartPrivileges backgroundStartPrivileges =
6303                 pr.getBackgroundStartPrivileges();
6304         // Is the allow activity background start flag on?
6305         if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) {
6306             // REASON_START_ACTIVITY_FLAG;
6307             return true;
6308         }
6309 
6310         final ProcessStateRecord state = pr.mState;
6311         final int procstate = state.getCurProcState();
6312         if (procstate <= PROCESS_STATE_BOUND_TOP) {
6313             if (doesReasonCodeAllowSchedulingUserInitiatedJobs(
6314                     getReasonCodeFromProcState(procstate))) {
6315                 return true;
6316             }
6317         }
6318 
6319         final long lastInvisibleTime = state.getLastInvisibleTime();
6320         if (lastInvisibleTime > 0 && lastInvisibleTime < Long.MAX_VALUE) {
6321             final long timeSinceVisibleMs = nowElapsed - lastInvisibleTime;
6322             if (timeSinceVisibleMs < mConstants.mVisibleToInvisibleUijScheduleGraceDurationMs) {
6323                 // REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD
6324                 return true;
6325             }
6326         }
6327 
6328         final ProcessServiceRecord psr = pr.mServices;
6329         if (psr != null && psr.hasForegroundServices()) {
6330             for (int s = psr.numberOfRunningServices() - 1; s >= 0; --s) {
6331                 final ServiceRecord sr = psr.getRunningServiceAt(s);
6332                 if (sr.isForeground && sr.mAllowUiJobScheduling) {
6333                     return true;
6334                 }
6335             }
6336         }
6337 
6338         return false;
6339     }
6340 
6341     /**
6342      * Returns whether the app in question is in a state where we allow scheduling a
6343      * {@link android.app.job.JobInfo.Builder#setUserInitiated(boolean) user-initiated job}.
6344      */
6345     // TODO(262260570): log allow reason to an atom
canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)6346     boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) {
6347         synchronized (this) {
6348             final ProcessRecord processRecord;
6349             synchronized (mPidsSelfLocked) {
6350                 processRecord = mPidsSelfLocked.get(pid);
6351             }
6352 
6353             final long nowElapsed = SystemClock.elapsedRealtime();
6354             final BackgroundStartPrivileges backgroundStartPrivileges;
6355             if (processRecord != null) {
6356                 if (isProcessInStateToScheduleUserInitiatedJobsLocked(processRecord, nowElapsed)) {
6357                     return true;
6358                 }
6359                 backgroundStartPrivileges = processRecord.getBackgroundStartPrivileges();
6360             } else {
6361                 backgroundStartPrivileges = getBackgroundStartPrivileges(uid);
6362             }
6363             // Is the allow activity background start flag on?
6364             if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) {
6365                 // REASON_START_ACTIVITY_FLAG;
6366                 return true;
6367             }
6368 
6369             // We allow scheduling a user-initiated job when the app is in the TOP or a
6370             // Background Activity Launch approved state. These are cases that indicate the user
6371             // has interacted with the app and therefore it is reasonable to believe the app may
6372             // attempt to schedule a user-initiated job in response to the user interaction.
6373             // As of Android UDC, the conditions required to grant a while-in-use permission
6374             // covers the majority of those cases, and so we piggyback on that logic as the base.
6375             // Missing cases are added after.
6376             if (mServices.canAllowWhileInUsePermissionInFgsLocked(
6377                     pid, uid, pkgName, processRecord, backgroundStartPrivileges)) {
6378                 return true;
6379             }
6380 
6381             final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
6382             if (uidRecord != null) {
6383                 for (int i = uidRecord.getNumOfProcs() - 1; i >= 0; --i) {
6384                     ProcessRecord pr = uidRecord.getProcessRecordByIndex(i);
6385                     if (isProcessInStateToScheduleUserInitiatedJobsLocked(pr, nowElapsed)) {
6386                         return true;
6387                     }
6388                 }
6389             }
6390 
6391             if (mAtmInternal.hasSystemAlertWindowPermission(uid, pid, pkgName)) {
6392                 // REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
6393                 return true;
6394             }
6395 
6396             final int userId = UserHandle.getUserId(uid);
6397             final boolean isCompanionApp = mInternal.isAssociatedCompanionApp(userId, uid);
6398             if (isCompanionApp) {
6399                 if (checkPermission(REQUEST_COMPANION_RUN_IN_BACKGROUND, pid, uid)
6400                         == PERMISSION_GRANTED) {
6401                     // REASON_COMPANION_DEVICE_MANAGER;
6402                     return true;
6403                 }
6404             }
6405         }
6406 
6407         return false;
6408     }
6409 
6410     /**
6411      * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on
6412      * the allowlist
6413      */
6414     @GuardedBy(anyOf = {"this", "mProcLock"})
getPendingTempAllowlistTagForUidLOSP(int uid)6415     String getPendingTempAllowlistTagForUidLOSP(int uid) {
6416         final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid);
6417         return ptw != null ? ptw.tag : null;
6418     }
6419 
6420     @VisibleForTesting
grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)6421     public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) {
6422         getPackageManagerInternal()
6423                 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/);
6424     }
6425 
6426     /**
6427      * @param uri This uri must NOT contain an embedded userId.
6428      * @param userId The userId in which the uri is to be resolved.
6429      */
6430     @Override
checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6431     public int checkUriPermission(Uri uri, int pid, int uid,
6432             final int modeFlags, int userId, IBinder callerToken) {
6433         enforceNotIsolatedCaller("checkUriPermission");
6434 
6435         // Our own process gets to do everything.
6436         if (pid == MY_PID) {
6437             return PackageManager.PERMISSION_GRANTED;
6438         }
6439         if (uid != ROOT_UID) { // bypass the root
6440             if (mPackageManagerInt.filterAppAccess(uid, Binder.getCallingUid())) {
6441                 return PackageManager.PERMISSION_DENIED;
6442             }
6443         }
6444         return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, modeFlags)
6445                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
6446     }
6447 
6448     @Override
checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6449     public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid,
6450             final int modeFlags, int userId, IBinder callerToken) {
6451         final int size = uris.size();
6452         int[] res = new int[size];
6453         // Default value DENIED.
6454         Arrays.fill(res, PackageManager.PERMISSION_DENIED);
6455 
6456         for (int i = 0; i < size; i++) {
6457             final Uri uri = uris.get(i);
6458             final int userIdFromUri = ContentProvider.getUserIdFromUri(uri, userId);
6459             res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid,
6460                     modeFlags, userIdFromUri, callerToken);
6461         }
6462         return res;
6463     }
6464 
6465     /**
6466      * @param uri This uri must NOT contain an embedded userId.
6467      * @param userId The userId in which the uri is to be resolved.
6468      */
6469     @Override
grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6470     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
6471             final int modeFlags, int userId) {
6472         enforceNotIsolatedCaller("grantUriPermission");
6473         GrantUri grantUri = new GrantUri(userId, uri, modeFlags);
6474         synchronized (this) {
6475             final ProcessRecord r = getRecordForAppLOSP(caller);
6476             if (r == null) {
6477                 throw new SecurityException("Unable to find app for caller "
6478                         + caller
6479                         + " when granting permission to uri " + grantUri);
6480             }
6481             if (targetPkg == null) {
6482                 throw new IllegalArgumentException("null target");
6483             }
6484             final int callingUserId = UserHandle.getUserId(r.uid);
6485             if (mPackageManagerInt.filterAppAccess(targetPkg, r.uid, callingUserId)) {
6486                 return;
6487             }
6488 
6489             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
6490                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
6491                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
6492                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
6493 
6494             final Intent intent = new Intent();
6495             intent.setData(uri);
6496             intent.setFlags(modeFlags);
6497 
6498             final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent,
6499                     r.uid, targetPkg, callingUserId);
6500             mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null);
6501         }
6502     }
6503 
6504     /**
6505      * @param uri This uri must NOT contain an embedded userId.
6506      * @param userId The userId in which the uri is to be resolved.
6507      */
6508     @Override
revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6509     public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
6510             final int modeFlags, int userId) {
6511         enforceNotIsolatedCaller("revokeUriPermission");
6512         synchronized (this) {
6513             final ProcessRecord r = getRecordForAppLOSP(caller);
6514             if (r == null) {
6515                 throw new SecurityException("Unable to find app for caller "
6516                         + caller
6517                         + " when revoking permission to uri " + uri);
6518             }
6519             if (uri == null) {
6520                 Slog.w(TAG, "revokeUriPermission: null uri");
6521                 return;
6522             }
6523 
6524             if (!Intent.isAccessUriMode(modeFlags)) {
6525                 return;
6526             }
6527 
6528             final String authority = uri.getAuthority();
6529             final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId,
6530                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
6531             if (pi == null) {
6532                 Slog.w(TAG, "No content provider found for permission revoke: "
6533                         + uri.toSafeString());
6534                 return;
6535             }
6536 
6537             mUgmInternal.revokeUriPermission(targetPackage, r.uid,
6538                     new GrantUri(userId, uri, modeFlags), modeFlags);
6539         }
6540     }
6541 
6542     @Override
showWaitingForDebugger(IApplicationThread who, boolean waiting)6543     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6544         synchronized (mProcLock) {
6545             final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null;
6546             if (app == null) return;
6547 
6548             Message msg = Message.obtain();
6549             msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
6550             msg.obj = app;
6551             msg.arg1 = waiting ? 1 : 0;
6552             mUiHandler.sendMessage(msg);
6553         }
6554     }
6555 
6556     @Override
getMemoryInfo(ActivityManager.MemoryInfo outInfo)6557     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6558         mProcessList.getMemoryInfo(outInfo);
6559     }
6560 
6561     // =========================================================
6562     // TASK MANAGEMENT
6563     // =========================================================
6564 
6565     @Override
getTasks(int maxNum)6566     public List<RunningTaskInfo> getTasks(int maxNum) {
6567         return mActivityTaskManager.getTasks(maxNum);
6568     }
6569 
6570     @Override
cancelTaskWindowTransition(int taskId)6571     public void cancelTaskWindowTransition(int taskId) {
6572         mActivityTaskManager.cancelTaskWindowTransition(taskId);
6573     }
6574 
6575     @Override
setTaskResizeable(int taskId, int resizeableMode)6576     public void setTaskResizeable(int taskId, int resizeableMode) {
6577         mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);
6578     }
6579 
6580     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)6581     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
6582         mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);
6583     }
6584 
6585     @Override
getTaskBounds(int taskId)6586     public Rect getTaskBounds(int taskId) {
6587         return mActivityTaskManager.getTaskBounds(taskId);
6588     }
6589 
6590     @Override
removeTask(int taskId)6591     public boolean removeTask(int taskId) {
6592         return mActivityTaskManager.removeTask(taskId);
6593     }
6594 
6595     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6596     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
6597             int flags, Bundle bOptions) {
6598         mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);
6599     }
6600 
6601     /**
6602      * Attempts to move a task backwards in z-order (the order of activities within the task is
6603      * unchanged).
6604      *
6605      * There are several possible results of this call:
6606      * - if the task is locked, then we will show the lock toast
6607      * - if there is a task behind the provided task, then that task is made visible and resumed as
6608      *   this task is moved to the back
6609      * - otherwise, if there are no other tasks in the stack:
6610      *     - if this task is in the pinned stack, then we remove the stack completely, which will
6611      *       have the effect of moving the task to the top or bottom of the fullscreen stack
6612      *       (depending on whether it is visible)
6613      *     - otherwise, we simply return home and hide this task
6614      *
6615      * @param token A reference to the activity we wish to move
6616      * @param nonRoot If false then this only works if the activity is the root
6617      *                of a task; if true it will work for any activity in a task.
6618      * @return Returns true if the move completed, false if not.
6619      */
6620     @Override
moveActivityTaskToBack(IBinder token, boolean nonRoot)6621     public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
6622         return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot);
6623     }
6624 
6625     @Override
moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)6626     public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) {
6627         mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop);
6628     }
6629 
6630     @Override
getRecentTasks(int maxNum, int flags, int userId)6631     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
6632             int userId) {
6633         return mActivityTaskManager.getRecentTasks(maxNum, flags, userId);
6634     }
6635 
6636     @Override
getAllRootTaskInfos()6637     public List<RootTaskInfo> getAllRootTaskInfos() {
6638         return mActivityTaskManager.getAllRootTaskInfos();
6639     }
6640 
6641     @Override
getTaskForActivity(IBinder token, boolean onlyRoot)6642     public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6643         return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot);
6644     }
6645 
6646     @Override
updateLockTaskPackages(int userId, String[] packages)6647     public void updateLockTaskPackages(int userId, String[] packages) {
6648         mActivityTaskManager.updateLockTaskPackages(userId, packages);
6649     }
6650 
6651     @Override
isInLockTaskMode()6652     public boolean isInLockTaskMode() {
6653         return mActivityTaskManager.isInLockTaskMode();
6654     }
6655 
6656     @Override
getLockTaskModeState()6657     public int getLockTaskModeState() {
6658         return mActivityTaskManager.getLockTaskModeState();
6659     }
6660 
6661     @Override
startSystemLockTaskMode(int taskId)6662     public void startSystemLockTaskMode(int taskId) throws RemoteException {
6663         mActivityTaskManager.startSystemLockTaskMode(taskId);
6664     }
6665 
6666     /**
6667      * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The
6668      * PackageManager could be unavailable at construction time and therefore needs to be accessed
6669      * on demand.
6670      */
6671     @VisibleForTesting
getPackageManager()6672     public IPackageManager getPackageManager() {
6673         return AppGlobals.getPackageManager();
6674     }
6675 
6676     @VisibleForTesting
getPackageManagerInternal()6677     public PackageManagerInternal getPackageManagerInternal() {
6678         // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will
6679         // be set to the same value anyway.
6680         if (mPackageManagerInt == null) {
6681             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
6682         }
6683         return mPackageManagerInt;
6684     }
6685 
getPermissionManagerInternal()6686     private PermissionManagerServiceInternal getPermissionManagerInternal() {
6687         // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will
6688         // be set to the same value anyway.
6689         if (mPermissionManagerInt == null) {
6690             mPermissionManagerInt =
6691                     LocalServices.getService(PermissionManagerServiceInternal.class);
6692         }
6693         return mPermissionManagerInt;
6694     }
6695 
getTestUtilityServiceLocked()6696     private TestUtilityService getTestUtilityServiceLocked() {
6697         if (mTestUtilityService == null) {
6698             mTestUtilityService =
6699                     LocalServices.getService(TestUtilityService.class);
6700         }
6701         return mTestUtilityService;
6702     }
6703 
6704     @Override
appNotResponding(final String reason)6705     public void appNotResponding(final String reason) {
6706         appNotResponding(reason, /*isContinuousAnr*/ false);
6707     }
6708 
appNotResponding(final String reason, boolean isContinuousAnr)6709     public void appNotResponding(final String reason, boolean isContinuousAnr) {
6710         TimeoutRecord timeoutRecord = TimeoutRecord.forApp("App requested: " + reason);
6711         final int callingPid = Binder.getCallingPid();
6712 
6713         timeoutRecord.mLatencyTracker.waitingOnPidLockStarted();
6714         synchronized (mPidsSelfLocked) {
6715             timeoutRecord.mLatencyTracker.waitingOnPidLockEnded();
6716             final ProcessRecord app = mPidsSelfLocked.get(callingPid);
6717             if (app == null) {
6718                 throw new SecurityException("Unknown process: " + callingPid);
6719             }
6720 
6721             mAnrHelper.appNotResponding(app, null, app.info, null, null, false,
6722                     timeoutRecord, isContinuousAnr);
6723         }
6724     }
6725 
appNotResponding(@onNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord)6726     void appNotResponding(@NonNull ProcessRecord anrProcess, @NonNull TimeoutRecord timeoutRecord) {
6727         mAnrHelper.appNotResponding(anrProcess, timeoutRecord);
6728     }
6729 
appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)6730     private void appNotResponding(@NonNull String processName, int uid,
6731             @NonNull TimeoutRecord timeoutRecord) {
6732         Objects.requireNonNull(processName);
6733         Objects.requireNonNull(timeoutRecord);
6734 
6735         synchronized (this) {
6736             final ProcessRecord app = getProcessRecordLocked(processName, uid);
6737             if (app == null) {
6738                 Slog.e(TAG, "Unknown process: " + processName);
6739                 return;
6740             }
6741             mAnrHelper.appNotResponding(app, timeoutRecord);
6742         }
6743     }
6744 
startPersistentApps(int matchFlags)6745     void startPersistentApps(int matchFlags) {
6746         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
6747 
6748         synchronized (this) {
6749             try {
6750                 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
6751                         .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
6752                 for (ApplicationInfo app : apps) {
6753                     if (!"android".equals(app.packageName)) {
6754                         final ProcessRecord proc = addAppLocked(
6755                                 app, null, false, null /* ABI override */,
6756                                 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
6757                         if (proc != null) {
6758                             proc.mProfile.addHostingComponentType(
6759                                     HOSTING_COMPONENT_TYPE_PERSISTENT);
6760                         }
6761                     }
6762                 }
6763             } catch (RemoteException ex) {
6764             }
6765         }
6766     }
6767 
6768     // =========================================================
6769     // CONTENT PROVIDERS
6770     // =========================================================
6771 
getContentProviderHelper()6772     public ContentProviderHelper getContentProviderHelper() {
6773         return mCpHelper;
6774     }
6775 
6776     @Override
getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)6777     public final ContentProviderHolder getContentProvider(
6778             IApplicationThread caller, String callingPackage, String name, int userId,
6779             boolean stable) {
6780         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name);
6781         try {
6782             return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable);
6783         } finally {
6784             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6785         }
6786     }
6787 
6788     @Override
getContentProviderExternal( String name, int userId, IBinder token, String tag)6789     public ContentProviderHolder getContentProviderExternal(
6790             String name, int userId, IBinder token, String tag) {
6791         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name);
6792         try {
6793             return mCpHelper.getContentProviderExternal(name, userId, token, tag);
6794         } finally {
6795             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6796         }
6797     }
6798 
6799     /**
6800      * Drop a content provider from a ProcessRecord's bookkeeping
6801      */
6802     @Override
removeContentProvider(IBinder connection, boolean stable)6803     public void removeContentProvider(IBinder connection, boolean stable) {
6804         mCpHelper.removeContentProvider(connection, stable);
6805     }
6806 
6807     /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */
6808     @Deprecated
6809     @Override
removeContentProviderExternal(String name, IBinder token)6810     public void removeContentProviderExternal(String name, IBinder token) {
6811         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name);
6812         try {
6813             removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId());
6814         } finally {
6815             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6816         }
6817     }
6818 
6819     @Override
removeContentProviderExternalAsUser(String name, IBinder token, int userId)6820     public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) {
6821         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name);
6822         try {
6823             mCpHelper.removeContentProviderExternalAsUser(name, token, userId);
6824         } finally {
6825             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6826         }
6827     }
6828 
6829     @Override
publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)6830     public final void publishContentProviders(IApplicationThread caller,
6831             List<ContentProviderHolder> providers) {
6832         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
6833             final int maxLength = 256;
6834             final StringBuilder sb = new StringBuilder(maxLength);
6835             sb.append("publishContentProviders: ");
6836             if (providers != null) {
6837                 boolean first = true;
6838                 for (int i = 0, size = providers.size(); i < size; i++) {
6839                     final ContentProviderHolder holder = providers.get(i);
6840                     if (holder != null && holder.info != null && holder.info.authority != null) {
6841                         final int len = holder.info.authority.length();
6842                         if (sb.length() + len > maxLength) {
6843                             sb.append("[[TRUNCATED]]");
6844                             break;
6845                         }
6846                         if (!first) {
6847                             sb.append(';');
6848                         } else {
6849                             first = false;
6850                         }
6851                         sb.append(holder.info.authority);
6852                     }
6853                 }
6854             }
6855             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString());
6856         }
6857         try {
6858             mCpHelper.publishContentProviders(caller, providers);
6859         } finally {
6860             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6861         }
6862     }
6863 
6864     @Override
refContentProvider(IBinder connection, int stable, int unstable)6865     public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6866         return mCpHelper.refContentProvider(connection, stable, unstable);
6867     }
6868 
6869     @Override
unstableProviderDied(IBinder connection)6870     public void unstableProviderDied(IBinder connection) {
6871         mCpHelper.unstableProviderDied(connection);
6872     }
6873 
6874     @Override
appNotRespondingViaProvider(IBinder connection)6875     public void appNotRespondingViaProvider(IBinder connection) {
6876         mCpHelper.appNotRespondingViaProvider(connection);
6877     }
6878 
6879     /**
6880      * Filters calls to getType based on permission. If the caller has required permission,
6881      * then it returns the contentProvider#getType.
6882      * Else, it returns the contentProvider#getTypeAnonymous, which does not
6883      * reveal any internal information which should be protected by any permission.
6884      */
6885     @Override
getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback)6886     public void getMimeTypeFilterAsync(Uri uri, int userId, RemoteCallback resultCallback) {
6887         mCpHelper.getMimeTypeFilterAsync(uri, userId, resultCallback);
6888     }
6889 
6890     // =========================================================
6891     // GLOBAL MANAGEMENT
6892     // =========================================================
6893 
6894     @GuardedBy(anyOf = {"this", "mProcLock"})
uidOnBackgroundAllowlistLOSP(final int uid)6895     private boolean uidOnBackgroundAllowlistLOSP(final int uid) {
6896         final int appId = UserHandle.getAppId(uid);
6897         final int[] allowlist = mBackgroundAppIdAllowlist;
6898         for (int i = 0, len = allowlist.length; i < len; i++) {
6899             if (appId == allowlist[i]) {
6900                 return true;
6901             }
6902         }
6903         return false;
6904     }
6905 
6906     @Override
isBackgroundRestricted(String packageName)6907     public boolean isBackgroundRestricted(String packageName) {
6908         final int callingUid = Binder.getCallingUid();
6909         final IPackageManager pm = AppGlobals.getPackageManager();
6910         try {
6911             final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
6912                     UserHandle.getUserId(callingUid));
6913             if (packageUid != callingUid) {
6914                 throw new IllegalArgumentException("Uid " + callingUid
6915                         + " cannot query restriction state for package " + packageName);
6916             }
6917         } catch (RemoteException exc) {
6918             // Ignore.
6919         }
6920         return isBackgroundRestrictedNoCheck(callingUid, packageName);
6921     }
6922 
6923     @VisibleForTesting
isBackgroundRestrictedNoCheck(final int uid, final String packageName)6924     public boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) {
6925         final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
6926                 uid, packageName);
6927         return mode != AppOpsManager.MODE_ALLOWED;
6928     }
6929 
6930     @Override
backgroundAllowlistUid(final int uid)6931     public void backgroundAllowlistUid(final int uid) {
6932         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
6933             throw new SecurityException("Only the OS may call backgroundAllowlistUid()");
6934         }
6935 
6936         if (DEBUG_BACKGROUND_CHECK) {
6937             Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist");
6938         }
6939         synchronized (this) {
6940             synchronized (mProcLock) {
6941                 final int num = mBackgroundAppIdAllowlist.length;
6942                 int[] newList = new int[num + 1];
6943                 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num);
6944                 newList[num] = UserHandle.getAppId(uid);
6945                 mBackgroundAppIdAllowlist = newList;
6946             }
6947         }
6948     }
6949 
6950     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)6951     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
6952             String abiOverride, int zygotePolicyFlags) {
6953         return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */,
6954                 abiOverride, zygotePolicyFlags);
6955     }
6956 
6957     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)6958     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
6959             boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) {
6960         return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks,
6961                 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags);
6962     }
6963 
6964     // TODO: Move to ProcessList?
6965     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)6966     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
6967             boolean disableHiddenApiChecks, boolean disableTestApiChecks,
6968             String abiOverride, int zygotePolicyFlags) {
6969         return addAppLocked(
6970                 info,
6971                 customProcess,
6972                 isolated,
6973                 /* isSdkSandbox= */ false,
6974                 /* sdkSandboxUid= */ 0,
6975                 /* sdkSandboxClientAppPackage= */ null,
6976                 disableHiddenApiChecks,
6977                 disableTestApiChecks,
6978                 abiOverride,
6979                 zygotePolicyFlags);
6980     }
6981 
addAppLocked( ApplicationInfo info, String customProcess, boolean isolated, boolean isSdkSandbox, int sdkSandboxUid, @Nullable String sdkSandboxClientAppPackage, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)6982     final ProcessRecord addAppLocked(
6983             ApplicationInfo info,
6984             String customProcess,
6985             boolean isolated,
6986             boolean isSdkSandbox,
6987             int sdkSandboxUid,
6988             @Nullable String sdkSandboxClientAppPackage,
6989             boolean disableHiddenApiChecks,
6990             boolean disableTestApiChecks,
6991             String abiOverride,
6992             int zygotePolicyFlags) {
6993         ProcessRecord app;
6994         if (!isolated) {
6995             app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
6996                     info.uid);
6997         } else {
6998             app = null;
6999         }
7000 
7001         if (app == null) {
7002             app = mProcessList.newProcessRecordLocked(
7003                     info,
7004                     customProcess,
7005                     isolated,
7006                     /* isolatedUid= */0,
7007                     isSdkSandbox,
7008                     sdkSandboxUid,
7009                     sdkSandboxClientAppPackage,
7010                     new HostingRecord(HostingRecord.HOSTING_TYPE_ADDED_APPLICATION,
7011                             customProcess != null ? customProcess : info.processName));
7012             updateLruProcessLocked(app, false, null);
7013             updateOomAdjLocked(app, OOM_ADJ_REASON_PROCESS_BEGIN);
7014         }
7015 
7016         // Report usage as process is persistent and being started.
7017         mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid),
7018                 Event.APP_COMPONENT_USED);
7019 
7020         // This package really, really can not be stopped.
7021         // TODO: how set package stopped state should work for sdk sandboxes?
7022         if (!isSdkSandbox) {
7023             try {
7024                 mPackageManagerInt.setPackageStoppedState(
7025                         info.packageName, false, UserHandle.getUserId(app.uid));
7026             } catch (IllegalArgumentException e) {
7027                 Slog.w(TAG, "Failed trying to unstop package "
7028                         + info.packageName + ": " + e);
7029             }
7030         }
7031 
7032         if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
7033             app.setPersistent(true);
7034             app.mState.setMaxAdj(ProcessList.PERSISTENT_PROC_ADJ);
7035         }
7036         if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7037             mPersistentStartingProcesses.add(app);
7038             mProcessList.startProcessLocked(app, new HostingRecord(
7039                     HostingRecord.HOSTING_TYPE_ADDED_APPLICATION,
7040                     customProcess != null ? customProcess : app.processName),
7041                     zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks,
7042                     abiOverride);
7043         }
7044 
7045         return app;
7046     }
7047 
unhandledBack()7048     public void unhandledBack() {
7049         mActivityTaskManager.unhandledBack();
7050     }
7051 
7052     // TODO: Replace this method with one that returns a bound IContentProvider.
openContentUri(String uriString)7053     public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
7054         enforceNotIsolatedCaller("openContentUri");
7055         final int userId = UserHandle.getCallingUserId();
7056         final Uri uri = Uri.parse(uriString);
7057         String name = uri.getAuthority();
7058         ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null,
7059                 Binder.getCallingUid(), "*opencontent*", userId);
7060         ParcelFileDescriptor pfd = null;
7061         if (cph != null) {
7062             try {
7063                 // This method is exposed to the VNDK and to avoid changing its
7064                 // signature we just use the first package in the UID. For shared
7065                 // UIDs we may blame the wrong app but that is Okay as they are
7066                 // in the same security/privacy sandbox.
7067                 final int uid = Binder.getCallingUid();
7068                 // Here we handle some of the special UIDs (mediaserver, systemserver, etc)
7069                 final String packageName = AppOpsManager.resolvePackageName(uid,
7070                         /*packageName*/ null);
7071                 final AndroidPackage androidPackage;
7072                 if (packageName != null) {
7073                     androidPackage = mPackageManagerInt.getPackage(packageName);
7074                 } else {
7075                     androidPackage = mPackageManagerInt.getPackage(uid);
7076                 }
7077                 if (androidPackage == null) {
7078                     Log.e(TAG, "Cannot find package for uid: " + uid);
7079                     return null;
7080                 }
7081 
7082                 final ApplicationInfo appInfo = mPackageManagerInt.getApplicationInfo(
7083                         androidPackage.getPackageName(), /*flags*/0, Process.SYSTEM_UID,
7084                         UserHandle.USER_SYSTEM);
7085                 if (!appInfo.isVendor() && !appInfo.isSystemApp() && !appInfo.isSystemExt()
7086                         && !appInfo.isProduct()) {
7087                     Log.e(TAG, "openContentUri may only be used by vendor/system/product.");
7088                     return null;
7089                 }
7090 
7091                 final AttributionSource attributionSource = new AttributionSource(
7092                         Binder.getCallingUid(), androidPackage.getPackageName(), null);
7093                 pfd = cph.provider.openFile(attributionSource, uri, "r", null);
7094             } catch (FileNotFoundException e) {
7095                 // do nothing; pfd will be returned null
7096             } finally {
7097                 // Ensure we're done with the provider.
7098                 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId);
7099             }
7100         } else {
7101             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
7102         }
7103         return pfd;
7104     }
7105 
reportGlobalUsageEvent(int event)7106     void reportGlobalUsageEvent(int event) {
7107         final int currentUserId = mUserController.getCurrentUserId();
7108         mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event);
7109         int[] profiles = mUserController.getCurrentProfileIds();
7110         if (profiles != null) {
7111             for (int i = profiles.length - 1; i >= 0; i--) {
7112                 if (profiles[i] == currentUserId) {
7113                     continue;
7114                 }
7115                 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event);
7116             }
7117         }
7118     }
7119 
reportCurWakefulnessUsageEvent()7120     void reportCurWakefulnessUsageEvent() {
7121         reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE
7122                 ? UsageEvents.Event.SCREEN_INTERACTIVE
7123                 : UsageEvents.Event.SCREEN_NON_INTERACTIVE);
7124     }
7125 
onWakefulnessChanged(int wakefulness)7126     void onWakefulnessChanged(int wakefulness) {
7127         synchronized (this) {
7128             boolean wasAwake = mWakefulness.getAndSet(wakefulness)
7129                     == PowerManagerInternal.WAKEFULNESS_AWAKE;
7130             boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
7131 
7132             if (wasAwake != isAwake) {
7133                 // Also update state in a special way for running foreground services UI.
7134                 mServices.updateScreenStateLocked(isAwake);
7135                 reportCurWakefulnessUsageEvent();
7136                 mActivityTaskManager.onScreenAwakeChanged(isAwake);
7137                 mOomAdjProfiler.onWakefulnessChanged(wakefulness);
7138                 mOomAdjuster.onWakefulnessChanged(wakefulness);
7139 
7140                 updateOomAdjLocked(OOM_ADJ_REASON_UI_VISIBILITY);
7141             }
7142         }
7143     }
7144 
7145     @Override
notifyCleartextNetwork(int uid, byte[] firstPacket)7146     public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
7147         mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
7148     }
7149 
7150     @Override
shutdown(int timeout)7151     public boolean shutdown(int timeout) {
7152         if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7153                 != PackageManager.PERMISSION_GRANTED) {
7154             throw new SecurityException("Requires permission "
7155                     + android.Manifest.permission.SHUTDOWN);
7156         }
7157 
7158         final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout);
7159 
7160         mAppOpsService.shutdown();
7161         if (mUsageStatsService != null) {
7162             mUsageStatsService.prepareShutdown();
7163         }
7164         mBatteryStatsService.shutdown();
7165         mProcessStats.shutdown();
7166 
7167         return timedout;
7168     }
7169 
7170     @Override
notifyLockedProfile(@serIdInt int userId)7171     public void notifyLockedProfile(@UserIdInt int userId) {
7172         mAtmInternal.notifyLockedProfile(userId);
7173     }
7174 
7175     @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7176     public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7177         mAtmInternal.startConfirmDeviceCredentialIntent(intent, options);
7178     }
7179 
7180     @Override
stopAppSwitches()7181     public void stopAppSwitches() {
7182         mActivityTaskManager.stopAppSwitches();
7183     }
7184 
7185     @Override
resumeAppSwitches()7186     public void resumeAppSwitches() {
7187         mActivityTaskManager.resumeAppSwitches();
7188     }
7189 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7190     public void setDebugApp(String packageName, boolean waitForDebugger,
7191             boolean persistent) {
7192         setDebugApp(packageName, waitForDebugger, persistent, false);
7193     }
7194 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent, boolean suspendUponWait)7195     private void setDebugApp(String packageName, boolean waitForDebugger,
7196             boolean persistent, boolean suspendUponWait) {
7197         enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7198                 "setDebugApp()");
7199 
7200         final long ident = Binder.clearCallingIdentity();
7201         try {
7202             // Note that this is not really thread safe if there are multiple
7203             // callers into it at the same time, but that's not a situation we
7204             // care about.
7205             if (persistent) {
7206                 final ContentResolver resolver = mContext.getContentResolver();
7207                 Settings.Global.putString(
7208                     resolver, Settings.Global.DEBUG_APP,
7209                     packageName);
7210                 Settings.Global.putInt(
7211                     resolver, Settings.Global.WAIT_FOR_DEBUGGER,
7212                     waitForDebugger ? 1 : 0);
7213             }
7214 
7215             synchronized (this) {
7216                 if (!persistent) {
7217                     mOrigDebugApp = mDebugApp;
7218                     mOrigWaitForDebugger = mWaitForDebugger;
7219                 }
7220                 mDebugApp = packageName;
7221                 mWaitForDebugger = waitForDebugger;
7222                 mSuspendUponWait = suspendUponWait;
7223                 mDebugTransient = !persistent;
7224                 if (packageName != null) {
7225                     forceStopPackageLocked(packageName, -1, false, false, true, true,
7226                             false, UserHandle.USER_ALL, "set debug app");
7227                 }
7228             }
7229         } finally {
7230             Binder.restoreCallingIdentity(ident);
7231         }
7232     }
7233 
7234     /**
7235      * Set or remove an agent to be run whenever an app with the given process name starts.
7236      *
7237      * This method will not check whether the given process name matches a debuggable app. That
7238      * would require scanning all current packages, and a rescan when new packages are installed
7239      * or updated.
7240      *
7241      * Instead, do the check when an application is started and matched to a stored agent.
7242      *
7243      * @param packageName the process name of the app.
7244      * @param agent the agent string to be used, or null to remove any previously set agent.
7245      */
7246     @Override
setAgentApp(@onNull String packageName, @Nullable String agent)7247     public void setAgentApp(@NonNull String packageName, @Nullable String agent) {
7248         // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
7249         // its own permission.
7250         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7251                 != PackageManager.PERMISSION_GRANTED) {
7252             throw new SecurityException(
7253                     "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7254         }
7255 
7256         synchronized (mAppProfiler.mProfilerLock) {
7257             mAppProfiler.setAgentAppLPf(packageName, agent);
7258         }
7259     }
7260 
setTrackAllocationApp(ApplicationInfo app, String processName)7261     void setTrackAllocationApp(ApplicationInfo app, String processName) {
7262         enforceDebuggable(app);
7263 
7264         synchronized (mProcLock) {
7265             mTrackAllocationApp = processName;
7266         }
7267     }
7268 
setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo, ApplicationInfo sdkSandboxClientApp)7269     void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo,
7270             ApplicationInfo sdkSandboxClientApp) {
7271         synchronized (mAppProfiler.mProfilerLock) {
7272             if (!Build.IS_DEBUGGABLE) {
7273                 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7274                 boolean isAppProfileable = app.isProfileableByShell();
7275 
7276                 if (sdkSandboxClientApp != null) {
7277                     isAppDebuggable |=
7278                             (sdkSandboxClientApp.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7279                     isAppProfileable |= sdkSandboxClientApp.isProfileableByShell();
7280                 }
7281                 if (!isAppDebuggable && !isAppProfileable) {
7282                     throw new SecurityException("Process not debuggable, "
7283                             + "and not profileable by shell: " + app.packageName);
7284                 }
7285             }
7286             mAppProfiler.setProfileAppLPf(processName, profilerInfo);
7287         }
7288     }
7289 
setNativeDebuggingAppLocked(ApplicationInfo app, String processName)7290     void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
7291         enforceDebuggable(app);
7292         mNativeDebuggingApp = processName;
7293     }
7294 
7295     @Override
setAlwaysFinish(boolean enabled)7296     public void setAlwaysFinish(boolean enabled) {
7297         enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7298                 "setAlwaysFinish()");
7299 
7300         final long ident = Binder.clearCallingIdentity();
7301         try {
7302             Settings.Global.putInt(
7303                     mContext.getContentResolver(),
7304                     Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7305 
7306             synchronized (this) {
7307                 mAlwaysFinishActivities = enabled;
7308             }
7309         } finally {
7310             Binder.restoreCallingIdentity(ident);
7311         }
7312     }
7313 
7314     @Override
setActivityController(IActivityController controller, boolean imAMonkey)7315     public void setActivityController(IActivityController controller, boolean imAMonkey) {
7316         if (controller != null) {
7317             Binder.allowBlocking(controller.asBinder());
7318         }
7319         mActivityTaskManager.setActivityController(controller, imAMonkey);
7320     }
7321 
7322     @Override
setUserIsMonkey(boolean userIsMonkey)7323     public void setUserIsMonkey(boolean userIsMonkey) {
7324         synchronized (mProcLock) {
7325             synchronized (mPidsSelfLocked) {
7326                 final int callingPid = Binder.getCallingPid();
7327                 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
7328                 if (proc == null) {
7329                     throw new SecurityException("Unknown process: " + callingPid);
7330                 }
7331                 if (proc.getActiveInstrumentation() == null
7332                         || proc.getActiveInstrumentation().mUiAutomationConnection == null) {
7333                     throw new SecurityException("Only an instrumentation process "
7334                             + "with a UiAutomation can call setUserIsMonkey");
7335                 }
7336             }
7337             mUserIsMonkey = userIsMonkey;
7338         }
7339     }
7340 
7341     @Override
isUserAMonkey()7342     public boolean isUserAMonkey() {
7343         synchronized (mProcLock) {
7344             // If there is a controller also implies the user is a monkey.
7345             return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey();
7346         }
7347     }
7348 
7349     @Override
requestSystemServerHeapDump()7350     public void requestSystemServerHeapDump() {
7351         if (!Build.IS_DEBUGGABLE) {
7352             Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build");
7353             return;
7354         }
7355         if (Binder.getCallingUid() != SYSTEM_UID) {
7356             // This also intentionally excludes secondary profiles from calling this.
7357             throw new SecurityException(
7358                     "Only the system process is allowed to request a system heap dump");
7359         }
7360         ProcessRecord pr;
7361         synchronized (mPidsSelfLocked) {
7362             pr = mPidsSelfLocked.get(myPid());
7363         }
7364         if (pr == null) {
7365             Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid());
7366             return;
7367         }
7368         synchronized (mAppProfiler.mProfilerLock) {
7369             mAppProfiler.startHeapDumpLPf(pr.mProfile, true);
7370         }
7371     }
7372 
7373     /**
7374      * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set
7375      * title and description
7376      */
7377     @Override
requestBugReport(@ugreportParams.BugreportMode int bugreportType)7378     public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) {
7379         requestBugReportWithDescription(null, null, bugreportType, 0L);
7380     }
7381 
7382     /**
7383      * Takes a bugreport using bug report API ({@code BugreportManager}) which gets
7384      * triggered by sending a broadcast to Shell.
7385      */
7386     @Override
requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)7387     public void requestBugReportWithDescription(@Nullable String shareTitle,
7388             @Nullable String shareDescription, int bugreportType) {
7389         requestBugReportWithDescription(shareTitle, shareDescription, bugreportType, /*nonce*/ 0L);
7390     }
7391 
7392     /**
7393      * Takes a bugreport using bug report API ({@code BugreportManager}) which gets
7394      * triggered by sending a broadcast to Shell.
7395      */
requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType, long nonce)7396     public void requestBugReportWithDescription(@Nullable String shareTitle,
7397             @Nullable String shareDescription, int bugreportType, long nonce) {
7398         String type = null;
7399         switch (bugreportType) {
7400             case BugreportParams.BUGREPORT_MODE_FULL:
7401                 type = "bugreportfull";
7402                 break;
7403             case BugreportParams.BUGREPORT_MODE_INTERACTIVE:
7404                 type = "bugreportplus";
7405                 break;
7406             case BugreportParams.BUGREPORT_MODE_REMOTE:
7407                 type = "bugreportremote";
7408                 break;
7409             case BugreportParams.BUGREPORT_MODE_WEAR:
7410                 type = "bugreportwear";
7411                 break;
7412             case BugreportParams.BUGREPORT_MODE_TELEPHONY:
7413                 type = "bugreporttelephony";
7414                 break;
7415             case BugreportParams.BUGREPORT_MODE_WIFI:
7416                 type = "bugreportwifi";
7417                 break;
7418             default:
7419                 throw new IllegalArgumentException(
7420                     "Provided bugreport type is not correct, value: "
7421                         + bugreportType);
7422         }
7423         // Always log caller, even if it does not have permission to dump.
7424         Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid());
7425         enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
7426 
7427         if (!TextUtils.isEmpty(shareTitle)) {
7428             if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
7429                 String errorStr = "shareTitle should be less than "
7430                         + MAX_BUGREPORT_TITLE_SIZE + " characters";
7431                 throw new IllegalArgumentException(errorStr);
7432             }
7433             if (!TextUtils.isEmpty(shareDescription)) {
7434                 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) {
7435                     String errorStr = "shareDescription should be less than "
7436                             + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters";
7437                     throw new IllegalArgumentException(errorStr);
7438                 }
7439             }
7440             Slog.d(TAG, "Bugreport notification title " + shareTitle
7441                     + " description " + shareDescription);
7442         }
7443         // Create intent to trigger Bugreport API via Shell
7444         Intent triggerShellBugreport = new Intent();
7445         triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED);
7446         triggerShellBugreport.setPackage(SHELL_APP_PACKAGE);
7447         triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType);
7448         triggerShellBugreport.putExtra(EXTRA_BUGREPORT_NONCE, nonce);
7449         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
7450         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
7451         if (shareTitle != null) {
7452             triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle);
7453         }
7454         if (shareDescription != null) {
7455             triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription);
7456         }
7457         final long identity = Binder.clearCallingIdentity();
7458         try {
7459             // Send broadcast to shell to trigger bugreport using Bugreport API
7460             // Always start the shell process on the current user to ensure that
7461             // the foreground user can see all bugreport notifications.
7462             // In case of BUGREPORT_MODE_REMOTE send the broadcast to SYSTEM user as the device
7463             // owner apps are running on the SYSTEM user.
7464             if (bugreportType == BugreportParams.BUGREPORT_MODE_REMOTE) {
7465                 mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM);
7466             } else {
7467                 mContext.sendBroadcastAsUser(triggerShellBugreport,
7468                         getCurrentUser().getUserHandle());
7469             }
7470         } finally {
7471             Binder.restoreCallingIdentity(identity);
7472         }
7473     }
7474 
7475     /**
7476      * Takes a telephony bugreport with title and description
7477      */
7478     @Override
requestTelephonyBugReport(String shareTitle, String shareDescription)7479     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
7480         requestBugReportWithDescription(shareTitle, shareDescription,
7481                 BugreportParams.BUGREPORT_MODE_TELEPHONY);
7482     }
7483 
7484     /**
7485      * Takes a minimal bugreport of Wifi-related state with pre-set title and description
7486      */
7487     @Override
requestWifiBugReport(String shareTitle, String shareDescription)7488     public void requestWifiBugReport(String shareTitle, String shareDescription) {
7489         requestBugReportWithDescription(shareTitle, shareDescription,
7490                 BugreportParams.BUGREPORT_MODE_WIFI);
7491     }
7492 
7493     /**
7494      * Takes an interactive bugreport with a progress notification
7495      */
7496     @Override
requestInteractiveBugReport()7497     public void requestInteractiveBugReport() {
7498         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE);
7499     }
7500 
7501     /**
7502      * Takes an interactive bugreport with a progress notification. Also, shows the given title and
7503      * description on the final share notification
7504      */
7505     @Override
requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)7506     public void requestInteractiveBugReportWithDescription(String shareTitle,
7507             String shareDescription) {
7508         requestBugReportWithDescription(shareTitle, shareDescription,
7509                 BugreportParams.BUGREPORT_MODE_INTERACTIVE);
7510     }
7511 
7512     /**
7513      * Takes a bugreport with minimal user interference
7514      */
7515     @Override
requestFullBugReport()7516     public void requestFullBugReport() {
7517         requestBugReportWithDescription(null, null,  BugreportParams.BUGREPORT_MODE_FULL);
7518     }
7519 
7520     /**
7521      * Takes a bugreport remotely
7522      */
7523     @Override
requestRemoteBugReport(long nonce)7524     public void requestRemoteBugReport(long nonce) {
7525         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE, nonce);
7526     }
7527 
7528     /**
7529      * Launches a bugreport-whitelisted app to handle a bugreport.
7530      *
7531      * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can
7532      * be predefined in the config, meant to be launched with the primary user. The user can
7533      * override this with a different (or same) handler app on possibly a different user. This is
7534      * useful for capturing bug reports from work profile, for instance.
7535      *
7536      * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false
7537      * otherwise.
7538      */
7539     @Override
launchBugReportHandlerApp()7540     public boolean launchBugReportHandlerApp() {
7541 
7542         Context currentUserContext = mContext.createContextAsUser(getCurrentUser().getUserHandle(),
7543                 /* flags= */ 0);
7544         if (!BugReportHandlerUtil.isBugReportHandlerEnabled(currentUserContext)) {
7545             return false;
7546         }
7547 
7548         // Always log caller, even if it does not have permission to dump.
7549         Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid());
7550         enforceCallingPermission(android.Manifest.permission.DUMP,
7551                 "launchBugReportHandlerApp");
7552 
7553         return BugReportHandlerUtil.launchBugReportHandlerApp(currentUserContext);
7554     }
7555 
7556     /**
7557      * Get packages of bugreport-whitelisted apps to handle a bug report.
7558      *
7559      * @return packages of bugreport-whitelisted apps to handle a bug report.
7560      */
7561     @Override
getBugreportWhitelistedPackages()7562     public List<String> getBugreportWhitelistedPackages() {
7563         enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING,
7564                 "getBugreportWhitelistedPackages");
7565         return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages());
7566     }
7567 
registerProcessObserver(IProcessObserver observer)7568     public void registerProcessObserver(IProcessObserver observer) {
7569         enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7570                 "registerProcessObserver()");
7571         mProcessList.registerProcessObserver(observer);
7572     }
7573 
7574     @Override
unregisterProcessObserver(IProcessObserver observer)7575     public void unregisterProcessObserver(IProcessObserver observer) {
7576         mProcessList.unregisterProcessObserver(observer);
7577     }
7578 
7579     @Override
getUidProcessState(int uid, String callingPackage)7580     public int getUidProcessState(int uid, String callingPackage) {
7581         if (!hasUsageStatsPermission(callingPackage)) {
7582             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7583                     "getUidProcessState");
7584         }
7585         // In case the caller is requesting processState of an app in a different user,
7586         // then verify the caller has INTERACT_ACROSS_USERS_FULL permission
7587         mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7588                 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY,
7589                 "getUidProcessState", callingPackage); // Ignore return value
7590 
7591         synchronized (mProcLock) {
7592             if (mPendingStartActivityUids.isPendingTopUid(uid)) {
7593                 return PROCESS_STATE_TOP;
7594             }
7595             return mProcessList.getUidProcStateLOSP(uid);
7596         }
7597     }
7598 
7599     @Override
getUidProcessCapabilities(int uid, String callingPackage)7600     public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) {
7601         if (!hasUsageStatsPermission(callingPackage)) {
7602             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7603                     "getUidProcessState");
7604         }
7605         // In case the caller is requesting processCapabilities of an app in a different user,
7606         // then verify the caller has INTERACT_ACROSS_USERS_FULL permission
7607         mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7608                 UserHandle.getUserId(uid), false /* allowAll */, ALLOW_FULL_ONLY,
7609                 "getUidProcessCapabilities", callingPackage); // Ignore return value
7610 
7611         synchronized (mProcLock) {
7612             return mProcessList.getUidProcessCapabilityLOSP(uid);
7613         }
7614     }
7615 
7616     @Override
registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)7617     public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
7618             String callingPackage) {
7619         if (!hasUsageStatsPermission(callingPackage)) {
7620             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7621                     "registerUidObserver");
7622         }
7623         mUidObserverController.register(observer, which, cutpoint, callingPackage,
7624                 Binder.getCallingUid(), /*uids*/null);
7625     }
7626 
7627     /**
7628      * Registers a UidObserver with a uid filter.
7629      *
7630      * @param observer The UidObserver implementation to register.
7631      * @param which    A bitmask of events to observe. See ActivityManager.UID_OBSERVER_*.
7632      * @param cutpoint The cutpoint for onUidStateChanged events. When the state crosses this
7633      *                 threshold in either direction, onUidStateChanged will be called.
7634      * @param callingPackage The name of the calling package.
7635      * @param uids     A list of uids to watch. If all uids are to be watched, use
7636      *                 registerUidObserver instead.
7637      * @throws RemoteException
7638      * @return Returns A binder token identifying the UidObserver registration.
7639      */
7640     @Override
registerUidObserverForUids(IUidObserver observer, int which, int cutpoint, String callingPackage, int[] uids)7641     public IBinder registerUidObserverForUids(IUidObserver observer, int which, int cutpoint,
7642             String callingPackage, int[] uids) {
7643         if (!hasUsageStatsPermission(callingPackage)) {
7644             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7645                     "registerUidObserver");
7646         }
7647         return mUidObserverController.register(observer, which, cutpoint, callingPackage,
7648                 Binder.getCallingUid(), uids);
7649     }
7650 
7651     @Override
unregisterUidObserver(IUidObserver observer)7652     public void unregisterUidObserver(IUidObserver observer) {
7653         mUidObserverController.unregister(observer);
7654     }
7655 
7656     /**
7657      * Adds a uid to the list of uids that a UidObserver will receive updates about.
7658      *
7659      * @param observerToken  The binder token identifying the UidObserver registration.
7660      * @param callingPackage The name of the calling package.
7661      * @param uid            The uid to watch.
7662      * @throws RemoteException
7663      */
7664     @Override
addUidToObserver(IBinder observerToken, String callingPackage, int uid)7665     public void addUidToObserver(IBinder observerToken, String callingPackage, int uid) {
7666         if (!hasUsageStatsPermission(callingPackage)) {
7667             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7668                     "registerUidObserver");
7669         }
7670         mUidObserverController.addUidToObserver(observerToken, uid);
7671     }
7672 
7673     /**
7674      * Removes a uid from the list of uids that a UidObserver will receive updates about.
7675      *
7676      * @param observerToken  The binder token identifying the UidObserver registration.
7677      * @param callingPackage The name of the calling package.
7678      * @param uid            The uid to stop watching.
7679      * @throws RemoteException
7680      */
7681     @Override
removeUidFromObserver(IBinder observerToken, String callingPackage, int uid)7682     public void removeUidFromObserver(IBinder observerToken, String callingPackage, int uid) {
7683         if (!hasUsageStatsPermission(callingPackage)) {
7684             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7685                     "registerUidObserver");
7686         }
7687         mUidObserverController.removeUidFromObserver(observerToken, uid);
7688     }
7689 
7690     @Override
isUidActive(int uid, String callingPackage)7691     public boolean isUidActive(int uid, String callingPackage) {
7692         if (!hasUsageStatsPermission(callingPackage)) {
7693             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7694                     "isUidActive");
7695         }
7696         synchronized (mProcLock) {
7697             if (isUidActiveLOSP(uid)) {
7698                 return true;
7699             }
7700         }
7701         return mInternal.isPendingTopUid(uid);
7702     }
7703 
7704     @GuardedBy(anyOf = {"this", "mProcLock"})
isUidActiveLOSP(int uid)7705     boolean isUidActiveLOSP(int uid) {
7706         final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
7707         return uidRecord != null && !uidRecord.isSetIdle();
7708     }
7709 
7710     @GuardedBy("mUidFrozenStateChangedCallbackList")
7711     private final RemoteCallbackList<IUidFrozenStateChangedCallback>
7712             mUidFrozenStateChangedCallbackList = new RemoteCallbackList<>();
7713 
7714     /**
7715      * Register a {@link IUidFrozenStateChangedCallback} to receive Uid frozen state events.
7716      *
7717      * @param callback remote callback object to be registered
7718      */
7719     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
7720     @Override
registerUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)7721     public void registerUidFrozenStateChangedCallback(
7722             @NonNull IUidFrozenStateChangedCallback callback) {
7723         Preconditions.checkNotNull(callback, "callback cannot be null");
7724         enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7725                 "registerUidFrozenStateChangedCallback()");
7726         synchronized (mUidFrozenStateChangedCallbackList) {
7727             final boolean registered = mUidFrozenStateChangedCallbackList.register(callback);
7728             if (!registered) {
7729                 Slog.w(TAG, "Failed to register with RemoteCallbackList!");
7730             }
7731         }
7732     }
7733 
7734     /**
7735      * Unregister a {@link IUidFrozenStateChangedCallback}.
7736      *
7737      * @param callback remote callback object to be unregistered
7738      */
7739     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
7740     @Override
unregisterUidFrozenStateChangedCallback( @onNull IUidFrozenStateChangedCallback callback)7741     public void unregisterUidFrozenStateChangedCallback(
7742             @NonNull IUidFrozenStateChangedCallback callback) {
7743         Preconditions.checkNotNull(callback, "callback cannot be null");
7744         enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7745                 "unregisterUidFrozenStateChangedCallback()");
7746         synchronized (mUidFrozenStateChangedCallbackList) {
7747             mUidFrozenStateChangedCallbackList.unregister(callback);
7748         }
7749     }
7750 
7751     /**
7752      * Query the frozen state of a list of UIDs.
7753      *
7754      * @param uids the array of UIDs which the client would like to know the frozen state of.
7755      * @return An array containing the frozen state for each requested UID, by index. Will be set
7756      *               to {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_FROZEN}
7757      *               if the UID is frozen. If the UID is not frozen or not found,
7758      *               {@link UidFrozenStateChangedCallback#UID_FROZEN_STATE_UNFROZEN}
7759      *               will be set.
7760      *
7761      * @hide
7762      */
7763     @RequiresPermission(Manifest.permission.PACKAGE_USAGE_STATS)
7764     @Override
getUidFrozenState(@onNull int[] uids)7765     public @NonNull int[] getUidFrozenState(@NonNull int[] uids) {
7766         Preconditions.checkNotNull(uids, "uid array cannot be null");
7767         enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
7768                 "getUidFrozenState()");
7769 
7770         final int[] frozenStates = new int[uids.length];
7771         synchronized (mProcLock) {
7772             for (int i = 0; i < uids.length; i++) {
7773                 final UidRecord uidRec = mProcessList.mActiveUids.get(uids[i]);
7774                 if (uidRec != null && uidRec.areAllProcessesFrozen()) {
7775                     frozenStates[i] = UID_FROZEN_STATE_FROZEN;
7776                 } else {
7777                     frozenStates[i] = UID_FROZEN_STATE_UNFROZEN;
7778                 }
7779             }
7780         }
7781         return frozenStates;
7782     }
7783 
7784     /**
7785      * Notify the system that a UID has been frozen or unfrozen.
7786      *
7787      * @param uids The Uid(s) in question
7788      * @param frozenStates Frozen state for each UID index
7789      *
7790      * @hide
7791      */
reportUidFrozenStateChanged(@onNull int[] uids, @UidFrozenState int[] frozenStates)7792     public void reportUidFrozenStateChanged(@NonNull int[] uids,
7793             @UidFrozenState int[] frozenStates) {
7794         synchronized (mUidFrozenStateChangedCallbackList) {
7795             final int n = mUidFrozenStateChangedCallbackList.beginBroadcast();
7796             for (int i = 0; i < n; i++) {
7797                 try {
7798                     mUidFrozenStateChangedCallbackList.getBroadcastItem(i).onUidFrozenStateChanged(
7799                             uids, frozenStates);
7800                 } catch (RemoteException e) {
7801                     /*
7802                     * The process at the other end has died or otherwise gone away.
7803                     * According to spec, RemoteCallbacklist will take care of unregistering any
7804                     * object associated with that process - we are safe to ignore the exception
7805                     * here.
7806                     */
7807                 }
7808             }
7809             mUidFrozenStateChangedCallbackList.finishBroadcast();
7810         }
7811     }
7812 
7813     @Override
setPersistentVrThread(int tid)7814     public void setPersistentVrThread(int tid) {
7815         mActivityTaskManager.setPersistentVrThread(tid);
7816     }
7817 
7818     /**
7819      * Schedule the given thread a normal scheduling priority.
7820      *
7821      * @param tid the tid of the thread to adjust the scheduling of.
7822      * @param suppressLogs {@code true} if any error logging should be disabled.
7823      *
7824      * @return {@code true} if this succeeded.
7825      */
scheduleAsRegularPriority(int tid, boolean suppressLogs)7826     public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
7827         try {
7828             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
7829             return true;
7830         } catch (IllegalArgumentException e) {
7831             if (!suppressLogs) {
7832                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
7833             }
7834         } catch (SecurityException e) {
7835             if (!suppressLogs) {
7836                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
7837             }
7838         }
7839         return false;
7840     }
7841 
7842     /**
7843      * Schedule the given thread an FIFO scheduling priority.
7844      *
7845      * @param tid the tid of the thread to adjust the scheduling of.
7846      * @param suppressLogs {@code true} if any error logging should be disabled.
7847      *
7848      * @return {@code true} if this succeeded.
7849      */
scheduleAsFifoPriority(int tid, boolean suppressLogs)7850     public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
7851         try {
7852             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
7853             return true;
7854         } catch (IllegalArgumentException e) {
7855             if (!suppressLogs) {
7856                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
7857             }
7858         } catch (SecurityException e) {
7859             if (!suppressLogs) {
7860                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
7861             }
7862         }
7863         return false;
7864     }
7865 
7866     @Override
setRenderThread(int tid)7867     public void setRenderThread(int tid) {
7868         synchronized (mProcLock) {
7869             ProcessRecord proc;
7870             int pid = Binder.getCallingPid();
7871             if (pid == Process.myPid()) {
7872                 demoteSystemServerRenderThread(tid);
7873                 return;
7874             }
7875             synchronized (mPidsSelfLocked) {
7876                 proc = mPidsSelfLocked.get(pid);
7877             }
7878             if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) {
7879                 // ensure the tid belongs to the process
7880                 if (!isThreadInProcess(pid, tid)) {
7881                     throw new IllegalArgumentException(
7882                             "Render thread does not belong to process");
7883                 }
7884                 proc.setRenderThreadTid(tid);
7885                 if (DEBUG_OOM_ADJ) {
7886                     Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
7887                 }
7888                 // promote to FIFO now
7889                 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) {
7890                     if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
7891                     if (mUseFifoUiScheduling) {
7892                         setThreadScheduler(proc.getRenderThreadTid(),
7893                                 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
7894                     } else {
7895                         setThreadPriority(proc.getRenderThreadTid(), THREAD_PRIORITY_TOP_APP_BOOST);
7896                     }
7897                 }
7898             } else {
7899                 if (DEBUG_OOM_ADJ) {
7900                     Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? "
7901                             + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling);
7902                 }
7903             }
7904         }
7905     }
7906 
7907     /**
7908      * We only use RenderThread in system_server to store task snapshots to the disk, which should
7909      * happen in the background. Thus, demote render thread from system_server to a lower priority.
7910      *
7911      * @param tid the tid of the RenderThread
7912      */
demoteSystemServerRenderThread(int tid)7913     private void demoteSystemServerRenderThread(int tid) {
7914         setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
7915     }
7916 
7917     @Override
isVrModePackageEnabled(ComponentName packageName)7918     public boolean isVrModePackageEnabled(ComponentName packageName) {
7919         mActivityTaskManager.enforceSystemHasVrFeature();
7920 
7921         final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
7922 
7923         return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
7924                 VrManagerInternal.NO_ERROR;
7925     }
7926 
isTopActivityImmersive()7927     public boolean isTopActivityImmersive() {
7928         return mActivityTaskManager.isTopActivityImmersive();
7929     }
7930 
7931     @Override
isTopOfTask(IBinder token)7932     public boolean isTopOfTask(IBinder token) {
7933         return ActivityClient.getInstance().isTopOfTask(token);
7934     }
7935 
7936     @Override
setHasTopUi(boolean hasTopUi)7937     public void setHasTopUi(boolean hasTopUi) throws RemoteException {
7938         if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
7939             String msg = "Permission Denial: setHasTopUi() from pid="
7940                     + Binder.getCallingPid()
7941                     + ", uid=" + Binder.getCallingUid()
7942                     + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
7943             Slog.w(TAG, msg);
7944             throw new SecurityException(msg);
7945         }
7946         final int pid = Binder.getCallingPid();
7947         final long origId = Binder.clearCallingIdentity();
7948         try {
7949             synchronized (this) {
7950                 boolean changed = false;
7951                 ProcessRecord pr;
7952                 synchronized (mPidsSelfLocked) {
7953                     pr = mPidsSelfLocked.get(pid);
7954                     if (pr == null) {
7955                         Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
7956                         return;
7957                     }
7958                     if (pr.mState.hasTopUi() != hasTopUi) {
7959                         if (DEBUG_OOM_ADJ) {
7960                             Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
7961                         }
7962                         pr.mState.setHasTopUi(hasTopUi);
7963                         changed = true;
7964                     }
7965                 }
7966                 if (changed) {
7967                     updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
7968                 }
7969             }
7970         } finally {
7971             Binder.restoreCallingIdentity(origId);
7972         }
7973     }
7974 
enterSafeMode()7975     public final void enterSafeMode() {
7976         synchronized(this) {
7977             // It only makes sense to do this before the system is ready
7978             // and started launching other packages.
7979             if (!mSystemReady) {
7980                 try {
7981                     AppGlobals.getPackageManager().enterSafeMode();
7982                 } catch (RemoteException e) {
7983                 }
7984             }
7985 
7986             mSafeMode = true;
7987         }
7988     }
7989 
showSafeModeOverlay()7990     public final void showSafeModeOverlay() {
7991         View v = LayoutInflater.from(mContext).inflate(
7992                 com.android.internal.R.layout.safe_mode, null);
7993         WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7994         lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7995         lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7996         lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7997         lp.gravity = Gravity.BOTTOM | Gravity.START;
7998         lp.format = v.getBackground().getOpacity();
7999         lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
8000                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
8001         lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
8002         ((WindowManager)mContext.getSystemService(
8003                 Context.WINDOW_SERVICE)).addView(v, lp);
8004     }
8005 
8006     @Override
noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8007     public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid,
8008             String sourcePkg, String tag) {
8009         if (workSource != null && workSource.isEmpty()) {
8010             workSource = null;
8011         }
8012 
8013         if (sourceUid <= 0 && workSource == null) {
8014             // Try and derive a UID to attribute things to based on the caller.
8015             if (sender != null) {
8016                 if (!(sender instanceof PendingIntentRecord)) {
8017                     return;
8018                 }
8019 
8020                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8021                 final int callerUid = Binder.getCallingUid();
8022                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8023             } else {
8024                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8025                 // haven't been able to derive a UID to attribute things to.
8026                 return;
8027             }
8028         }
8029 
8030         int standbyBucket = 0;
8031 
8032         mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag);
8033         if (workSource != null) {
8034             String workSourcePackage = workSource.getPackageName(0);
8035             int workSourceUid = workSource.getAttributionUid();
8036             if (workSourcePackage == null) {
8037                 workSourcePackage = sourcePkg;
8038                 workSourceUid = sourceUid;
8039             }
8040 
8041             if (mUsageStatsService != null) {
8042                 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage,
8043                         UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime());
8044             }
8045 
8046             FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag,
8047                     sourcePkg, standbyBucket);
8048             if (DEBUG_POWER) {
8049                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8050                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8051                         + standbyBucket + " wsName=" + workSourcePackage + ")]");
8052             }
8053         } else {
8054             if (mUsageStatsService != null) {
8055                 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg,
8056                         UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime());
8057             }
8058             FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid,
8059                     null, tag, sourcePkg, standbyBucket);
8060             if (DEBUG_POWER) {
8061                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8062                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8063                         + standbyBucket + "]");
8064             }
8065         }
8066 
8067     }
8068 
8069     @Override
noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8070     public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid,
8071             String tag) {
8072         if (workSource != null && workSource.isEmpty()) {
8073             workSource = null;
8074         }
8075 
8076         if (sourceUid <= 0 && workSource == null) {
8077             // Try and derive a UID to attribute things to based on the caller.
8078             if (sender != null) {
8079                 if (!(sender instanceof PendingIntentRecord)) {
8080                     return;
8081                 }
8082 
8083                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8084                 final int callerUid = Binder.getCallingUid();
8085                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8086             } else {
8087                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8088                 // haven't been able to derive a UID to attribute things to.
8089                 return;
8090             }
8091         }
8092 
8093         if (DEBUG_POWER) {
8094             Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource +
8095                     ", tag=" + tag + "]");
8096         }
8097 
8098         mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid);
8099     }
8100 
8101     @Override
noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8102     public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid,
8103             String tag) {
8104         if (workSource != null && workSource.isEmpty()) {
8105             workSource = null;
8106         }
8107 
8108         if (sourceUid <= 0 && workSource == null) {
8109             // Try and derive a UID to attribute things to based on the caller.
8110             if (sender != null) {
8111                 if (!(sender instanceof PendingIntentRecord)) {
8112                     return;
8113                 }
8114 
8115                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8116                 final int callerUid = Binder.getCallingUid();
8117                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8118             } else {
8119                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8120                 // haven't been able to derive a UID to attribute things to.
8121                 return;
8122             }
8123         }
8124 
8125         if (DEBUG_POWER) {
8126             Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource +
8127                     ", tag=" + tag + "]");
8128         }
8129 
8130         mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid);
8131     }
8132 
killPids(int[] pids, String pReason, boolean secure)8133     public boolean killPids(int[] pids, String pReason, boolean secure) {
8134         if (Binder.getCallingUid() != SYSTEM_UID) {
8135             throw new SecurityException("killPids only available to the system");
8136         }
8137         final String reason = (pReason == null) ? "Unknown" : pReason;
8138         // XXX Note: don't acquire main activity lock here, because the window
8139         // manager calls in with its locks held.
8140 
8141         boolean killed = false;
8142         final ArrayList<ProcessRecord> killCandidates = new ArrayList<>();
8143         synchronized (mPidsSelfLocked) {
8144             int worstType = 0;
8145             for (int i = 0; i < pids.length; i++) {
8146                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8147                 if (proc != null) {
8148                     int type = proc.mState.getSetAdj();
8149                     if (type > worstType) {
8150                         worstType = type;
8151                     }
8152                 }
8153             }
8154 
8155             // If the worst oom_adj is somewhere in the cached proc LRU range,
8156             // then constrain it so we will kill all cached procs.
8157             if (worstType < ProcessList.CACHED_APP_MAX_ADJ
8158                     && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
8159                 worstType = ProcessList.CACHED_APP_MIN_ADJ;
8160             }
8161 
8162             // If this is not a secure call, don't let it kill processes that
8163             // are important.
8164             if (!secure && worstType < ProcessList.SERVICE_ADJ) {
8165                 worstType = ProcessList.SERVICE_ADJ;
8166             }
8167 
8168             Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
8169             for (int i = 0; i < pids.length; i++) {
8170                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8171                 if (proc == null) {
8172                     continue;
8173                 }
8174                 int adj = proc.mState.getSetAdj();
8175                 if (adj >= worstType && !proc.isKilledByAm()) {
8176                     killCandidates.add(proc);
8177                     killed = true;
8178                 }
8179             }
8180         }
8181         if (!killCandidates.isEmpty()) {
8182             mHandler.post(() -> {
8183                 synchronized (ActivityManagerService.this) {
8184                     for (int i = 0, size = killCandidates.size(); i < size; i++) {
8185                         killCandidates.get(i).killLocked(reason,
8186                                 ApplicationExitInfo.REASON_OTHER,
8187                                 ApplicationExitInfo.SUBREASON_KILL_PID, true);
8188                     }
8189                 }
8190             });
8191         }
8192         return killed;
8193     }
8194 
8195     @Override
killUid(int appId, int userId, String reason)8196     public void killUid(int appId, int userId, String reason) {
8197         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
8198         synchronized (this) {
8199             final long identity = Binder.clearCallingIdentity();
8200             try {
8201                 synchronized (mProcLock) {
8202                     mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId,
8203                             ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
8204                             true /* callerWillRestart */, true /* doit */,
8205                             true /* evenPersistent */, false /* setRemoved */,
8206                             false /* uninstalling */,
8207                             ApplicationExitInfo.REASON_OTHER,
8208                             ApplicationExitInfo.SUBREASON_KILL_UID,
8209                             reason != null ? reason : "kill uid");
8210                 }
8211             } finally {
8212                 Binder.restoreCallingIdentity(identity);
8213             }
8214         }
8215     }
8216 
8217     @Override
killUidForPermissionChange(int appId, int userId, String reason)8218     public void killUidForPermissionChange(int appId, int userId, String reason) {
8219         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
8220         synchronized (this) {
8221             final long identity = Binder.clearCallingIdentity();
8222             try {
8223                 synchronized (mProcLock) {
8224                     mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId,
8225                             ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
8226                             true /* callerWillRestart */, true /* doit */,
8227                             true /* evenPersistent */, false /* setRemoved */,
8228                             false /* uninstalling */,
8229                             ApplicationExitInfo.REASON_PERMISSION_CHANGE,
8230                             ApplicationExitInfo.SUBREASON_UNKNOWN,
8231                             reason != null ? reason : "kill uid");
8232                 }
8233             } finally {
8234                 Binder.restoreCallingIdentity(identity);
8235             }
8236         }
8237     }
8238 
8239     @Override
killProcessesBelowForeground(String reason)8240     public boolean killProcessesBelowForeground(String reason) {
8241         if (Binder.getCallingUid() != SYSTEM_UID) {
8242             throw new SecurityException("killProcessesBelowForeground() only available to system");
8243         }
8244 
8245         return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
8246     }
8247 
killProcessesBelowAdj(int belowAdj, String reason)8248     private boolean killProcessesBelowAdj(int belowAdj, String reason) {
8249         if (Binder.getCallingUid() != SYSTEM_UID) {
8250             throw new SecurityException("killProcessesBelowAdj() only available to system");
8251         }
8252 
8253         boolean killed = false;
8254         synchronized (this) {
8255             synchronized (mProcLock) {
8256                 synchronized (mPidsSelfLocked) {
8257                     final int size = mPidsSelfLocked.size();
8258                     for (int i = 0; i < size; i++) {
8259                         final int pid = mPidsSelfLocked.keyAt(i);
8260                         final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8261                         if (proc == null) continue;
8262 
8263                         final int adj = proc.mState.getSetAdj();
8264                         if (adj > belowAdj && !proc.isKilledByAm()) {
8265                             proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE,
8266                                     true);
8267                             killed = true;
8268                         }
8269                     }
8270                 }
8271             }
8272         }
8273         return killed;
8274     }
8275 
8276     /**
8277      * Similar to {@link #killPids} but killing will be delayed until the device is idle
8278      * and the given process is imperceptible.
8279      */
8280     @Override
killProcessesWhenImperceptible(int[] pids, String reason)8281     public void killProcessesWhenImperceptible(int[] pids, String reason) {
8282         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
8283                 != PackageManager.PERMISSION_GRANTED) {
8284             throw new SecurityException("Requires permission "
8285                     + android.Manifest.permission.FORCE_STOP_PACKAGES);
8286         }
8287         int callerUid = Binder.getCallingUid();
8288         final long iden = Binder.clearCallingIdentity();
8289         try {
8290             mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid);
8291         } finally {
8292             Binder.restoreCallingIdentity(iden);
8293         }
8294     }
8295 
8296     @Override
hang(final IBinder who, boolean allowRestart)8297     public void hang(final IBinder who, boolean allowRestart) {
8298         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8299                 != PackageManager.PERMISSION_GRANTED) {
8300             throw new SecurityException("Requires permission "
8301                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8302         }
8303 
8304         final IBinder.DeathRecipient death = new DeathRecipient() {
8305             @Override
8306             public void binderDied() {
8307                 synchronized (this) {
8308                     notifyAll();
8309                 }
8310             }
8311         };
8312 
8313         try {
8314             who.linkToDeath(death, 0);
8315         } catch (RemoteException e) {
8316             Slog.w(TAG, "hang: given caller IBinder is already dead.");
8317             return;
8318         }
8319 
8320         synchronized (this) {
8321             Watchdog.getInstance().setAllowRestart(allowRestart);
8322             Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
8323             synchronized (death) {
8324                 while (who.isBinderAlive()) {
8325                     try {
8326                         death.wait();
8327                     } catch (InterruptedException e) {
8328                     }
8329                 }
8330             }
8331             Watchdog.getInstance().setAllowRestart(true);
8332         }
8333     }
8334 
8335     @Override
restart()8336     public void restart() {
8337         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8338                 != PackageManager.PERMISSION_GRANTED) {
8339             throw new SecurityException("Requires permission "
8340                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8341         }
8342 
8343         Log.i(TAG, "Sending shutdown broadcast...");
8344 
8345         BroadcastReceiver br = new BroadcastReceiver() {
8346             @Override public void onReceive(Context context, Intent intent) {
8347                 // Now the broadcast is done, finish up the low-level shutdown.
8348                 Log.i(TAG, "Shutting down activity manager...");
8349                 shutdown(10000);
8350                 Log.i(TAG, "Shutdown complete, restarting!");
8351                 killProcess(myPid());
8352                 System.exit(10);
8353             }
8354         };
8355 
8356         // First send the high-level shut down broadcast.
8357         Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
8358         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8359         intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
8360         /* For now we are not doing a clean shutdown, because things seem to get unhappy.
8361         mContext.sendOrderedBroadcastAsUser(intent,
8362                 UserHandle.ALL, null, br, mHandler, 0, null, null);
8363         */
8364         br.onReceive(mContext, intent);
8365     }
8366 
8367     @Override
performIdleMaintenance()8368     public void performIdleMaintenance() {
8369         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8370                 != PackageManager.PERMISSION_GRANTED) {
8371             throw new SecurityException("Requires permission "
8372                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8373         }
8374 
8375         synchronized (mProcLock) {
8376             final long now = SystemClock.uptimeMillis();
8377             final long timeSinceLastIdle = now - mLastIdleTime;
8378 
8379             // Compact all non-zygote processes to freshen up the page cache.
8380             mOomAdjuster.mCachedAppOptimizer.compactAllSystem();
8381 
8382             final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now);
8383             mLastIdleTime = now;
8384             mAppProfiler.updateLowRamTimestampLPr(now);
8385 
8386             StringBuilder sb = new StringBuilder(128);
8387             sb.append("Idle maintenance over ");
8388             TimeUtils.formatDuration(timeSinceLastIdle, sb);
8389             sb.append(" low RAM for ");
8390             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
8391             Slog.i(TAG, sb.toString());
8392 
8393             // If at least 1/3 of our time since the last idle period has been spent
8394             // with RAM low, then we want to kill processes.
8395             boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
8396             // If the processes' memory has increased by more than 1% of the total memory,
8397             // or 10 MB, whichever is greater, then the processes' are eligible to be killed.
8398             final long totalMemoryInKb = getTotalMemory() / 1000;
8399             final long memoryGrowthThreshold =
8400                     Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
8401             mProcessList.forEachLruProcessesLOSP(false, proc -> {
8402                 if (proc.getThread() == null) {
8403                     return;
8404                 }
8405                 final ProcessProfileRecord pr = proc.mProfile;
8406                 final ProcessStateRecord state = proc.mState;
8407                 final int setProcState = state.getSetProcState();
8408                 if (state.isNotCachedSinceIdle()) {
8409                     if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
8410                             && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
8411                         final long initialIdlePss, lastPss, lastSwapPss;
8412                         synchronized (mAppProfiler.mProfilerLock) {
8413                             initialIdlePss = pr.getInitialIdlePss();
8414                             lastPss = pr.getLastPss();
8415                             lastSwapPss = pr.getLastSwapPss();
8416                         }
8417                         if (doKilling && initialIdlePss != 0
8418                                 && lastPss > (initialIdlePss * 3 / 2)
8419                                 && lastPss > (initialIdlePss + memoryGrowthThreshold)) {
8420                             final StringBuilder sb2 = new StringBuilder(128);
8421                             sb2.append("Kill");
8422                             sb2.append(proc.processName);
8423                             sb2.append(" in idle maint: pss=");
8424                             sb2.append(lastPss);
8425                             sb2.append(", swapPss=");
8426                             sb2.append(lastSwapPss);
8427                             sb2.append(", initialPss=");
8428                             sb2.append(initialIdlePss);
8429                             sb2.append(", period=");
8430                             TimeUtils.formatDuration(timeSinceLastIdle, sb2);
8431                             sb2.append(", lowRamPeriod=");
8432                             TimeUtils.formatDuration(lowRamSinceLastIdle, sb2);
8433                             Slog.wtfQuiet(TAG, sb2.toString());
8434                             mHandler.post(() -> {
8435                                 synchronized (ActivityManagerService.this) {
8436                                     proc.killLocked("idle maint (pss " + lastPss
8437                                             + " from " + initialIdlePss + ")",
8438                                             ApplicationExitInfo.REASON_OTHER,
8439                                             ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE,
8440                                             true);
8441                                 }
8442                             });
8443                         }
8444                     }
8445                 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME
8446                         && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
8447                     state.setNotCachedSinceIdle(true);
8448                     synchronized (mAppProfiler.mProfilerLock) {
8449                         pr.setInitialIdlePss(0);
8450                         mAppProfiler.updateNextPssTimeLPf(
8451                                 state.getSetProcState(), proc.mProfile, now, true);
8452                     }
8453                 }
8454             });
8455         }
8456     }
8457 
8458     @Override
sendIdleJobTrigger()8459     public void sendIdleJobTrigger() {
8460         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8461                 != PackageManager.PERMISSION_GRANTED) {
8462             throw new SecurityException("Requires permission "
8463                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8464         }
8465 
8466         final long ident = Binder.clearCallingIdentity();
8467         try {
8468             Intent intent = new Intent(ACTION_TRIGGER_IDLE)
8469                     .setPackage("android")
8470                     .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8471             broadcastIntent(null, intent, null, null, 0, null, null, null,
8472                     OP_NONE, null, false, false, UserHandle.USER_ALL);
8473         } finally {
8474             Binder.restoreCallingIdentity(ident);
8475         }
8476     }
8477 
retrieveSettings()8478     private void retrieveSettings() {
8479         final ContentResolver resolver = mContext.getContentResolver();
8480         mActivityTaskManager.retrieveSettings(resolver);
8481 
8482         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
8483         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
8484         final boolean alwaysFinishActivities =
8485                 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
8486         mHiddenApiBlacklist.registerObserver();
8487         mPlatformCompat.registerContentObserver();
8488 
8489         mAppProfiler.retrieveSettings();
8490 
8491         final Resources res;
8492         synchronized (this) {
8493             mDebugApp = mOrigDebugApp = debugApp;
8494             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
8495             mAlwaysFinishActivities = alwaysFinishActivities;
8496             // Load resources only after the current configuration has been set.
8497             res = mContext.getResources();
8498             final boolean userSwitchUiEnabled = !res.getBoolean(
8499                     com.android.internal.R.bool.config_customUserSwitchUi);
8500             final int maxRunningUsers = res.getInteger(
8501                     com.android.internal.R.integer.config_multiuserMaxRunningUsers);
8502             final boolean delayUserDataLocking = res.getBoolean(
8503                     com.android.internal.R.bool.config_multiuserDelayUserDataLocking);
8504             mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers,
8505                     delayUserDataLocking);
8506         }
8507         mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString(
8508                 com.android.internal.R.string.config_appsNotReportingCrashes));
8509     }
8510 
8511     /**
8512      * Ready. Set. Go!
8513      */
systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)8514     public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
8515         t.traceBegin("PhaseActivityManagerReady");
8516         mSystemServiceManager.preSystemReady();
8517         synchronized(this) {
8518             if (mSystemReady) {
8519                 // If we're done calling all the receivers, run the next "boot phase" passed in
8520                 // by the SystemServer
8521                 if (goingCallback != null) {
8522                     goingCallback.run();
8523                 }
8524                 t.traceEnd(); // PhaseActivityManagerReady
8525                 return;
8526             }
8527 
8528             t.traceBegin("controllersReady");
8529             mLocalDeviceIdleController =
8530                     LocalServices.getService(DeviceIdleInternal.class);
8531             mActivityTaskManager.onSystemReady();
8532             // Make sure we have the current profile info, since it is needed for security checks.
8533             mUserController.onSystemReady();
8534             mAppOpsService.systemReady();
8535             mProcessList.onSystemReady();
8536             mAppRestrictionController.onSystemReady();
8537             mSystemReady = true;
8538             t.traceEnd();
8539         }
8540 
8541         try {
8542             sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
8543                     ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
8544                     .getSerial();
8545         } catch (RemoteException e) {}
8546 
8547         t.traceBegin("killProcesses");
8548         ArrayList<ProcessRecord> procsToKill = null;
8549         synchronized(mPidsSelfLocked) {
8550             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
8551                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8552                 if (!isAllowedWhileBooting(proc.info)) {
8553                     if (procsToKill == null) {
8554                         procsToKill = new ArrayList<ProcessRecord>();
8555                     }
8556                     procsToKill.add(proc);
8557                 }
8558             }
8559         }
8560 
8561         synchronized(this) {
8562             if (procsToKill != null) {
8563                 for (int i = procsToKill.size() - 1; i >= 0; i--) {
8564                     ProcessRecord proc = procsToKill.get(i);
8565                     Slog.i(TAG, "Removing system update proc: " + proc);
8566                     mProcessList.removeProcessLocked(proc, true, false,
8567                             ApplicationExitInfo.REASON_OTHER,
8568                             ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
8569                             "system update done");
8570                 }
8571             }
8572 
8573             // Now that we have cleaned up any update processes, we
8574             // are ready to start launching real processes and know that
8575             // we won't trample on them any more.
8576             mProcessesReady = true;
8577         }
8578         t.traceEnd(); // KillProcesses
8579 
8580         Slog.i(TAG, "System now ready");
8581 
8582         EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
8583 
8584         t.traceBegin("updateTopComponentForFactoryTest");
8585         mAtmInternal.updateTopComponentForFactoryTest();
8586         t.traceEnd();
8587 
8588         t.traceBegin("registerActivityLaunchObserver");
8589         mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
8590         t.traceEnd();
8591 
8592         t.traceBegin("watchDeviceProvisioning");
8593         watchDeviceProvisioning(mContext);
8594         t.traceEnd();
8595 
8596         t.traceBegin("retrieveSettings");
8597         retrieveSettings();
8598         t.traceEnd();
8599 
8600         t.traceBegin("Ugm.onSystemReady");
8601         mUgmInternal.onSystemReady();
8602         t.traceEnd();
8603 
8604         t.traceBegin("updateForceBackgroundCheck");
8605         final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
8606         if (pmi != null) {
8607             pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
8608                     state -> updateForceBackgroundCheck(state.batterySaverEnabled));
8609             updateForceBackgroundCheck(
8610                     pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
8611         } else {
8612             Slog.wtf(TAG, "PowerManagerInternal not found.");
8613         }
8614         t.traceEnd();
8615 
8616         if (goingCallback != null) goingCallback.run();
8617 
8618         t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
8619         // Check the current user here as a user can be started inside goingCallback.run() from
8620         // other system services.
8621         final int currentUserId = mUserController.getCurrentUserId();
8622         Slog.i(TAG, "Current user:" + currentUserId);
8623         if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
8624             // User other than system user has started. Make sure that system user is already
8625             // started before switching user.
8626             throw new RuntimeException("System user not started while current user is:"
8627                     + currentUserId);
8628         }
8629         t.traceEnd();
8630 
8631         t.traceBegin("ActivityManagerStartApps");
8632         mBatteryStatsService.onSystemReady();
8633         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
8634                 Integer.toString(currentUserId), currentUserId);
8635         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
8636                 Integer.toString(currentUserId), currentUserId);
8637 
8638         // On Automotive / Headless System User Mode, at this point the system user has already been
8639         // started and unlocked, and some of the tasks we do here have already been done. So skip
8640         // those in that case. The duplicate system user start is guarded in SystemServiceManager.
8641         // TODO(b/266158156): this workaround shouldn't be necessary once we move the headless-user
8642         // start logic to UserManager-land.
8643         mUserController.onSystemUserStarting();
8644 
8645         synchronized (this) {
8646             // Only start up encryption-aware persistent apps; once user is
8647             // unlocked we'll come back around and start unaware apps
8648             t.traceBegin("startPersistentApps");
8649             startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
8650             t.traceEnd();
8651 
8652             // Start up initial activity.
8653             mBooting = true;
8654             // Enable home activity for system user, so that the system can always boot. We don't
8655             // do this when the system user is not setup since the setup wizard should be the one
8656             // to handle home activity in this case.
8657             if (SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
8658                 t.traceBegin("enableHomeActivity");
8659                 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
8660                 try {
8661                     AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
8662                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
8663                             UserHandle.USER_SYSTEM, "am");
8664                 } catch (RemoteException e) {
8665                     throw e.rethrowAsRuntimeException();
8666                 }
8667                 t.traceEnd();
8668             }
8669 
8670             boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
8671 
8672             // Some systems - like automotive - will explicitly unlock system user then switch
8673             // to a secondary user.
8674             // TODO(b/266158156): this workaround shouldn't be necessary once we move
8675             // the headless-user start logic to UserManager-land.
8676             if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) {
8677                 t.traceBegin("startHomeOnAllDisplays");
8678                 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
8679                 t.traceEnd();
8680             }
8681 
8682             t.traceBegin("showSystemReadyErrorDialogs");
8683             mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
8684             t.traceEnd();
8685 
8686 
8687             if (isBootingSystemUser) {
8688                 // Need to send the broadcasts for the system user here because
8689                 // UserController#startUserInternal will not send them for the system user starting,
8690                 // It checks if the user state already exists, which is always the case for the
8691                 // system user.
8692                 t.traceBegin("sendUserStartBroadcast");
8693                 final int callingUid = Binder.getCallingUid();
8694                 final int callingPid = Binder.getCallingPid();
8695                 final long ident = Binder.clearCallingIdentity();
8696                 try {
8697                     mUserController.sendUserStartedBroadcast(
8698                             currentUserId, callingUid, callingPid);
8699                     mUserController.sendUserStartingBroadcast(
8700                             currentUserId, callingUid, callingPid);
8701                 } catch (Throwable e) {
8702                     Slog.wtf(TAG, "Failed sending first user broadcasts", e);
8703                 } finally {
8704                     Binder.restoreCallingIdentity(ident);
8705                 }
8706                 t.traceEnd();
8707             } else {
8708                 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
8709                         + currentUserId);
8710             }
8711 
8712             t.traceBegin("resumeTopActivities");
8713             mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
8714             t.traceEnd();
8715 
8716             if (isBootingSystemUser) {
8717                 t.traceBegin("sendUserSwitchBroadcasts");
8718                 mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
8719                 t.traceEnd();
8720             }
8721 
8722             t.traceBegin("setBinderProxies");
8723             BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
8724                     BINDER_PROXY_LOW_WATERMARK);
8725             BinderInternal.nSetBinderProxyCountEnabled(true);
8726             BinderInternal.setBinderProxyCountCallback(
8727                     (uid) -> {
8728                         Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
8729                                 + Process.myUid());
8730                         BinderProxy.dumpProxyDebugInfo();
8731                         if (uid == Process.SYSTEM_UID) {
8732                             Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
8733                         } else {
8734                             killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
8735                                     "Too many Binders sent to SYSTEM");
8736                             // We need to run a GC here, because killing the processes involved
8737                             // actually isn't guaranteed to free up the proxies; in fact, if the
8738                             // GC doesn't run for a long time, we may even exceed the global
8739                             // proxy limit for a process (20000), resulting in system_server itself
8740                             // being killed.
8741                             // Note that the GC here might not actually clean up all the proxies,
8742                             // because the binder reference decrements will come in asynchronously;
8743                             // but if new processes belonging to the UID keep adding proxies, we
8744                             // will get another callback here, and run the GC again - this time
8745                             // cleaning up the old proxies.
8746                             VMRuntime.getRuntime().requestConcurrentGC();
8747                         }
8748                     }, mHandler);
8749             t.traceEnd(); // setBinderProxies
8750 
8751             t.traceEnd(); // ActivityManagerStartApps
8752 
8753             // Load the component aliases.
8754             t.traceBegin("componentAlias");
8755             mComponentAliasResolver.onSystemReady(mConstants.mEnableComponentAlias,
8756                     mConstants.mComponentAliasOverrides);
8757             t.traceEnd(); // componentAlias
8758 
8759             t.traceEnd(); // PhaseActivityManagerReady
8760         }
8761     }
8762 
watchDeviceProvisioning(Context context)8763     private void watchDeviceProvisioning(Context context) {
8764         // setting system property based on whether device is provisioned
8765 
8766         if (isDeviceProvisioned(context)) {
8767             SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
8768         } else {
8769             // watch for device provisioning change
8770             context.getContentResolver().registerContentObserver(
8771                     Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false,
8772                     new ContentObserver(new Handler(Looper.getMainLooper())) {
8773                         @Override
8774                         public void onChange(boolean selfChange) {
8775                             if (isDeviceProvisioned(context)) {
8776                                 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
8777                                 context.getContentResolver().unregisterContentObserver(this);
8778                             }
8779                         }
8780                     });
8781         }
8782     }
8783 
isDeviceProvisioned(Context context)8784     private boolean isDeviceProvisioned(Context context) {
8785         return Settings.Global.getInt(context.getContentResolver(),
8786                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
8787     }
8788 
startBroadcastObservers()8789     private void startBroadcastObservers() {
8790         for (BroadcastQueue queue : mBroadcastQueues) {
8791             queue.start(mContext.getContentResolver());
8792         }
8793     }
8794 
updateForceBackgroundCheck(boolean enabled)8795     private void updateForceBackgroundCheck(boolean enabled) {
8796         synchronized (this) {
8797             synchronized (mProcLock) {
8798                 if (mForceBackgroundCheck != enabled) {
8799                     mForceBackgroundCheck = enabled;
8800 
8801                     if (DEBUG_BACKGROUND_CHECK) {
8802                         Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled"));
8803                     }
8804 
8805                     if (mForceBackgroundCheck) {
8806                         // Stop background services for idle UIDs.
8807                         mProcessList.doStopUidForIdleUidsLocked();
8808                     }
8809                 }
8810             }
8811         }
8812     }
8813 
killAppAtUsersRequest(ProcessRecord app)8814     void killAppAtUsersRequest(ProcessRecord app) {
8815         synchronized (this) {
8816             mAppErrors.killAppAtUserRequestLocked(app);
8817         }
8818     }
8819 
8820     /**
8821      * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8822      * The application process will exit immediately after this call returns.
8823      * @param app object of the crashing app, null for the system server
8824      * @param crashInfo describing the exception
8825      */
handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)8826     public void handleApplicationCrash(IBinder app,
8827             ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
8828         ProcessRecord r = findAppProcess(app, "Crash");
8829         final String processName = app == null ? "system_server"
8830                 : (r == null ? "unknown" : r.processName);
8831 
8832         handleApplicationCrashInner("crash", r, processName, crashInfo);
8833     }
8834 
8835     /* Native crash reporting uses this inner version because it needs to be somewhat
8836      * decoupled from the AM-managed cleanup lifecycle
8837      */
handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)8838     void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
8839             ApplicationErrorReport.CrashInfo crashInfo) {
8840         float loadingProgress = 1;
8841         IncrementalMetrics incrementalMetrics = null;
8842         // Obtain Incremental information if available
8843         if (r != null && r.info != null && r.info.packageName != null) {
8844             IncrementalStatesInfo incrementalStatesInfo =
8845                     mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, SYSTEM_UID,
8846                             r.userId);
8847             if (incrementalStatesInfo != null) {
8848                 loadingProgress = incrementalStatesInfo.getProgress();
8849             }
8850             final String codePath = r.info.getCodePath();
8851             if (codePath != null && !codePath.isEmpty()
8852                     && IncrementalManager.isIncrementalPath(codePath)) {
8853                 // Report in the main log about the incremental package
8854                 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName
8855                         + " which is " + ((int) (loadingProgress * 100)) + "% loaded.");
8856                 final IBinder incrementalService = ServiceManager.getService(
8857                         Context.INCREMENTAL_SERVICE);
8858                 if (incrementalService != null) {
8859                     final IncrementalManager incrementalManager = new IncrementalManager(
8860                             IIncrementalService.Stub.asInterface(incrementalService));
8861                     incrementalMetrics = incrementalManager.getMetrics(codePath);
8862                 }
8863             }
8864         }
8865 
8866         boolean recoverable = eventType.equals("native_recoverable_crash");
8867 
8868         EventLogTags.writeAmCrash(Binder.getCallingPid(),
8869                 UserHandle.getUserId(Binder.getCallingUid()), processName,
8870                 r == null ? -1 : r.info.flags,
8871                 crashInfo.exceptionClassName,
8872                 crashInfo.exceptionMessage,
8873                 crashInfo.throwFileName,
8874                 crashInfo.throwLineNumber,
8875                 recoverable ? 1 : 0);
8876 
8877         int processClassEnum = processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER
8878                 : (r != null) ? r.getProcessClassEnum()
8879                         : ServerProtoEnums.ERROR_SOURCE_UNKNOWN;
8880         int uid = (r != null) ? r.uid : -1;
8881         int pid = (r != null) ? r.getPid() : -1;
8882         FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED,
8883                 uid,
8884                 eventType,
8885                 processName,
8886                 pid,
8887                 (r != null && r.info != null) ? r.info.packageName : "",
8888                 (r != null && r.info != null) ? (r.info.isInstantApp()
8889                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE
8890                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE)
8891                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE,
8892                 r != null ? (r.isInterestingToUserLocked()
8893                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND
8894                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND)
8895                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN,
8896                 processClassEnum,
8897                 incrementalMetrics != null /* isIncremental */, loadingProgress,
8898                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead()
8899                         : -1,
8900                 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode()
8901                         : -1,
8902                 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode()
8903                         : -1,
8904                 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(),
8905                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind()
8906                         : -1,
8907                 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis()
8908                         : -1,
8909                 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads()
8910                         : -1,
8911                 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads()
8912                         : -1,
8913                 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid()
8914                         : -1,
8915                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError()
8916                         : -1,
8917                 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber()
8918                         : 0,
8919                 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis()
8920                         : -1
8921         );
8922 
8923         if (eventType.equals("native_crash")) {
8924             CriticalEventLog.getInstance().logNativeCrash(processClassEnum, processName, uid, pid);
8925         } else if (eventType.equals("crash")) {
8926             CriticalEventLog.getInstance().logJavaCrash(crashInfo.exceptionClassName,
8927                     processClassEnum, processName, uid, pid);
8928         }
8929 
8930         final int relaunchReason = r == null ? RELAUNCH_REASON_NONE
8931                         : r.getWindowProcessController().computeRelaunchReason();
8932         final String relaunchReasonString = relaunchReasonToString(relaunchReason);
8933         if (crashInfo.crashTag == null) {
8934             crashInfo.crashTag = relaunchReasonString;
8935         } else {
8936             crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString;
8937         }
8938 
8939         addErrorToDropBox(
8940                 eventType, r, processName, null, null, null, null, null, null, crashInfo,
8941                 new Float(loadingProgress), incrementalMetrics, null, null);
8942 
8943         // For GWP-ASan recoverable crashes, don't make the app crash (the whole point of
8944         // 'recoverable' is that the app doesn't crash). Normally, for nonrecoreable native crashes,
8945         // debuggerd will terminate the process, but there's a backup where ActivityManager will
8946         // also kill it. Avoid that.
8947         if (recoverable) {
8948             mAppErrors.sendRecoverableCrashToAppExitInfo(r, crashInfo);
8949         } else {
8950             mAppErrors.crashApplication(r, crashInfo);
8951         }
8952     }
8953 
handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)8954     public void handleApplicationStrictModeViolation(
8955             IBinder app,
8956             int penaltyMask,
8957             StrictMode.ViolationInfo info) {
8958         // We're okay if the ProcessRecord is missing; it probably means that
8959         // we're reporting a violation from the system process itself.
8960         final ProcessRecord r = findAppProcess(app, "StrictMode");
8961 
8962         if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) {
8963             Integer stackFingerprint = info.hashCode();
8964             boolean logIt = true;
8965             synchronized (mAlreadyLoggedViolatedStacks) {
8966                 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8967                     logIt = false;
8968                     // TODO: sub-sample into EventLog for these, with
8969                     // the info.durationMillis?  Then we'd get
8970                     // the relative pain numbers, without logging all
8971                     // the stack traces repeatedly.  We'd want to do
8972                     // likewise in the client code, which also does
8973                     // dup suppression, before the Binder call.
8974                 } else {
8975                     if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8976                         mAlreadyLoggedViolatedStacks.clear();
8977                     }
8978                     mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8979                 }
8980             }
8981             if (logIt) {
8982                 logStrictModeViolationToDropBox(r, info);
8983             }
8984         }
8985 
8986         if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) {
8987             AppErrorResult result = new AppErrorResult();
8988             final long origId = Binder.clearCallingIdentity();
8989             try {
8990                 Message msg = Message.obtain();
8991                 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG;
8992                 HashMap<String, Object> data = new HashMap<String, Object>();
8993                 data.put("result", result);
8994                 data.put("app", r);
8995                 data.put("info", info);
8996                 msg.obj = data;
8997                 mUiHandler.sendMessage(msg);
8998             } finally {
8999                 Binder.restoreCallingIdentity(origId);
9000             }
9001             int res = result.get();
9002             Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
9003         }
9004     }
9005 
9006     /**
9007      * Register a callback to raise strict mode violations.
9008      * @param callback The binder used to communicate the violations.
9009      */
9010     @Override
registerStrictModeCallback(IBinder callback)9011     public void registerStrictModeCallback(IBinder callback) {
9012         int callingPid = Binder.getCallingPid();
9013         mStrictModeCallbacks.put(callingPid,
9014                 IUnsafeIntentStrictModeCallback.Stub.asInterface(callback));
9015         try {
9016             callback.linkToDeath(new DeathRecipient() {
9017                 @Override
9018                 public void binderDied() {
9019                     mStrictModeCallbacks.remove(callingPid);
9020                 }
9021             }, 0);
9022         } catch (RemoteException e) {
9023             mStrictModeCallbacks.remove(callingPid);
9024         }
9025     }
9026 
9027     // Depending on the policy in effect, there could be a bunch of
9028     // these in quick succession so we try to batch these together to
9029     // minimize disk writes, number of dropbox entries, and maximize
9030     // compression, by having more fewer, larger records.
logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9031     private void logStrictModeViolationToDropBox(
9032             ProcessRecord process,
9033             StrictMode.ViolationInfo info) {
9034         if (info == null) {
9035             return;
9036         }
9037         final boolean isSystemApp = process == null ||
9038                 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
9039                                        ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
9040         final String processName = process == null ? "unknown" : process.processName;
9041         final DropBoxManager dbox = (DropBoxManager)
9042                 mContext.getSystemService(Context.DROPBOX_SERVICE);
9043 
9044         // Exit early if the dropbox isn't configured to accept this report type.
9045         final String dropboxTag = processClass(process) + "_strictmode";
9046         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9047 
9048         final StringBuilder sb = new StringBuilder(1024);
9049         synchronized (sb) {
9050             appendDropBoxProcessHeaders(process, processName, null, sb);
9051             sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9052             sb.append("System-App: ").append(isSystemApp).append("\n");
9053             sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
9054             if (info.violationNumThisLoop != 0) {
9055                 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
9056             }
9057             if (info.numAnimationsRunning != 0) {
9058                 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
9059             }
9060             if (info.broadcastIntentAction != null) {
9061                 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
9062             }
9063             if (info.durationMillis != -1) {
9064                 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
9065             }
9066             if (info.numInstances != -1) {
9067                 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
9068             }
9069             if (info.tags != null) {
9070                 for (String tag : info.tags) {
9071                     sb.append("Span-Tag: ").append(tag).append("\n");
9072                 }
9073             }
9074             sb.append("\n");
9075             sb.append(info.getStackTrace());
9076             sb.append("\n");
9077             if (info.getViolationDetails() != null) {
9078                 sb.append(info.getViolationDetails());
9079                 sb.append("\n");
9080             }
9081         }
9082 
9083         final String res = sb.toString();
9084         IoThread.getHandler().post(() -> {
9085             dbox.addText(dropboxTag, res);
9086         });
9087     }
9088 
9089     /**
9090      * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
9091      * @param app object of the crashing app, null for the system server
9092      * @param tag reported by the caller
9093      * @param system whether this wtf is coming from the system
9094      * @param crashInfo describing the context of the error
9095      * @return true if the process should exit immediately (WTF is fatal)
9096      */
9097     @Override
handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)9098     public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag,
9099             boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo,
9100             int immediateCallerPid) {
9101         final int callingUid = Binder.getCallingUid();
9102         final int callingPid = Binder.getCallingPid();
9103 
9104         // Internal callers in RuntimeInit should always generate a crashInfo.
9105         Preconditions.checkNotNull(crashInfo);
9106 
9107         // If this is coming from the system, we could very well have low-level
9108         // system locks held, so we want to do this all asynchronously.  And we
9109         // never want this to become fatal, so there is that too.
9110         //
9111         // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller
9112         // is within the system server, if it calls Log.wtf() without clearning the calling
9113         // identity, callingPid would still be of a remote caller. So we explicltly pass the
9114         // process PID from the caller.
9115         if (system || (immediateCallerPid == Process.myPid())) {
9116             mHandler.post(new Runnable() {
9117                 @Override public void run() {
9118                     handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo);
9119                 }
9120             });
9121             return false;
9122         }
9123 
9124         final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag,
9125                 crashInfo);
9126 
9127         final boolean isFatal = Build.IS_ENG || Settings.Global
9128                 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0;
9129         final boolean isSystem = (r == null) || r.isPersistent();
9130 
9131         if (isFatal && !isSystem) {
9132             mAppErrors.crashApplication(r, crashInfo);
9133             return true;
9134         } else {
9135             return false;
9136         }
9137     }
9138 
handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)9139     ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app,
9140             @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) {
9141         final ProcessRecord r = findAppProcess(app, "WTF");
9142         final String processName = app == null ? "system_server"
9143                 : (r == null ? "unknown" : r.processName);
9144 
9145         EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid,
9146                 processName, r == null ? -1 : r.info.flags, tag,
9147                 crashInfo == null ? "unknown" : crashInfo.exceptionMessage);
9148 
9149         FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName,
9150                 callingPid, (r != null) ? r.getProcessClassEnum() : 0);
9151 
9152         addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo,
9153                 null, null, null, null);
9154 
9155         return r;
9156     }
9157 
9158     /**
9159      * Schedule to handle any pending system_server WTFs.
9160      */
schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9161     public void schedulePendingSystemServerWtfs(
9162             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
9163         mHandler.post(() -> handlePendingSystemServerWtfs(list));
9164     }
9165 
9166     /**
9167      * Handle any pending system_server WTFs, add into the dropbox
9168      */
handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)9169     private void handlePendingSystemServerWtfs(
9170             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
9171         ProcessRecord proc;
9172         synchronized (mPidsSelfLocked) {
9173             proc = mPidsSelfLocked.get(MY_PID);
9174         }
9175         for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll();
9176                 p != null; p = list.poll()) {
9177             addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null,
9178                     p.second, null, null, null, null);
9179         }
9180     }
9181 
9182     /**
9183      * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
9184      * @return the corresponding {@link ProcessRecord} object, or null if none could be found
9185      */
findAppProcess(IBinder app, String reason)9186     private ProcessRecord findAppProcess(IBinder app, String reason) {
9187         if (app == null) {
9188             return null;
9189         }
9190 
9191         synchronized (mProcLock) {
9192             return mProcessList.findAppProcessLOSP(app, reason);
9193         }
9194     }
9195 
9196     /**
9197      * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
9198      * to append various headers to the dropbox log text.
9199      */
appendDropBoxProcessHeaders(ProcessRecord process, String processName, final VolatileDropboxEntryStates volatileStates, final StringBuilder sb)9200     void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
9201             final VolatileDropboxEntryStates volatileStates, final StringBuilder sb) {
9202         // Watchdog thread ends up invoking this function (with
9203         // a null ProcessRecord) to add the stack file to dropbox.
9204         // Do not acquire a lock on this (am) in such cases, as it
9205         // could cause a potential deadlock, if and when watchdog
9206         // is invoked due to unavailability of lock on am and it
9207         // would prevent watchdog from killing system_server.
9208         if (process == null) {
9209             sb.append("Process: ").append(processName).append("\n");
9210             return;
9211         }
9212         // Note: ProcessRecord 'process' is guarded by the service
9213         // instance.  (notably process.pkgList, which could otherwise change
9214         // concurrently during execution of this method)
9215         synchronized (mProcLock) {
9216             sb.append("Process: ").append(processName).append("\n");
9217             sb.append("PID: ").append(process.getPid()).append("\n");
9218             sb.append("UID: ").append(process.uid).append("\n");
9219             if (process.mOptRecord != null) {
9220                 // Use 'isProcessFrozen' from 'volatileStates' if it'snon-null (present),
9221                 // otherwise use 'isFrozen' from 'mOptRecord'.
9222                 sb.append("Frozen: ").append(
9223                     (volatileStates != null && volatileStates.isProcessFrozen() != null)
9224                     ? volatileStates.isProcessFrozen() : process.mOptRecord.isFrozen()
9225                 ).append("\n");
9226             }
9227             int flags = process.info.flags;
9228             final IPackageManager pm = AppGlobals.getPackageManager();
9229             sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n");
9230             final int callingUserId = UserHandle.getCallingUserId();
9231             process.getPkgList().forEachPackage(pkg -> {
9232                 sb.append("Package: ").append(pkg);
9233                 try {
9234                     final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId);
9235                     if (pi != null) {
9236                         sb.append(" v").append(pi.getLongVersionCode());
9237                         if (pi.versionName != null) {
9238                             sb.append(" (").append(pi.versionName).append(")");
9239                         }
9240                     }
9241                 } catch (RemoteException e) {
9242                     Slog.e(TAG, "Error getting package info: " + pkg, e);
9243                 }
9244                 sb.append("\n");
9245             });
9246             if (process.info.isInstantApp()) {
9247                 sb.append("Instant-App: true\n");
9248             }
9249 
9250             if (process.isSdkSandbox) {
9251                 final String clientPackage = process.sdkSandboxClientAppPackage;
9252                 try {
9253                     final PackageInfo pi = pm.getPackageInfo(clientPackage,
9254                             PackageManager.GET_SHARED_LIBRARY_FILES, callingUserId);
9255                     if (pi != null) {
9256                         appendSdkSandboxClientPackageHeader(sb, pi);
9257                         appendSdkSandboxLibraryHeaders(sb, pi);
9258                     } else {
9259                         Slog.e(TAG,
9260                                 "PackageInfo is null for SDK sandbox client: " + clientPackage);
9261                     }
9262                 } catch (RemoteException e) {
9263                     Slog.e(TAG,
9264                             "Error getting package info for SDK sandbox client: " + clientPackage,
9265                             e);
9266                 }
9267                 sb.append("SdkSandbox: true\n");
9268             }
9269         }
9270     }
9271 
appendSdkSandboxClientPackageHeader(StringBuilder sb, PackageInfo clientPackageInfo)9272     private void appendSdkSandboxClientPackageHeader(StringBuilder sb,
9273             PackageInfo clientPackageInfo) {
9274         sb.append("SdkSandbox-Client-Package: ").append(clientPackageInfo.packageName);
9275         sb.append(" v").append(clientPackageInfo.getLongVersionCode());
9276         if (clientPackageInfo.versionName != null) {
9277             sb.append(" (").append(clientPackageInfo.versionName).append(")");
9278         }
9279         sb.append("\n");
9280     }
9281 
appendSdkSandboxLibraryHeaders(StringBuilder sb, PackageInfo clientPackageInfo)9282     private void appendSdkSandboxLibraryHeaders(StringBuilder sb,
9283             PackageInfo clientPackageInfo) {
9284         final ApplicationInfo info = clientPackageInfo.applicationInfo;
9285         final List<SharedLibraryInfo> sharedLibraries = info.getSharedLibraryInfos();
9286         for (int j = 0, size = sharedLibraries.size(); j < size; j++) {
9287             final SharedLibraryInfo sharedLibrary = sharedLibraries.get(j);
9288             if (!sharedLibrary.isSdk()) {
9289                 continue;
9290             }
9291 
9292             sb.append("SdkSandbox-Library: ").append(sharedLibrary.getPackageName());
9293             final VersionedPackage versionedPackage = sharedLibrary.getDeclaringPackage();
9294             sb.append(" v").append(versionedPackage.getLongVersionCode());
9295             sb.append("\n");
9296         }
9297     }
9298 
processClass(ProcessRecord process)9299     private static String processClass(ProcessRecord process) {
9300         if (process == null || process.getPid() == MY_PID) {
9301             return "system_server";
9302         } else if (process.info.isSystemApp() || process.info.isSystemExt()) {
9303             return "system_app";
9304         } else {
9305             return "data_app";
9306         }
9307     }
9308 
9309     private final DropboxRateLimiter mDropboxRateLimiter = new DropboxRateLimiter();
9310 
9311     /**
9312      * Write a description of an error (crash, WTF, ANR) to the drop box.
9313      * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
9314      * @param process which caused the error, null means the system server
9315      * @param activityShortComponentName which triggered the error, null if unknown
9316      * @param parentShortComponentName activity related to the error, null if unknown
9317      * @param parentProcess parent process
9318      * @param subject line related to the error, null if absent
9319      * @param report in long form describing the error, null if absent
9320      * @param dataFile text file to include in the report, null if none
9321      * @param crashInfo giving an application stack trace, null if absent
9322      * @param loadingProgress the loading progress of an installed package, range in [0, 1].
9323      * @param incrementalMetrics metrics for apps installed on Incremental.
9324      * @param errorId a unique id to append to the dropbox headers.
9325      */
9326     @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)9327     public void addErrorToDropBox(String eventType,
9328             ProcessRecord process, String processName, String activityShortComponentName,
9329             String parentShortComponentName, ProcessRecord parentProcess,
9330             String subject, final String report, final File dataFile,
9331             final ApplicationErrorReport.CrashInfo crashInfo,
9332             @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics,
9333             @Nullable UUID errorId, @Nullable VolatileDropboxEntryStates volatileStates) {
9334         // NOTE -- this must never acquire the ActivityManagerService lock,
9335         // otherwise the watchdog may be prevented from resetting the system.
9336 
9337         // Bail early if not published yet
9338         final DropBoxManager dbox;
9339         try {
9340             dbox = mContext.getSystemService(DropBoxManager.class);
9341         } catch (Exception e) {
9342             return;
9343         }
9344 
9345         // Exit early if the dropbox isn't configured to accept this report type.
9346         final String dropboxTag = processClass(process) + "_" + eventType;
9347         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9348 
9349         // Check if we should rate limit and abort early if needed.
9350         final DropboxRateLimiter.RateLimitResult rateLimitResult =
9351                 mDropboxRateLimiter.shouldRateLimit(eventType, processName);
9352         if (rateLimitResult.shouldRateLimit()) return;
9353 
9354         final StringBuilder sb = new StringBuilder(1024);
9355         appendDropBoxProcessHeaders(process, processName, volatileStates, sb);
9356         if (process != null) {
9357             sb.append("Foreground: ")
9358                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
9359                     .append("\n");
9360             if (process.getStartUptime() > 0) {
9361                 long runtimeMillis = SystemClock.uptimeMillis() - process.getStartUptime();
9362                 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n");
9363             }
9364         }
9365         if (activityShortComponentName != null) {
9366             sb.append("Activity: ").append(activityShortComponentName).append("\n");
9367         }
9368         if (parentShortComponentName != null) {
9369             if (parentProcess != null && parentProcess.getPid() != process.getPid()) {
9370                 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n");
9371             }
9372             if (!parentShortComponentName.equals(activityShortComponentName)) {
9373                 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n");
9374             }
9375         }
9376         if (subject != null) {
9377             sb.append("Subject: ").append(subject).append("\n");
9378         }
9379         if (errorId != null) {
9380             sb.append("ErrorId: ").append(errorId.toString()).append("\n");
9381         }
9382         sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9383         if (Debug.isDebuggerConnected()) {
9384             sb.append("Debugger: Connected\n");
9385         }
9386         if (crashInfo != null && crashInfo.exceptionHandlerClassName != null
9387                 && !crashInfo.exceptionHandlerClassName.isEmpty()) {
9388             sb.append("Crash-Handler: ").append(crashInfo.exceptionHandlerClassName).append("\n");
9389         }
9390         if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) {
9391             sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n");
9392         }
9393         if (loadingProgress != null) {
9394             sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n");
9395         }
9396         if (incrementalMetrics != null) {
9397             sb.append("Incremental: Yes").append("\n");
9398             final long millisSinceOldestPendingRead =
9399                     incrementalMetrics.getMillisSinceOldestPendingRead();
9400             if (millisSinceOldestPendingRead > 0) {
9401                 sb.append("Millis-Since-Oldest-Pending-Read: ").append(
9402                         millisSinceOldestPendingRead).append("\n");
9403             }
9404         }
9405         sb.append(rateLimitResult.createHeader());
9406         sb.append("\n");
9407 
9408         // Do the rest in a worker thread to avoid blocking the caller on I/O
9409         // (After this point, we shouldn't access AMS internal data structures.)
9410         //
9411         // If process is null, we are being called from some internal code
9412         // and may be about to die -- run this synchronously.
9413         final boolean runSynchronously = process == null;
9414         Thread worker = new Thread("Error dump: " + dropboxTag) {
9415             @Override
9416             public void run() {
9417                 if (report != null) {
9418                     sb.append(report);
9419                 }
9420 
9421                 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
9422                 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag;
9423                 int lines = Build.IS_USER
9424                         ? 0
9425                         : Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0);
9426                 int dropboxMaxSize = Settings.Global.getInt(
9427                         mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE);
9428                 int maxDataFileSize = dropboxMaxSize - sb.length()
9429                         - lines * RESERVED_BYTES_PER_LOGCAT_LINE;
9430 
9431                 if (dataFile != null && maxDataFileSize > 0) {
9432                     try {
9433                         sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize,
9434                                     "\n\n[[TRUNCATED]]"));
9435                     } catch (IOException e) {
9436                         Slog.e(TAG, "Error reading " + dataFile, e);
9437                     }
9438                 }
9439                 if (crashInfo != null && crashInfo.stackTrace != null) {
9440                     sb.append(crashInfo.stackTrace);
9441                 }
9442 
9443                 if (lines > 0 && !runSynchronously) {
9444                     sb.append("\n");
9445 
9446                     InputStreamReader input = null;
9447                     try {
9448                         java.lang.Process logcat = new ProcessBuilder(
9449                                 // Time out after 10s of inactivity, but kill logcat with SEGV
9450                                 // so we can investigate why it didn't finish.
9451                                 "/system/bin/timeout", "-i", "-s", "SEGV", "10s",
9452                                 // Merge several logcat streams, and take the last N lines.
9453                                 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system",
9454                                 "-b", "main", "-b", "crash", "-t", String.valueOf(lines))
9455                                         .redirectErrorStream(true).start();
9456 
9457                         try { logcat.getOutputStream().close(); } catch (IOException e) {}
9458                         try { logcat.getErrorStream().close(); } catch (IOException e) {}
9459                         input = new InputStreamReader(logcat.getInputStream());
9460 
9461                         int num;
9462                         char[] buf = new char[8192];
9463                         while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
9464                     } catch (IOException e) {
9465                         Slog.e(TAG, "Error running logcat", e);
9466                     } finally {
9467                         if (input != null) try { input.close(); } catch (IOException e) {}
9468                     }
9469                 }
9470 
9471                 dbox.addText(dropboxTag, sb.toString());
9472             }
9473         };
9474 
9475         if (runSynchronously) {
9476             final int oldMask = StrictMode.allowThreadDiskWritesMask();
9477             try {
9478                 worker.run();
9479             } finally {
9480                 StrictMode.setThreadPolicyMask(oldMask);
9481             }
9482         } else {
9483             worker.start();
9484         }
9485     }
9486 
9487     @Override
getProcessesInErrorState()9488     public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
9489         enforceNotIsolatedCaller("getProcessesInErrorState");
9490         // assume our apps are happy - lazy create the list
9491         final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1];
9492 
9493         final int callingUid = Binder.getCallingUid();
9494         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9495                 callingUid) == PackageManager.PERMISSION_GRANTED;
9496         int userId = UserHandle.getUserId(callingUid);
9497 
9498         final boolean hasDumpPermission = ActivityManager.checkUidPermission(
9499                 android.Manifest.permission.DUMP, callingUid) == PackageManager.PERMISSION_GRANTED;
9500 
9501         synchronized (mProcLock) {
9502             // iterate across all processes
9503             mProcessList.forEachLruProcessesLOSP(false, app -> {
9504                 if (!allUsers && app.userId != userId) {
9505                     return;
9506                 }
9507                 if (!hasDumpPermission && app.info.uid != callingUid) {
9508                     return;
9509                 }
9510                 final ProcessErrorStateRecord errState = app.mErrorState;
9511                 final boolean crashing = errState.isCrashing();
9512                 final boolean notResponding = errState.isNotResponding();
9513                 if ((app.getThread() != null) && (crashing || notResponding)) {
9514                     // This one's in trouble, so we'll generate a report for it
9515                     // crashes are higher priority (in case there's a crash *and* an anr)
9516                     ActivityManager.ProcessErrorStateInfo report = null;
9517                     if (crashing) {
9518                         report = errState.getCrashingReport();
9519                     } else if (notResponding) {
9520                         report = errState.getNotRespondingReport();
9521                     }
9522 
9523                     if (report != null) {
9524                         if (errList[0] == null) {
9525                             errList[0] = new ArrayList<>(1);
9526                         }
9527                         errList[0].add(report);
9528                     } else {
9529                         Slog.w(TAG, "Missing app error report, app = " + app.processName +
9530                                 " crashing = " + crashing +
9531                                 " notResponding = " + notResponding);
9532                     }
9533                 }
9534             });
9535         }
9536 
9537         return errList[0];
9538     }
9539 
9540     @Override
getRunningAppProcesses()9541     public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
9542         enforceNotIsolatedCaller("getRunningAppProcesses");
9543 
9544         final int callingUid = Binder.getCallingUid();
9545         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9546 
9547         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9548                 callingUid) == PackageManager.PERMISSION_GRANTED;
9549         final int userId = UserHandle.getUserId(callingUid);
9550         final boolean allUids = mAtmInternal.isGetTasksAllowed(
9551                 "getRunningAppProcesses", Binder.getCallingPid(), callingUid);
9552 
9553         synchronized (mProcLock) {
9554             // Iterate across all processes
9555             return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids,
9556                     callingUid, clientTargetSdk);
9557         }
9558     }
9559 
9560     @Override
getRunningExternalApplications()9561     public List<ApplicationInfo> getRunningExternalApplications() {
9562         enforceNotIsolatedCaller("getRunningExternalApplications");
9563         List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
9564         List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
9565         if (runningApps != null && runningApps.size() > 0) {
9566             Set<String> extList = new HashSet<String>();
9567             for (ActivityManager.RunningAppProcessInfo app : runningApps) {
9568                 if (app.pkgList != null) {
9569                     for (String pkg : app.pkgList) {
9570                         extList.add(pkg);
9571                     }
9572                 }
9573             }
9574             IPackageManager pm = AppGlobals.getPackageManager();
9575             for (String pkg : extList) {
9576                 try {
9577                     ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
9578                     if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
9579                         retList.add(info);
9580                     }
9581                 } catch (RemoteException e) {
9582                 }
9583             }
9584         }
9585         return retList;
9586     }
9587 
9588     /* @hide */
9589     @Override
getHistoricalProcessStartReasons( String packageName, int maxNum, int userId)9590     public ParceledListSlice<ApplicationStartInfo> getHistoricalProcessStartReasons(
9591             String packageName, int maxNum, int userId) {
9592         if (!mConstants.mFlagApplicationStartInfoEnabled) {
9593             return new ParceledListSlice<ApplicationStartInfo>(
9594                 new ArrayList<ApplicationStartInfo>());
9595         }
9596         enforceNotIsolatedCaller("getHistoricalProcessStartReasons");
9597 
9598         final ArrayList<ApplicationStartInfo> results = new ArrayList<ApplicationStartInfo>();
9599 
9600         return new ParceledListSlice<ApplicationStartInfo>(results);
9601     }
9602 
9603 
9604     /* @hide */
9605     @Override
setApplicationStartInfoCompleteListener( IApplicationStartInfoCompleteListener listener, int userId)9606     public void setApplicationStartInfoCompleteListener(
9607             IApplicationStartInfoCompleteListener listener, int userId) {
9608         if (!mConstants.mFlagApplicationStartInfoEnabled) {
9609             return;
9610         }
9611         enforceNotIsolatedCaller("setApplicationStartInfoCompleteListener");
9612     }
9613 
9614 
9615     /* @hide */
9616     @Override
removeApplicationStartInfoCompleteListener(int userId)9617     public void removeApplicationStartInfoCompleteListener(int userId) {
9618         if (!mConstants.mFlagApplicationStartInfoEnabled) {
9619             return;
9620         }
9621         enforceNotIsolatedCaller("removeApplicationStartInfoCompleteListener");
9622     }
9623 
9624     @Override
getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)9625     public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons(
9626             String packageName, int pid, int maxNum, int userId) {
9627         enforceNotIsolatedCaller("getHistoricalProcessExitReasons");
9628 
9629         // For the simplification, we don't support USER_ALL nor USER_CURRENT here.
9630         if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) {
9631             throw new IllegalArgumentException("Unsupported userId");
9632         }
9633 
9634         final int callingPid = Binder.getCallingPid();
9635         final int callingUid = Binder.getCallingUid();
9636         final int callingUserId = UserHandle.getCallingUserId();
9637         mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL,
9638                 "getHistoricalProcessExitReasons", null);
9639 
9640         NativeTombstoneManager tombstoneService = LocalServices.getService(
9641                 NativeTombstoneManager.class);
9642 
9643         final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>();
9644         if (!TextUtils.isEmpty(packageName)) {
9645             final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid,
9646                       "getHistoricalProcessExitReasons");
9647             if (uid != INVALID_UID) {
9648                 mProcessList.mAppExitInfoTracker.getExitInfo(
9649                         packageName, uid, pid, maxNum, results);
9650                 tombstoneService.collectTombstones(results, uid, pid, maxNum);
9651             }
9652         } else {
9653             // If no package name is given, use the caller's uid as the filter uid.
9654             mProcessList.mAppExitInfoTracker.getExitInfo(
9655                     packageName, callingUid, pid, maxNum, results);
9656             tombstoneService.collectTombstones(results, callingUid, pid, maxNum);
9657         }
9658 
9659         return new ParceledListSlice<ApplicationExitInfo>(results);
9660     }
9661 
9662     @Override
setProcessStateSummary(@ullable byte[] state)9663     public void setProcessStateSummary(@Nullable byte[] state) {
9664         if (state != null && state.length > MAX_STATE_DATA_SIZE) {
9665             throw new IllegalArgumentException("Data size is too large");
9666         }
9667         mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(),
9668                 Binder.getCallingPid(), state);
9669     }
9670 
9671     /**
9672      * Check if the calling process has the permission to dump given package,
9673      * throw SecurityException if it doesn't have the permission.
9674      *
9675      * @return The real UID of process that can be dumped, or {@link android.os.Process#INVALID_UID}
9676      *         if the package is not found.
9677      */
enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)9678     int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid,
9679             String function) {
9680         // Allow SDK sandbox process to dump for its own process (under SDK sandbox package)
9681         try {
9682             if (Process.isSdkSandboxUid(callingUid)
9683                     && getPackageManager().getSdkSandboxPackageName().equals(packageName)) {
9684                 return callingUid;
9685             }
9686         } catch (RemoteException e) {
9687             Log.e(TAG, "Could not get SDK sandbox package name");
9688         }
9689         final long identity = Binder.clearCallingIdentity();
9690         int uid = INVALID_UID;
9691         try {
9692             uid = mPackageManagerInt.getPackageUid(packageName,
9693                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
9694         } finally {
9695             Binder.restoreCallingIdentity(identity);
9696         }
9697         // If the uid is Process.INVALID_UID, the below 'if' check will be always true
9698         if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) {
9699             // Requires the DUMP permission if the target package doesn't belong
9700             // to the caller or it doesn't exist.
9701             enforceCallingPermission(android.Manifest.permission.DUMP, function);
9702         }
9703         return uid;
9704     }
9705 
9706     @Override
getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)9707     public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) {
9708         if (outState == null) {
9709             throw new IllegalArgumentException("outState is null");
9710         }
9711         enforceNotIsolatedCaller("getMyMemoryState");
9712 
9713         final int callingUid = Binder.getCallingUid();
9714         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9715 
9716         synchronized (mProcLock) {
9717             ProcessRecord proc;
9718             synchronized (mPidsSelfLocked) {
9719                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9720             }
9721             if (proc != null) {
9722                 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk);
9723             }
9724         }
9725     }
9726 
9727     @Override
getMemoryTrimLevel()9728     public @MemFactor int getMemoryTrimLevel() {
9729         enforceNotIsolatedCaller("getMyMemoryState");
9730         synchronized (this) {
9731             return mAppProfiler.getLastMemoryLevelLocked();
9732         }
9733     }
9734 
setMemFactorOverride(@emFactor int level)9735     void setMemFactorOverride(@MemFactor int level) {
9736         synchronized (this) {
9737             if (level == mAppProfiler.getLastMemoryLevelLocked()) {
9738                 return;
9739             }
9740 
9741             mAppProfiler.setMemFactorOverrideLocked(level);
9742             // Kick off an oom adj update since we forced a mem factor update.
9743             updateOomAdjLocked(OOM_ADJ_REASON_SHELL);
9744         }
9745     }
9746 
9747     /**
9748      * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}.
9749      */
setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)9750     void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable,
9751             @NonNull String reason) {
9752         synchronized (this) {
9753             mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason);
9754         }
9755     }
9756 
9757     /**
9758      * @return {@code false} if the given package has been disable from enforcing the service
9759      * restart backoff policy, used by {@link ActivityManagerShellCommand}.
9760      */
isServiceRestartBackoffEnabled(@onNull String packageName)9761     boolean isServiceRestartBackoffEnabled(@NonNull String packageName) {
9762         synchronized (this) {
9763             return mServices.isServiceRestartBackoffEnabledLocked(packageName);
9764         }
9765     }
9766 
9767     @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)9768     public void onShellCommand(FileDescriptor in, FileDescriptor out,
9769             FileDescriptor err, String[] args, ShellCallback callback,
9770             ResultReceiver resultReceiver) {
9771         final int callingUid = Binder.getCallingUid();
9772         if (callingUid != ROOT_UID && callingUid != Process.SHELL_UID) {
9773             if (resultReceiver != null) {
9774                 resultReceiver.send(-1, null);
9775             }
9776             throw new SecurityException("Shell commands are only callable by root or shell");
9777         }
9778         (new ActivityManagerShellCommand(this, false)).exec(
9779                 this, in, out, err, args, callback, resultReceiver);
9780     }
9781 
9782     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)9783     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9784         PriorityDump.dump(mPriorityDumper, fd, pw, args);
9785     }
9786 
dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)9787     private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti,
9788             boolean dumpAll, String dumpPackage, int displayIdFilter, boolean dumpClient,
9789             boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies) {
9790 
9791         ActiveServices.ServiceDumper sdumper;
9792 
9793         synchronized(this) {
9794             mConstants.dump(pw);
9795             synchronized (mProcLock) {
9796                 mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
9797             }
9798             mOomAdjuster.dumpCacheOomRankerSettings(pw);
9799             pw.println();
9800             if (dumpAll) {
9801                 pw.println("-------------------------------------------------------------------------------");
9802 
9803             }
9804             dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9805             pw.println();
9806             if (dumpAll) {
9807                 pw.println("-------------------------------------------------------------------------------");
9808 
9809             }
9810             mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage);
9811             pw.println();
9812             if (dumpAll) {
9813                 pw.println("-------------------------------------------------------------------------------");
9814             }
9815             dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9816             pw.println();
9817             if (dumpAll) {
9818                 pw.println("-------------------------------------------------------------------------------");
9819             }
9820             if (dumpAll || dumpPackage != null) {
9821                 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9822                 pw.println();
9823                 if (dumpAll) {
9824                     pw.println("-------------------------------------------------------------------------------");
9825                 }
9826             }
9827             mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9828             pw.println();
9829             if (dumpAll) {
9830                 pw.println("-------------------------------------------------------------------------------");
9831             }
9832             dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage);
9833             pw.println();
9834             sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9835             if (!dumpClient) {
9836                 if (dumpAll) {
9837                     pw.println("-------------------------------------------------------------------------------");
9838                 }
9839                 sdumper.dumpLocked();
9840             }
9841         }
9842         // We drop the lock here because we can't call dumpWithClient() with the lock held;
9843         // if the caller wants a consistent state for the !dumpClient case, it can call this
9844         // method with the lock held.
9845         if (dumpClient) {
9846             if (dumpAll) {
9847                 pw.println("-------------------------------------------------------------------------------");
9848             }
9849             sdumper.dumpWithClient();
9850         }
9851         if (dumpPackage == null && dumpProxies) {
9852             // Intentionally dropping the lock for this, because dumpBinderProxies() will make many
9853             // outgoing binder calls to retrieve interface descriptors; while that is system code,
9854             // there is nothing preventing an app from overriding this implementation by talking to
9855             // the binder driver directly, and hang up system_server in the process. So, dump
9856             // without locks held, and even then only when there is an unreasonably large number of
9857             // proxies in the first place.
9858             pw.println();
9859             if (dumpAll) {
9860                 pw.println("-------------------------------------------------------------------------------");
9861             }
9862             dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */);
9863         }
9864         synchronized(this) {
9865             pw.println();
9866             if (dumpAll) {
9867                 pw.println("-------------------------------------------------------------------------------");
9868             }
9869             mAtmInternal.dump(DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9870                     dumpPackage, displayIdFilter);
9871             pw.println();
9872             if (dumpAll) {
9873                 pw.println("-------------------------------------------------------------------------------");
9874             }
9875             mAtmInternal.dump(DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9876                     dumpPackage, displayIdFilter);
9877             pw.println();
9878             if (dumpAll) {
9879                 pw.println("-------------------------------------------------------------------------------");
9880             }
9881             mAtmInternal.dump(DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9882                     dumpPackage, displayIdFilter);
9883             if (dumpPackage == null) {
9884                 pw.println();
9885                 if (dumpAll) {
9886                     pw.println("-------------------------------------------------------------------------------");
9887                 }
9888                 mAtmInternal.dump(DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9889                         dumpPackage, displayIdFilter);
9890             }
9891             // Activities section is dumped as part of the Critical priority dump. Exclude the
9892             // section if priority is Normal.
9893             if (!dumpNormalPriority) {
9894                 pw.println();
9895                 if (dumpAll) {
9896                     pw.println("-------------------------------------------------------------------------------");
9897                 }
9898                 mAtmInternal.dump(DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient,
9899                         dumpPackage, displayIdFilter);
9900             }
9901             if (mAssociations.size() > 0) {
9902                 pw.println();
9903                 if (dumpAll) {
9904                     pw.println("-------------------------------------------------------------------------------");
9905                 }
9906                 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9907             }
9908             pw.println();
9909             if (dumpAll) {
9910                 pw.println("-------------------------------------------------------------------------------");
9911                 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
9912             }
9913             if (dumpPackage == null) {
9914                 pw.println();
9915                 if (dumpAll) {
9916                     pw.println("-------------------------------------------------------------------------------");
9917                 }
9918                 mOomAdjProfiler.dump(pw);
9919                 pw.println();
9920                 if (dumpAll) {
9921                     pw.println("-------------------------------------------------------------------------------");
9922                 }
9923                 dumpLmkLocked(pw);
9924             }
9925             pw.println();
9926             if (dumpAll) {
9927                 pw.println("-------------------------------------------------------------------------------");
9928             }
9929             synchronized (mProcLock) {
9930                 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId);
9931             }
9932             pw.println();
9933             if (dumpAll) {
9934                 pw.println("-------------------------------------------------------------------------------");
9935             }
9936             dumpUsers(pw);
9937 
9938             pw.println();
9939             if (dumpAll) {
9940                 pw.println("-------------------------------------------------------------------------------");
9941             }
9942             mComponentAliasResolver.dump(pw);
9943         }
9944     }
9945 
9946     /**
9947      * Dump the app restriction controller, it's required not to hold the global lock here.
9948      */
dumpAppRestrictionController(PrintWriter pw)9949     private void dumpAppRestrictionController(PrintWriter pw) {
9950         pw.println("-------------------------------------------------------------------------------");
9951         mAppRestrictionController.dump(pw, "");
9952     }
9953 
dumpAppRestrictionController(ProtoOutputStream proto, int uid)9954     void dumpAppRestrictionController(ProtoOutputStream proto, int uid) {
9955         mAppRestrictionController.dumpAsProto(proto, uid);
9956     }
9957 
9958     /**
9959      * Wrapper function to print out debug data filtered by specified arguments.
9960     */
9961     @NeverCompile // Avoid size overhead of debugging code.
doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)9962     private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
9963         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
9964 
9965         boolean dumpAll = false;
9966         boolean dumpClient = false;
9967         boolean dumpCheckin = false;
9968         boolean dumpCheckinFormat = false;
9969         boolean dumpNormalPriority = false;
9970         boolean dumpVisibleStacksOnly = false;
9971         boolean dumpFocusedStackOnly = false;
9972         int dumpDisplayId = INVALID_DISPLAY;
9973         String dumpPackage = null;
9974         int dumpUserId = UserHandle.USER_ALL;
9975 
9976         int opti = 0;
9977         while (opti < args.length) {
9978             String opt = args[opti];
9979             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9980                 break;
9981             }
9982             opti++;
9983             if ("-a".equals(opt)) {
9984                 dumpAll = true;
9985             } else if ("-c".equals(opt)) {
9986                 dumpClient = true;
9987             } else if ("-v".equals(opt)) {
9988                 dumpVisibleStacksOnly = true;
9989             } else if ("-f".equals(opt)) {
9990                 dumpFocusedStackOnly = true;
9991             } else if ("-p".equals(opt)) {
9992                 if (opti < args.length) {
9993                     dumpPackage = args[opti];
9994                     opti++;
9995                 } else {
9996                     pw.println("Error: -p option requires package argument");
9997                     return;
9998                 }
9999                 dumpClient = true;
10000             } else if ("--checkin".equals(opt)) {
10001                 dumpCheckin = dumpCheckinFormat = true;
10002             } else if ("-C".equals(opt)) {
10003                 dumpCheckinFormat = true;
10004             } else if ("--normal-priority".equals(opt)) {
10005                 dumpNormalPriority = true;
10006             } else if ("--user".equals(opt)) {
10007                 if (opti < args.length) {
10008                     dumpUserId = UserHandle.parseUserArg(args[opti]);
10009                     if (dumpUserId == UserHandle.USER_CURRENT) {
10010                         dumpUserId = mUserController.getCurrentUserId();
10011                     }
10012                     opti++;
10013                 } else {
10014                     pw.println("Error: --user option requires user id argument");
10015                     return;
10016                 }
10017             } else if ("-d".equals(opt)) {
10018                 if (opti < args.length) {
10019                     dumpDisplayId = Integer.parseInt(args[opti]);
10020                     if (dumpDisplayId == INVALID_DISPLAY) {
10021                         pw.println("Error: -d cannot be used with INVALID_DISPLAY");
10022                         return;
10023                     }
10024                     opti++;
10025                 } else {
10026                     pw.println("Error: -d option requires display argument");
10027                     return;
10028                 }
10029                 dumpClient = true;
10030             } else if ("-h".equals(opt)) {
10031                 ActivityManagerShellCommand.dumpHelp(pw, true);
10032                 return;
10033             } else {
10034                 pw.println("Unknown argument: " + opt + "; use -h for help");
10035                 return;
10036             }
10037         }
10038 
10039         final long origId = Binder.clearCallingIdentity();
10040 
10041         if (useProto) {
10042             final ProtoOutputStream proto = new ProtoOutputStream(fd);
10043             String cmd = opti < args.length ? args[opti] : "";
10044             opti++;
10045 
10046             if ("activities".equals(cmd) || "a".equals(cmd)) {
10047                 // output proto is ActivityManagerServiceDumpActivitiesProto
10048                 mAtmInternal.writeActivitiesToProto(proto);
10049             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10050                 // output proto is ActivityManagerServiceDumpBroadcastsProto
10051                 synchronized (this) {
10052                     writeBroadcastsToProtoLocked(proto);
10053                 }
10054             } else if ("provider".equals(cmd)) {
10055                 String[] newArgs;
10056                 String name;
10057                 if (opti >= args.length) {
10058                     name = null;
10059                     newArgs = EMPTY_STRING_ARRAY;
10060                 } else {
10061                     name = args[opti];
10062                     opti++;
10063                     newArgs = new String[args.length - opti];
10064                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10065                             args.length - opti);
10066                 }
10067                 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) {
10068                     pw.println("No providers match: " + name);
10069                     pw.println("Use -h for help.");
10070                 }
10071             } else if ("service".equals(cmd)) {
10072                 // output proto is ActivityManagerServiceDumpServicesProto
10073                 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10074             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10075                 if (opti < args.length) {
10076                     dumpPackage = args[opti];
10077                     opti++;
10078                 }
10079                 // output proto is ProcessProto
10080                 synchronized (this) {
10081                     synchronized (mProcLock) {
10082                         mProcessList.writeProcessesToProtoLSP(proto, dumpPackage);
10083                     }
10084                 }
10085             } else if ("app-restrictions".equals(cmd)) {
10086                 int uid = Process.INVALID_UID;
10087                 boolean error = false;
10088                 for (int i = 0; i < args.length; i++) {
10089                     if ("--uid".equals(args[i])) {
10090                         if (i + 1 < args.length) {
10091                             try {
10092                                 uid = Integer.parseInt(args[i + 1]);
10093                             } catch (NumberFormatException e) {
10094                                 error = true;
10095                             }
10096                         } else {
10097                             error = true;
10098                         }
10099                         break;
10100                     }
10101                 }
10102                 if (error) {
10103                     pw.println("Invalid --uid argument");
10104                     pw.println("Use -h for help.");
10105                 } else {
10106                     dumpAppRestrictionController(proto, uid);
10107                 }
10108             } else {
10109                 // default option, dump everything, output is ActivityManagerServiceProto
10110                 synchronized (this) {
10111                     long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES);
10112                     mAtmInternal.writeActivitiesToProto(proto);
10113                     proto.end(activityToken);
10114 
10115                     long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS);
10116                     writeBroadcastsToProtoLocked(proto);
10117                     proto.end(broadcastToken);
10118 
10119                     long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES);
10120                     mServices.dumpDebug(proto,
10121                             ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10122                     proto.end(serviceToken);
10123 
10124                     long processToken = proto.start(ActivityManagerServiceProto.PROCESSES);
10125                     synchronized (mProcLock) {
10126                         mProcessList.writeProcessesToProtoLSP(proto, dumpPackage);
10127                     }
10128                     proto.end(processToken);
10129                 }
10130             }
10131             proto.flush();
10132             Binder.restoreCallingIdentity(origId);
10133             return;
10134         }
10135 
10136         int dumpAppId = getAppId(dumpPackage);
10137         boolean more = false;
10138         // Is the caller requesting to dump a particular piece of data?
10139         if (opti < args.length) {
10140             String cmd = args[opti];
10141             opti++;
10142             if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
10143                     || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
10144                     || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
10145                     || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)
10146                     || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd)
10147                     || DUMP_VISIBLE_ACTIVITIES.equals(cmd)) {
10148                 mAtmInternal.dump(cmd, fd, pw, args, opti, /* dumpAll= */ true , dumpClient,
10149                         dumpPackage, dumpDisplayId);
10150             } else if ("binder-proxies".equals(cmd)) {
10151                 if (opti >= args.length) {
10152                     dumpBinderProxies(pw, 0 /* minToDump */);
10153                 } else {
10154                     String uid = args[opti];
10155                     opti++;
10156                     // Ensure Binder Proxy Count is as up to date as possible
10157                     System.gc();
10158                     System.runFinalization();
10159                     System.gc();
10160                     pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid)));
10161                 }
10162             } else if ("allowed-associations".equals(cmd)) {
10163                 if (opti < args.length) {
10164                     dumpPackage = args[opti];
10165                     opti++;
10166                 }
10167                 synchronized (this) {
10168                     dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage);
10169                 }
10170             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10171                 if (opti < args.length) {
10172                     dumpPackage = args[opti];
10173                     opti++;
10174                 }
10175                 synchronized (this) {
10176                     dumpBroadcastsLocked(fd, pw, args, opti, /* dumpAll= */ true, dumpPackage);
10177                 }
10178             } else if ("broadcast-stats".equals(cmd)) {
10179                 if (opti < args.length) {
10180                     dumpPackage = args[opti];
10181                     opti++;
10182                 }
10183                 synchronized (this) {
10184                     if (dumpCheckinFormat) {
10185                         dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
10186                                 dumpPackage);
10187                     } else {
10188                         dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
10189                     }
10190                 }
10191             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
10192                 if (opti < args.length) {
10193                     dumpPackage = args[opti];
10194                     opti++;
10195                 }
10196                 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage);
10197             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10198                 if (opti < args.length) {
10199                     dumpPackage = args[opti];
10200                     opti++;
10201                 }
10202                 synchronized (this) {
10203                     synchronized (mProcLock) {
10204                         mProcessList.dumpProcessesLSP(
10205                                 fd, pw, args, opti, true, dumpPackage, dumpAppId);
10206                     }
10207                 }
10208             } else if ("oom".equals(cmd) || "o".equals(cmd)) {
10209                 synchronized (this) {
10210                     mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true);
10211                 }
10212             } else if ("lmk".equals(cmd)) {
10213                 synchronized (this) {
10214                     dumpLmkLocked(pw);
10215                 }
10216             } else if ("lru".equals(cmd)) {
10217                 synchronized (this) {
10218                     mProcessList.dumpLruLocked(pw, dumpPackage, null);
10219                 }
10220             } else if ("permissions".equals(cmd) || "perm".equals(cmd)) {
10221                 dumpPermissions(fd, pw, args, opti, true, dumpPackage);
10222             } else if ("provider".equals(cmd)) {
10223                 String[] newArgs;
10224                 String name;
10225                 if (opti >= args.length) {
10226                     name = null;
10227                     newArgs = EMPTY_STRING_ARRAY;
10228                 } else {
10229                     name = args[opti];
10230                     opti++;
10231                     newArgs = new String[args.length - opti];
10232                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
10233                 }
10234                 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
10235                     pw.println("No providers match: " + name);
10236                     pw.println("Use -h for help.");
10237                 }
10238             } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
10239                 synchronized (this) {
10240                     mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage);
10241                 }
10242             } else if ("service".equals(cmd)) {
10243                 String[] newArgs;
10244                 String name;
10245                 if (opti >= args.length) {
10246                     name = null;
10247                     newArgs = EMPTY_STRING_ARRAY;
10248                 } else {
10249                     name = args[opti];
10250                     opti++;
10251                     newArgs = new String[args.length - opti];
10252                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10253                             args.length - opti);
10254                 }
10255                 int[] users = dumpUserId == UserHandle.USER_ALL ? null : new int[] { dumpUserId };
10256                 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) {
10257                     pw.println("No services match: " + name);
10258                     pw.println("Use -h for help.");
10259                 }
10260             } else if ("package".equals(cmd)) {
10261                 String[] newArgs;
10262                 if (opti >= args.length) {
10263                     pw.println("package: no package name specified");
10264                     pw.println("Use -h for help.");
10265                 } else {
10266                     dumpPackage = args[opti];
10267                     opti++;
10268                     newArgs = new String[args.length - opti];
10269                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10270                             args.length - opti);
10271                     args = newArgs;
10272                     opti = 0;
10273                     more = true;
10274                 }
10275             } else if ("associations".equals(cmd) || "as".equals(cmd)) {
10276                 synchronized (this) {
10277                     dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage);
10278                 }
10279             } else if ("settings".equals(cmd)) {
10280                 synchronized (this) {
10281                     mConstants.dump(pw);
10282                 }
10283                 synchronized (mProcLock) {
10284                     mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
10285                     mOomAdjuster.dumpCacheOomRankerSettings(pw);
10286                 }
10287             } else if ("services".equals(cmd) || "s".equals(cmd)) {
10288                 if (dumpClient) {
10289                     ActiveServices.ServiceDumper dumper;
10290                     synchronized (this) {
10291                         dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10292                                 dumpPackage);
10293                     }
10294                     dumper.dumpWithClient();
10295                 } else {
10296                     synchronized (this) {
10297                         mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10298                                 dumpPackage).dumpLocked();
10299                     }
10300                 }
10301             } else if ("locks".equals(cmd)) {
10302                 LockGuard.dump(fd, pw, args);
10303             } else if ("users".equals(cmd)) {
10304                 dumpUsers(pw);
10305             } else if ("exit-info".equals(cmd)) {
10306                 if (opti < args.length) {
10307                     dumpPackage = args[opti];
10308                     opti++;
10309                 }
10310                 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
10311             } else if ("component-alias".equals(cmd)) {
10312                 mComponentAliasResolver.dump(pw);
10313             } else {
10314                 // Dumping a single activity?
10315                 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll,
10316                         dumpVisibleStacksOnly, dumpFocusedStackOnly, dumpDisplayId, dumpUserId)) {
10317                     ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true);
10318                     int res = shell.exec(this, null, fd, null, args, null,
10319                             new ResultReceiver(null));
10320                     if (res < 0) {
10321                         pw.println("Bad activity command, or no activities match: " + cmd);
10322                         pw.println("Use -h for help.");
10323                     }
10324                 }
10325             }
10326             if (!more) {
10327                 Binder.restoreCallingIdentity(origId);
10328                 return;
10329             }
10330         }
10331 
10332         // No piece of data specified, dump everything.
10333         if (dumpCheckinFormat) {
10334             dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage);
10335         } else {
10336             if (dumpClient) {
10337                 // dumpEverything() will take the lock when needed, and momentarily drop
10338                 // it for dumping client state.
10339                 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId,
10340                         dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ true);
10341             } else {
10342                 // Take the lock here, so we get a consistent state for the entire dump;
10343                 // dumpEverything() will take the lock as well, which is fine for everything
10344                 // except dumping proxies, which can take a long time; exclude them.
10345                 synchronized(this) {
10346                     dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpDisplayId,
10347                             dumpClient, dumpNormalPriority, dumpAppId, /* dumpProxies= */ false);
10348                 }
10349             }
10350             if (dumpAll) {
10351                 dumpAppRestrictionController(pw);
10352             }
10353         }
10354         Binder.restoreCallingIdentity(origId);
10355     }
10356 
dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)10357     void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10358             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
10359         pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)");
10360 
10361         int dumpUid = 0;
10362         if (dumpPackage != null) {
10363             IPackageManager pm = AppGlobals.getPackageManager();
10364             try {
10365                 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0);
10366             } catch (RemoteException e) {
10367             }
10368         }
10369 
10370         boolean printedAnything = false;
10371 
10372         final long now = SystemClock.uptimeMillis();
10373 
10374         for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
10375             ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
10376                     = mAssociations.valueAt(i1);
10377             for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
10378                 SparseArray<ArrayMap<String, Association>> sourceUids
10379                         = targetComponents.valueAt(i2);
10380                 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) {
10381                     ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3);
10382                     for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
10383                         Association ass = sourceProcesses.valueAt(i4);
10384                         if (dumpPackage != null) {
10385                             if (!ass.mTargetComponent.getPackageName().equals(dumpPackage)
10386                                     && UserHandle.getAppId(ass.mSourceUid) != dumpUid) {
10387                                 continue;
10388                             }
10389                         }
10390                         printedAnything = true;
10391                         pw.print("  ");
10392                         pw.print(ass.mTargetProcess);
10393                         pw.print("/");
10394                         UserHandle.formatUid(pw, ass.mTargetUid);
10395                         pw.print(" <- ");
10396                         pw.print(ass.mSourceProcess);
10397                         pw.print("/");
10398                         UserHandle.formatUid(pw, ass.mSourceUid);
10399                         pw.println();
10400                         pw.print("    via ");
10401                         pw.print(ass.mTargetComponent.flattenToShortString());
10402                         pw.println();
10403                         pw.print("    ");
10404                         long dur = ass.mTime;
10405                         if (ass.mNesting > 0) {
10406                             dur += now - ass.mStartTime;
10407                         }
10408                         TimeUtils.formatDuration(dur, pw);
10409                         pw.print(" (");
10410                         pw.print(ass.mCount);
10411                         pw.print(" times)");
10412                         pw.print("  ");
10413                         for (int i=0; i<ass.mStateTimes.length; i++) {
10414                             long amt = ass.mStateTimes[i];
10415                             if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10416                                 amt += now - ass.mLastStateUptime;
10417                             }
10418                             if (amt != 0) {
10419                                 pw.print(" ");
10420                                 pw.print(ProcessList.makeProcStateString(
10421                                             i + ActivityManager.MIN_PROCESS_STATE));
10422                                 pw.print("=");
10423                                 TimeUtils.formatDuration(amt, pw);
10424                                 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10425                                     pw.print("*");
10426                                 }
10427                             }
10428                         }
10429                         pw.println();
10430                         if (ass.mNesting > 0) {
10431                             pw.print("    Currently active: ");
10432                             TimeUtils.formatDuration(now - ass.mStartTime, pw);
10433                             pw.println();
10434                         }
10435                     }
10436                 }
10437             }
10438 
10439         }
10440 
10441         if (!printedAnything) {
10442             pw.println("  (nothing)");
10443         }
10444     }
10445 
getAppId(String dumpPackage)10446     int getAppId(String dumpPackage) {
10447         if (dumpPackage != null) {
10448             try {
10449                 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
10450                         dumpPackage, 0);
10451                 return UserHandle.getAppId(info.uid);
10452             } catch (NameNotFoundException e) {
10453                 e.printStackTrace();
10454             }
10455         }
10456         return -1;
10457     }
10458 
dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)10459     void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) {
10460         final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50);
10461 
10462         pw.println(header);
10463         for (int i = 0; i < proxyCounts.length; i++) {
10464             pw.println("    #" + (i + 1) + ": " + proxyCounts[i]);
10465         }
10466     }
10467 
dumpBinderProxiesCounts(PrintWriter pw, String header)10468     boolean dumpBinderProxiesCounts(PrintWriter pw, String header) {
10469         SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
10470         if(counts != null) {
10471             pw.println(header);
10472             for (int i = 0; i < counts.size(); i++) {
10473                 final int uid = counts.keyAt(i);
10474                 final int binderCount = counts.valueAt(i);
10475                 pw.print("    UID ");
10476                 pw.print(uid);
10477                 pw.print(", binder count = ");
10478                 pw.print(binderCount);
10479                 pw.print(", package(s)= ");
10480                 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid);
10481                 if (pkgNames != null) {
10482                     for (int j = 0; j < pkgNames.length; j++) {
10483                         pw.print(pkgNames[j]);
10484                         pw.print("; ");
10485                     }
10486                 } else {
10487                     pw.print("NO PACKAGE NAME FOUND");
10488                 }
10489                 pw.println();
10490             }
10491             return true;
10492         }
10493         return false;
10494     }
10495 
dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)10496     void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) {
10497         pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)");
10498         final int proxyCount = BinderProxy.getProxyCount();
10499         if (proxyCount >= minCountToDumpInterfaces) {
10500             dumpBinderProxyInterfaceCounts(pw,
10501                     "Top proxy interface names held by SYSTEM");
10502         } else {
10503             pw.print("Not dumping proxy interface counts because size ("
10504                     + Integer.toString(proxyCount) + ") looks reasonable");
10505             pw.println();
10506         }
10507         dumpBinderProxiesCounts(pw,
10508                 "  Counts of Binder Proxies held by SYSTEM");
10509     }
10510 
10511     @GuardedBy("this")
dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)10512     boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) {
10513         final int size = mActiveInstrumentation.size();
10514         if (size > 0) {
10515             boolean printed = false;
10516             for (int i = 0; i < size; i++) {
10517                 ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10518                 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10519                         && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10520                     continue;
10521                 }
10522                 if (!printed) {
10523                     if (needSep) {
10524                         pw.println();
10525                     }
10526                     pw.println("  Active instrumentation:");
10527                     printed = true;
10528                     needSep = true;
10529                 }
10530                 pw.print("    Instrumentation #"); pw.print(i); pw.print(": ");
10531                 pw.println(ai);
10532                 ai.dump(pw, "      ");
10533             }
10534         }
10535         return needSep;
10536     }
10537 
10538     @NeverCompile // Avoid size overhead of debugging code.
10539     @GuardedBy({"this", "mProcLock"})
dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)10540     void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw,
10541             boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) {
10542         if (dumpAll || dumpPackage != null) {
10543             final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>();
10544             synchronized (mPidsSelfLocked) {
10545                 boolean printed = false;
10546                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
10547                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10548                     pidToProcess.put(r.getPid(), r);
10549                     if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) {
10550                         continue;
10551                     }
10552                     if (!printed) {
10553                         if (needSep) pw.println();
10554                         needSep = true;
10555                         pw.println("  PID mappings:");
10556                         printed = true;
10557                     }
10558                     pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
10559                     pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
10560                 }
10561             }
10562 
10563             synchronized (sActiveProcessInfoSelfLocked) {
10564                 boolean printed = false;
10565                 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) {
10566                     ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i);
10567                     ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i));
10568                     if (r != null && dumpPackage != null
10569                             && !r.getPkgList().containsKey(dumpPackage)) {
10570                         continue;
10571                     }
10572                     if (!printed) {
10573                         if (needSep) pw.println();
10574                         needSep = true;
10575                         pw.println("  Active process infos:");
10576                         printed = true;
10577                     }
10578                     pw.print("    Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i));
10579                     pw.println(":");
10580                     pw.print("      name="); pw.println(info.name);
10581                     if (info.deniedPermissions != null) {
10582                         for (int j = 0; j < info.deniedPermissions.size(); j++) {
10583                             pw.print("      deny: ");
10584                             pw.println(info.deniedPermissions.valueAt(j));
10585                         }
10586                     }
10587                 }
10588             }
10589         }
10590 
10591         if (dumpAll) {
10592             mPhantomProcessList.dump(pw, "  ");
10593         }
10594 
10595         if (mImportantProcesses.size() > 0) {
10596             synchronized (mPidsSelfLocked) {
10597                 boolean printed = false;
10598                 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) {
10599                     ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid);
10600                     if (dumpPackage != null && (r == null
10601                             || !r.getPkgList().containsKey(dumpPackage))) {
10602                         continue;
10603                     }
10604                     if (!printed) {
10605                         if (needSep) pw.println();
10606                         needSep = true;
10607                         pw.println("  Foreground Processes:");
10608                         printed = true;
10609                     }
10610                     pw.print("    PID #"); pw.print(mImportantProcesses.keyAt(i));
10611                             pw.print(": "); pw.println(mImportantProcesses.valueAt(i));
10612                 }
10613             }
10614         }
10615 
10616         if (mPersistentStartingProcesses.size() > 0) {
10617             if (needSep) pw.println();
10618             needSep = true;
10619             pw.println("  Persisent processes that are starting:");
10620             dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
10621                     "Starting Norm", "Restarting PERS", dumpPackage);
10622         }
10623 
10624         if (mProcessList.mRemovedProcesses.size() > 0) {
10625             if (needSep) pw.println();
10626             needSep = true;
10627             pw.println("  Processes that are being removed:");
10628             dumpProcessList(pw, this, mProcessList.mRemovedProcesses, "    ",
10629                     "Removed Norm", "Removed PERS", dumpPackage);
10630         }
10631 
10632         if (mProcessesOnHold.size() > 0) {
10633             if (needSep) pw.println();
10634             needSep = true;
10635             pw.println("  Processes that are on old until the system is ready:");
10636             dumpProcessList(pw, this, mProcessesOnHold, "    ",
10637                     "OnHold Norm", "OnHold PERS", dumpPackage);
10638         }
10639 
10640         needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage);
10641 
10642         needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep,
10643                 mAppProfiler.getTestPssMode(), mWakefulness.get());
10644 
10645         if (dumpAll && mProcessList.mPendingStarts.size() > 0) {
10646             if (needSep) pw.println();
10647             needSep = true;
10648             pw.println("  mPendingStarts: ");
10649             for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) {
10650                 pw.println("    " + mProcessList.mPendingStarts.keyAt(i) + ": "
10651                         + mProcessList.mPendingStarts.valueAt(i));
10652             }
10653         }
10654         if (dumpAll) {
10655             mUidObserverController.dump(pw, dumpPackage);
10656 
10657             pw.println("  mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist));
10658             pw.println("  mDeviceIdleExceptIdleAllowlist="
10659                     + Arrays.toString(mDeviceIdleExceptIdleAllowlist));
10660             pw.println("  mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist));
10661             if (mPendingTempAllowlist.size() > 0) {
10662                 pw.println("  mPendingTempAllowlist:");
10663                 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) {
10664                     PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i);
10665                     pw.print("    ");
10666                     UserHandle.formatUid(pw, ptw.targetUid);
10667                     pw.print(": ");
10668                     TimeUtils.formatDuration(ptw.duration, pw);
10669                     pw.print(" ");
10670                     pw.println(ptw.tag);
10671                     pw.print(" ");
10672                     pw.print(ptw.type);
10673                     pw.print(" ");
10674                     pw.print(ptw.reasonCode);
10675                     pw.print(" ");
10676                     pw.print(ptw.callingUid);
10677                 }
10678             }
10679             pw.println("  mFgsStartTempAllowList:");
10680             final long currentTimeNow = System.currentTimeMillis();
10681             final long elapsedRealtimeNow = SystemClock.elapsedRealtime();
10682             mFgsStartTempAllowList.forEach((uid, entry) -> {
10683                 pw.print("    " + UserHandle.formatUid(uid) + ": ");
10684                 entry.second.dump(pw);
10685                 pw.print(" expiration=");
10686                 // Convert entry.mExpirationTime, which is an elapsed time since boot,
10687                 // to a time since epoch (i.e. System.currentTimeMillis()-based time.)
10688                 final long expirationInCurrentTime =
10689                         currentTimeNow - elapsedRealtimeNow + entry.first;
10690                 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow);
10691                 pw.println();
10692             });
10693 
10694             if (!mProcessList.mAppsInBackgroundRestricted.isEmpty()) {
10695                 pw.println("  Processes that are in background restricted:");
10696                 for (int i = 0, size = mProcessList.mAppsInBackgroundRestricted.size();
10697                         i < size; i++) {
10698                     pw.println(String.format("%s #%2d: %s", "    ", i,
10699                             mProcessList.mAppsInBackgroundRestricted.valueAt(i).toString()));
10700                 }
10701             }
10702         }
10703         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
10704                 || mOrigWaitForDebugger) {
10705             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
10706                     || dumpPackage.equals(mOrigDebugApp)) {
10707                 if (needSep) {
10708                     pw.println();
10709                     needSep = false;
10710                 }
10711                 pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
10712                         + " mDebugTransient=" + mDebugTransient
10713                         + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
10714             }
10715         }
10716         synchronized (mAppProfiler.mProfilerLock) {
10717             needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep);
10718         }
10719         if (mTrackAllocationApp != null) {
10720             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
10721                 if (needSep) {
10722                     pw.println();
10723                     needSep = false;
10724                 }
10725                 pw.println("  mTrackAllocationApp=" + mTrackAllocationApp);
10726             }
10727         }
10728         needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep);
10729         if (mNativeDebuggingApp != null) {
10730             if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
10731                 if (needSep) {
10732                     pw.println();
10733                     needSep = false;
10734                 }
10735                 pw.println("  mNativeDebuggingApp=" + mNativeDebuggingApp);
10736             }
10737         }
10738         if (dumpPackage == null) {
10739             if (mAlwaysFinishActivities) {
10740                 pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities);
10741             }
10742             if (dumpAll) {
10743                 pw.println("  Total persistent processes: " + numPers);
10744                 pw.println("  mProcessesReady=" + mProcessesReady
10745                         + " mSystemReady=" + mSystemReady
10746                         + " mBooted=" + mBooted
10747                         + " mFactoryTest=" + mFactoryTest);
10748                 pw.println("  mBooting=" + mBooting
10749                         + " mCallFinishBooting=" + mCallFinishBooting
10750                         + " mBootAnimationComplete=" + mBootAnimationComplete);
10751                 pw.print("  mLastPowerCheckUptime=");
10752                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
10753                         pw.println("");
10754                 mOomAdjuster.dumpSequenceNumbersLocked(pw);
10755                 mOomAdjuster.dumpProcCountsLocked(pw);
10756                 mAppProfiler.dumpMemoryLevelsLocked(pw);
10757                 long now = SystemClock.uptimeMillis();
10758                 pw.print("  mLastIdleTime=");
10759                         TimeUtils.formatDuration(now, mLastIdleTime, pw);
10760                         pw.print(" mLowRamSinceLastIdle=");
10761                         TimeUtils.formatDuration(
10762                                 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw);
10763                         pw.println();
10764 
10765                 pw.println();
10766                 pw.println("  ServiceManager statistics:");
10767                 ServiceManager.sStatLogger.dump(pw, "    ");
10768                 pw.println();
10769             }
10770         }
10771         pw.println("  mForceBackgroundCheck=" + mForceBackgroundCheck);
10772     }
10773 
dumpUsers(PrintWriter pw)10774     private void dumpUsers(PrintWriter pw) {
10775         pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)");
10776         mUserController.dump(pw);
10777     }
10778 
10779     @GuardedBy({"this", "mProcLock"})
writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)10780     void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage,
10781             int dumpAppId, int numPers) {
10782         for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) {
10783             ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10784             if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10785                     && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10786                 continue;
10787             }
10788             ai.dumpDebug(proto,
10789                     ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS);
10790         }
10791 
10792         mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId,
10793                 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS);
10794 
10795         if (dumpPackage != null) {
10796             synchronized (mPidsSelfLocked) {
10797                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
10798                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10799                     if (!r.getPkgList().containsKey(dumpPackage)) {
10800                         continue;
10801                     }
10802                     r.dumpDebug(proto,
10803                             ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED);
10804                 }
10805             }
10806         }
10807 
10808         if (mImportantProcesses.size() > 0) {
10809             synchronized (mPidsSelfLocked) {
10810                 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) {
10811                     ImportanceToken it = mImportantProcesses.valueAt(i);
10812                     ProcessRecord r = mPidsSelfLocked.get(it.pid);
10813                     if (dumpPackage != null && (r == null
10814                             || !r.getPkgList().containsKey(dumpPackage))) {
10815                         continue;
10816                     }
10817                     it.dumpDebug(proto,
10818                             ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS);
10819                 }
10820             }
10821         }
10822 
10823         for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) {
10824             ProcessRecord r = mPersistentStartingProcesses.get(i);
10825             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10826                 continue;
10827             }
10828             r.dumpDebug(proto,
10829                     ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS);
10830         }
10831 
10832         for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) {
10833             ProcessRecord r = mProcessList.mRemovedProcesses.get(i);
10834             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10835                 continue;
10836             }
10837             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS);
10838         }
10839 
10840         for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) {
10841             ProcessRecord r = mProcessesOnHold.get(i);
10842             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10843                 continue;
10844             }
10845             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS);
10846         }
10847 
10848         synchronized (mAppProfiler.mProfilerLock) {
10849             mAppProfiler.writeProcessesToGcToProto(proto,
10850                     ActivityManagerServiceDumpProcessesProto.GC_PROCS,
10851                     dumpPackage);
10852         }
10853         mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS,
10854                 dumpPackage);
10855         mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(),
10856                 mAppProfiler.getTestPssMode());
10857 
10858         if (dumpPackage == null) {
10859             mUserController.dumpDebug(proto,
10860             ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER);
10861         }
10862 
10863         mUidObserverController.dumpDebug(proto, dumpPackage);
10864 
10865         for (int v : mDeviceIdleAllowlist) {
10866             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v);
10867         }
10868 
10869         for (int v : mDeviceIdleTempAllowlist) {
10870             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v);
10871         }
10872 
10873         if (mPendingTempAllowlist.size() > 0) {
10874             for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) {
10875                 mPendingTempAllowlist.valueAt(i).dumpDebug(proto,
10876                         ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST);
10877             }
10878         }
10879 
10880         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
10881                 || mOrigWaitForDebugger) {
10882             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
10883                     || dumpPackage.equals(mOrigDebugApp)) {
10884                 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG);
10885                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp);
10886                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp);
10887                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient);
10888                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger);
10889                 proto.end(debugAppToken);
10890             }
10891         }
10892 
10893         synchronized (mAppProfiler.mProfilerLock) {
10894             mAppProfiler.writeMemWatchProcessToProtoLPf(proto);
10895         }
10896 
10897         if (mTrackAllocationApp != null) {
10898             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
10899                 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP,
10900                         mTrackAllocationApp);
10901             }
10902         }
10903 
10904         mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage);
10905 
10906         if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
10907             proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp);
10908         }
10909 
10910         if (dumpPackage == null) {
10911             proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities);
10912             proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers);
10913             proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady);
10914             proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady);
10915             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted);
10916             proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest);
10917             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting);
10918             proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting);
10919             proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete);
10920             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime);
10921             mOomAdjuster.dumpProcessListVariablesLocked(proto);
10922             mAppProfiler.writeMemoryLevelsToProtoLocked(proto);
10923             long now = SystemClock.uptimeMillis();
10924             ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now);
10925             proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS,
10926                     mAppProfiler.getLowRamTimeSinceIdleLPr(now));
10927         }
10928     }
10929 
reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)10930     private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) {
10931         Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj);
10932         if (cnt != null) {
10933             pw.println("    kills at or below oom_adj " + oom_adj + ": " + cnt);
10934             return true;
10935         }
10936         return false;
10937     }
10938 
dumpLmkLocked(PrintWriter pw)10939     boolean dumpLmkLocked(PrintWriter pw) {
10940         pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)");
10941         Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ,
10942                 ProcessList.UNKNOWN_ADJ);
10943         if (cnt == null) {
10944             return false;
10945         }
10946         pw.println("  Total number of kills: " + cnt);
10947 
10948         return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) &&
10949                 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) &&
10950                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) &&
10951                 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) &&
10952                 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) &&
10953                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) &&
10954                 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) &&
10955                 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) &&
10956                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) &&
10957                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) &&
10958                 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) &&
10959                 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ);
10960     }
10961 
10962     public static class ItemMatcher {
10963         ArrayList<ComponentName> components;
10964         ArrayList<String> strings;
10965         ArrayList<Integer> objects;
10966         boolean all;
10967 
ItemMatcher()10968         public ItemMatcher() {
10969             all = true;
10970         }
10971 
build(String name)10972         public void build(String name) {
10973             ComponentName componentName = ComponentName.unflattenFromString(name);
10974             if (componentName != null) {
10975                 if (components == null) {
10976                     components = new ArrayList<ComponentName>();
10977                 }
10978                 components.add(componentName);
10979                 all = false;
10980             } else {
10981                 int objectId = 0;
10982                 // Not a '/' separated full component name; maybe an object ID?
10983                 try {
10984                     objectId = Integer.parseInt(name, 16);
10985                     if (objects == null) {
10986                         objects = new ArrayList<Integer>();
10987                     }
10988                     objects.add(objectId);
10989                     all = false;
10990                 } catch (RuntimeException e) {
10991                     // Not an integer; just do string match.
10992                     if (strings == null) {
10993                         strings = new ArrayList<String>();
10994                     }
10995                     strings.add(name);
10996                     all = false;
10997                 }
10998             }
10999         }
11000 
build(String[] args, int opti)11001         public int build(String[] args, int opti) {
11002             for (; opti<args.length; opti++) {
11003                 String name = args[opti];
11004                 if ("--".equals(name)) {
11005                     return opti+1;
11006                 }
11007                 build(name);
11008             }
11009             return opti;
11010         }
11011 
match(Object object, ComponentName comp)11012         public boolean match(Object object, ComponentName comp) {
11013             if (all) {
11014                 return true;
11015             }
11016             if (components != null) {
11017                 for (int i=0; i<components.size(); i++) {
11018                     if (components.get(i).equals(comp)) {
11019                         return true;
11020                     }
11021                 }
11022             }
11023             if (objects != null) {
11024                 for (int i=0; i<objects.size(); i++) {
11025                     if (System.identityHashCode(object) == objects.get(i)) {
11026                         return true;
11027                     }
11028                 }
11029             }
11030             if (strings != null) {
11031                 String flat = comp.flattenToString();
11032                 for (int i=0; i<strings.size(); i++) {
11033                     if (flat.contains(strings.get(i))) {
11034                         return true;
11035                     }
11036                 }
11037             }
11038             return false;
11039         }
11040     }
11041 
writeBroadcastsToProtoLocked(ProtoOutputStream proto)11042     void writeBroadcastsToProtoLocked(ProtoOutputStream proto) {
11043         if (mRegisteredReceivers.size() > 0) {
11044             Iterator it = mRegisteredReceivers.values().iterator();
11045             while (it.hasNext()) {
11046                 ReceiverList r = (ReceiverList)it.next();
11047                 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST);
11048             }
11049         }
11050         mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER);
11051         for (BroadcastQueue q : mBroadcastQueues) {
11052             q.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE);
11053         }
11054         for (int user=0; user<mStickyBroadcasts.size(); user++) {
11055             long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS);
11056             proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user));
11057             for (Map.Entry<String, ArrayList<StickyBroadcast>> ent
11058                     : mStickyBroadcasts.valueAt(user).entrySet()) {
11059                 long actionToken = proto.start(StickyBroadcastProto.ACTIONS);
11060                 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey());
11061                 for (StickyBroadcast broadcast : ent.getValue()) {
11062                     broadcast.intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS,
11063                             false, true, true, false);
11064                 }
11065                 proto.end(actionToken);
11066             }
11067             proto.end(token);
11068         }
11069 
11070         long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER);
11071         proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString());
11072         mHandler.getLooper().dumpDebug(proto,
11073             ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER);
11074         proto.end(handlerToken);
11075     }
11076 
dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11077     void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11078             int opti, boolean dumpAll, String dumpPackage) {
11079         pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)");
11080         boolean printed = false;
11081         if (mAllowedAssociations != null) {
11082             for (int i = 0; i < mAllowedAssociations.size(); i++) {
11083                 final String pkg = mAllowedAssociations.keyAt(i);
11084                 final ArraySet<String> asc =
11085                         mAllowedAssociations.valueAt(i).getAllowedPackageAssociations();
11086                 if (!printed) {
11087                     pw.println("  Allowed associations (by restricted package):");
11088                     printed = true;
11089                 }
11090                 pw.print("  * ");
11091                 pw.print(pkg);
11092                 pw.println(":");
11093                 for (int j = 0; j < asc.size(); j++) {
11094                     if (dumpPackage == null || pkg.equals(dumpPackage)
11095                             || asc.valueAt(j).equals(dumpPackage)) {
11096                         pw.print("      Allow: ");
11097                         pw.println(asc.valueAt(j));
11098                     }
11099                 }
11100                 if (mAllowedAssociations.valueAt(i).isDebuggable()) {
11101                     pw.println("      (debuggable)");
11102                 }
11103             }
11104         }
11105         if (!printed) {
11106             pw.println("  (No association restrictions)");
11107         }
11108     }
11109 
11110     @NeverCompile
dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11111     void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11112             int opti, boolean dumpAll, String dumpPackage) {
11113         boolean dumpConstants = true;
11114         boolean dumpHistory = true;
11115         boolean needSep = false;
11116         boolean onlyHistory = false;
11117         boolean printedAnything = false;
11118         boolean onlyReceivers = false;
11119         int filteredUid = Process.INVALID_UID;
11120 
11121         if ("history".equals(dumpPackage)) {
11122             if (opti < args.length && "-s".equals(args[opti])) {
11123                 dumpAll = false;
11124             }
11125             onlyHistory = true;
11126             dumpPackage = null;
11127         }
11128         if ("receivers".equals(dumpPackage)) {
11129             onlyReceivers = true;
11130             dumpPackage = null;
11131             if (opti + 2 <= args.length) {
11132                 for (int i = opti; i < args.length; i++) {
11133                     String arg = args[i];
11134                     switch (arg) {
11135                         case "--uid":
11136                             filteredUid = getIntArg(pw, args, ++i, Process.INVALID_UID);
11137                             if (filteredUid == Process.INVALID_UID) {
11138                                 return;
11139                             }
11140                             break;
11141                         default:
11142                             pw.printf("Invalid argument at index %d: %s\n", i, arg);
11143                             return;
11144                     }
11145                 }
11146             }
11147         }
11148         if (DEBUG_BROADCAST) {
11149             Slogf.d(TAG_BROADCAST, "dumpBroadcastsLocked(): dumpPackage=%s, onlyHistory=%b, "
11150                     + "onlyReceivers=%b, filteredUid=%d", dumpPackage, onlyHistory, onlyReceivers,
11151                     filteredUid);
11152         }
11153 
11154         pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
11155         if (!onlyHistory && dumpAll) {
11156             if (mRegisteredReceivers.size() > 0) {
11157                 boolean printed = false;
11158                 Iterator it = mRegisteredReceivers.values().iterator();
11159                 while (it.hasNext()) {
11160                     ReceiverList r = (ReceiverList)it.next();
11161                     if (dumpPackage != null && (r.app == null ||
11162                             !dumpPackage.equals(r.app.info.packageName))) {
11163                         continue;
11164                     }
11165                     if (filteredUid != Process.INVALID_UID && filteredUid != r.app.uid) {
11166                         if (DEBUG_BROADCAST) {
11167                             Slogf.v(TAG_BROADCAST, "dumpBroadcastsLocked(): skipping receiver whose"
11168                                     + " uid (%d) is not %d: %s", r.app.uid, filteredUid, r.app);
11169                         }
11170                         continue;
11171                     }
11172                     if (!printed) {
11173                         pw.println("  Registered Receivers:");
11174                         needSep = true;
11175                         printed = true;
11176                         printedAnything = true;
11177                     }
11178                     pw.print("  * "); pw.println(r);
11179                     r.dump(pw, "    ");
11180                 }
11181             } else {
11182                 if (onlyReceivers) {
11183                     pw.println("  (no registered receivers)");
11184                 }
11185             }
11186 
11187             if (!onlyReceivers) {
11188                 if (mReceiverResolver.dump(pw, needSep
11189                         ? "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
11190                         "    ", dumpPackage, false, false)) {
11191                     needSep = true;
11192                     printedAnything = true;
11193                 }
11194             }
11195         }
11196 
11197         if (!onlyReceivers) {
11198             for (BroadcastQueue q : mBroadcastQueues) {
11199                 needSep = q.dumpLocked(fd, pw, args, opti,
11200                         dumpConstants, dumpHistory, dumpAll, dumpPackage, needSep);
11201                 printedAnything |= needSep;
11202             }
11203         }
11204 
11205         needSep = true;
11206 
11207         if (!onlyHistory && !onlyReceivers && mStickyBroadcasts != null && dumpPackage == null) {
11208             for (int user=0; user<mStickyBroadcasts.size(); user++) {
11209                 if (needSep) {
11210                     pw.println();
11211                 }
11212                 needSep = true;
11213                 printedAnything = true;
11214                 pw.print("  Sticky broadcasts for user ");
11215                         pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
11216                 StringBuilder sb = new StringBuilder(128);
11217                 for (Map.Entry<String, ArrayList<StickyBroadcast>> ent
11218                         : mStickyBroadcasts.valueAt(user).entrySet()) {
11219                     pw.print("  * Sticky action "); pw.print(ent.getKey());
11220                     if (dumpAll) {
11221                         pw.println(":");
11222                         ArrayList<StickyBroadcast> broadcasts = ent.getValue();
11223                         final int N = broadcasts.size();
11224                         for (int i=0; i<N; i++) {
11225                             final Intent intent = broadcasts.get(i).intent;
11226                             final boolean deferUntilActive = broadcasts.get(i).deferUntilActive;
11227                             sb.setLength(0);
11228                             sb.append("    Intent: ");
11229                             intent.toShortString(sb, false, true, false, false);
11230                             pw.print(sb);
11231                             if (deferUntilActive) {
11232                                 pw.print(" [D]");
11233                             }
11234                             pw.println();
11235                             pw.print("      originalCallingUid: ");
11236                             pw.println(broadcasts.get(i).originalCallingUid);
11237                             pw.println();
11238                             Bundle bundle = intent.getExtras();
11239                             if (bundle != null) {
11240                                 pw.print("      extras: ");
11241                                 pw.println(bundle);
11242                             }
11243                         }
11244                     } else {
11245                         pw.println("");
11246                     }
11247                 }
11248             }
11249         }
11250 
11251         if (!onlyHistory && !onlyReceivers && dumpAll) {
11252             pw.println();
11253             for (BroadcastQueue queue : mBroadcastQueues) {
11254                 pw.println("  Queue " + queue.toString() + ": " + queue.describeStateLocked());
11255             }
11256             pw.println("  mHandler:");
11257             mHandler.dump(new PrintWriterPrinter(pw), "    ");
11258             needSep = true;
11259             printedAnything = true;
11260         }
11261 
11262         if (!printedAnything) {
11263             pw.println("  (nothing)");
11264         }
11265     }
11266 
11267     @NeverCompile
dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11268     void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11269             int opti, boolean dumpAll, String dumpPackage) {
11270         if (mCurBroadcastStats == null) {
11271             return;
11272         }
11273 
11274         pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)");
11275         final long now = SystemClock.elapsedRealtime();
11276         if (mLastBroadcastStats != null) {
11277             pw.print("  Last stats (from ");
11278             TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw);
11279             pw.print(" to ");
11280             TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw);
11281             pw.print(", ");
11282             TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime
11283                     - mLastBroadcastStats.mStartUptime, pw);
11284             pw.println(" uptime):");
11285             if (!mLastBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11286                 pw.println("    (nothing)");
11287             }
11288             pw.println();
11289         }
11290         pw.print("  Current stats (from ");
11291         TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw);
11292         pw.print(" to now, ");
11293         TimeUtils.formatDuration(SystemClock.uptimeMillis()
11294                 - mCurBroadcastStats.mStartUptime, pw);
11295         pw.println(" uptime):");
11296         if (!mCurBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11297             pw.println("    (nothing)");
11298         }
11299     }
11300 
11301     @NeverCompile
dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)11302     void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11303             int opti, boolean fullCheckin, String dumpPackage) {
11304         if (mCurBroadcastStats == null) {
11305             return;
11306         }
11307 
11308         if (mLastBroadcastStats != null) {
11309             mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11310             if (fullCheckin) {
11311                 mLastBroadcastStats = null;
11312                 return;
11313             }
11314         }
11315         mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11316         if (fullCheckin) {
11317             mCurBroadcastStats = null;
11318         }
11319     }
11320 
dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11321     void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args,
11322             int opti, boolean dumpAll, String dumpPackage) {
11323 
11324         pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)");
11325 
11326         mUgmInternal.dump(pw, dumpAll, dumpPackage);
11327     }
11328 
dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)11329     private static int dumpProcessList(PrintWriter pw,
11330             ActivityManagerService service, List list,
11331             String prefix, String normalLabel, String persistentLabel,
11332             String dumpPackage) {
11333         int numPers = 0;
11334         for (int i = list.size() - 1; i >= 0; i--) {
11335             ProcessRecord r = (ProcessRecord) list.get(i);
11336             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11337                 continue;
11338             }
11339             pw.println(String.format("%s%s #%2d: %s",
11340                     prefix, (r.isPersistent() ? persistentLabel : normalLabel),
11341                     i, r.toString()));
11342             if (r.isPersistent()) {
11343                 numPers++;
11344             }
11345         }
11346         return numPers;
11347     }
11348 
collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)11349     ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs,
11350             String[] args) {
11351         synchronized (mProcLock) {
11352             return mProcessList.collectProcessesLOSP(start, allPkgs, args);
11353         }
11354     }
11355 
dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)11356     final void dumpGraphicsHardwareUsage(FileDescriptor fd,
11357             PrintWriter pw, String[] args) {
11358         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11359         if (procs == null) {
11360             pw.println("No process found for: " + args[0]);
11361             return;
11362         }
11363 
11364         long uptime = SystemClock.uptimeMillis();
11365         long realtime = SystemClock.elapsedRealtime();
11366         pw.println("Applications Graphics Acceleration Info:");
11367         pw.println("Uptime: " + uptime + " Realtime: " + realtime);
11368 
11369         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
11370             ProcessRecord r = procs.get(i);
11371             final int pid = r.getPid();
11372             final IApplicationThread thread = r.getThread();
11373             if (thread != null) {
11374                 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **");
11375                 pw.flush();
11376                 try {
11377                     TransferPipe tp = new TransferPipe();
11378                     try {
11379                         thread.dumpGfxInfo(tp.getWriteFd(), args);
11380                         tp.go(fd);
11381                     } finally {
11382                         tp.kill();
11383                     }
11384                 } catch (IOException e) {
11385                     pw.println("Failure while dumping the app: " + r);
11386                     pw.flush();
11387                 } catch (RemoteException e) {
11388                     pw.println("Got a RemoteException while dumping the app " + r);
11389                     pw.flush();
11390                 }
11391             }
11392         }
11393     }
11394 
dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)11395     final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) {
11396         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11397         if (procs == null) {
11398             pw.println("No process found for: " + args[0]);
11399             return;
11400         }
11401 
11402         pw.println("Per-process Binder Cache Contents");
11403 
11404         for (int i = procs.size() - 1; i >= 0; i--) {
11405             ProcessRecord r = procs.get(i);
11406             final int pid = r.getPid();
11407             final IApplicationThread thread = r.getThread();
11408             if (thread != null) {
11409                 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **");
11410                 pw.flush();
11411                 try {
11412                     TransferPipe tp = new TransferPipe();
11413                     try {
11414                         thread.dumpCacheInfo(tp.getWriteFd(), args);
11415                         tp.go(fd);
11416                     } finally {
11417                         tp.kill();
11418                     }
11419                 } catch (IOException e) {
11420                     pw.println("Failure while dumping the app " + r);
11421                     pw.flush();
11422                 } catch (RemoteException e) {
11423                     pw.println("Got a RemoteException while dumping the app " + r);
11424                     pw.flush();
11425                 }
11426             }
11427         }
11428     }
11429 
dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)11430     final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
11431         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11432         if (procs == null) {
11433             pw.println("No process found for: " + args[0]);
11434             return;
11435         }
11436 
11437         pw.println("Applications Database Info:");
11438 
11439         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
11440             ProcessRecord r = procs.get(i);
11441             final int pid = r.getPid();
11442             final IApplicationThread thread = r.getThread();
11443             if (thread != null) {
11444                 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **");
11445                 pw.flush();
11446                 try {
11447                     TransferPipe tp = new TransferPipe();
11448                     try {
11449                         thread.dumpDbInfo(tp.getWriteFd(), args);
11450                         tp.go(fd);
11451                     } finally {
11452                         tp.kill();
11453                     }
11454                 } catch (IOException e) {
11455                     pw.println("Failure while dumping the app: " + r);
11456                     pw.flush();
11457                 } catch (RemoteException e) {
11458                     pw.println("Got a RemoteException while dumping the app " + r);
11459                     pw.flush();
11460                 }
11461             }
11462         }
11463     }
11464 
11465     final static class MemItem {
11466         final boolean isProc;
11467         final String label;
11468         final String shortLabel;
11469         final long pss;
11470         final long swapPss;
11471         final long mRss;
11472         final int id; // pid
11473         final int userId;
11474         final boolean hasActivities;
11475         ArrayList<MemItem> subitems;
11476 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, @UserIdInt int userId, boolean hasActivities)11477         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id,
11478                 @UserIdInt int userId,
11479                 boolean hasActivities) {
11480             this.isProc = true;
11481             this.label = label;
11482             this.shortLabel = shortLabel;
11483             this.pss = pss;
11484             this.swapPss = swapPss;
11485             this.mRss = rss;
11486             this.id = id;
11487             this.userId = userId;
11488             this.hasActivities = hasActivities;
11489         }
11490 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id)11491         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id) {
11492             this.isProc = false;
11493             this.label = label;
11494             this.shortLabel = shortLabel;
11495             this.pss = pss;
11496             this.swapPss = swapPss;
11497             this.mRss = rss;
11498             this.id = id;
11499             this.userId = UserHandle.USER_SYSTEM;
11500             this.hasActivities = false;
11501         }
11502     }
11503 
sortMemItems(List<MemItem> items, final boolean pss)11504     private static void sortMemItems(List<MemItem> items, final boolean pss) {
11505         Collections.sort(items, new Comparator<MemItem>() {
11506             @Override
11507             public int compare(MemItem lhs, MemItem rhs) {
11508                 long lss = pss ? lhs.pss : lhs.mRss;
11509                 long rss = pss ? rhs.pss : rhs.mRss;
11510                 if (lss < rss) {
11511                     return 1;
11512                 } else if (lss > rss) {
11513                     return -1;
11514                 }
11515                 return 0;
11516             }
11517         });
11518     }
11519 
dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss)11520     static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
11521             ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss,
11522             boolean dumpSwapPss) {
11523         if (sort && !isCompact) {
11524             sortMemItems(items, dumpPss);
11525         }
11526 
11527         for (int i=0; i<items.size(); i++) {
11528             MemItem mi = items.get(i);
11529             if (!isCompact) {
11530                 if (dumpPss && dumpSwapPss) {
11531                     pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss),
11532                             mi.label, stringifyKBSize(mi.swapPss));
11533                 } else {
11534                     pw.printf("%s%s: %s%s\n", prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss),
11535                             mi.label,
11536                             mi.userId != UserHandle.USER_SYSTEM ? " (user " + mi.userId + ")" : "");
11537                 }
11538             } else if (mi.isProc) {
11539                 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
11540                 pw.print(","); pw.print(mi.id); pw.print(",");
11541                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
11542                 pw.print(dumpSwapPss ? mi.swapPss : "N/A");
11543                 pw.println(mi.hasActivities ? ",a" : ",e");
11544             } else {
11545                 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
11546                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
11547                 pw.println(dumpSwapPss ? mi.swapPss : "N/A");
11548             }
11549             if (mi.subitems != null) {
11550                 dumpMemItems(pw, prefix + "    ", mi.shortLabel, mi.subitems,
11551                         true, isCompact, dumpPss, dumpSwapPss);
11552             }
11553         }
11554     }
11555 
dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)11556     static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag,
11557             ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) {
11558         if (sort) {
11559             sortMemItems(items, dumpPss);
11560         }
11561 
11562         for (int i=0; i<items.size(); i++) {
11563             MemItem mi = items.get(i);
11564             final long token = proto.start(fieldId);
11565 
11566             proto.write(MemInfoDumpProto.MemItem.TAG, tag);
11567             proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel);
11568             proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc);
11569             proto.write(MemInfoDumpProto.MemItem.ID, mi.id);
11570             proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities);
11571             proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss);
11572             proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss);
11573             if (dumpSwapPss) {
11574                 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss);
11575             }
11576             if (mi.subitems != null) {
11577                 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems,
11578                         true, dumpPss, dumpSwapPss);
11579             }
11580             proto.end(token);
11581         }
11582     }
11583 
11584     // These are in KB.
11585     static final long[] DUMP_MEM_BUCKETS = new long[] {
11586         5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
11587         120*1024, 160*1024, 200*1024,
11588         250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
11589         1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
11590     };
11591 
appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)11592     static final void appendMemBucket(StringBuilder out, long memKB, String label,
11593             boolean stackLike) {
11594         int start = label.lastIndexOf('.');
11595         if (start >= 0) start++;
11596         else start = 0;
11597         int end = label.length();
11598         for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
11599             if (DUMP_MEM_BUCKETS[i] >= memKB) {
11600                 long bucket = DUMP_MEM_BUCKETS[i]/1024;
11601                 out.append(bucket);
11602                 out.append(stackLike ? "MB." : "MB ");
11603                 out.append(label, start, end);
11604                 return;
11605             }
11606         }
11607         out.append(memKB/1024);
11608         out.append(stackLike ? "MB." : "MB ");
11609         out.append(label, start, end);
11610     }
11611 
11612     static final int[] DUMP_MEM_OOM_ADJ = new int[] {
11613             ProcessList.NATIVE_ADJ,
11614             ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ,
11615             ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ,
11616             ProcessList.VISIBLE_APP_ADJ,
11617             ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ,
11618             ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ,
11619             ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
11620             ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
11621             ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ
11622     };
11623     static final String[] DUMP_MEM_OOM_LABEL = new String[] {
11624             "Native",
11625             "System", "Persistent", "Persistent Service", "Foreground",
11626             "Visible", "Perceptible", "Perceptible Low", "Perceptible Medium",
11627             "Backup", "Heavy Weight",
11628             "A Services", "Home",
11629             "Previous", "B Services", "Cached"
11630     };
11631     static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
11632             "native",
11633             "sys", "pers", "persvc", "fore",
11634             "vis", "percept", "perceptl", "perceptm",
11635             "backup", "heavy",
11636             "servicea", "home",
11637             "prev", "serviceb", "cached"
11638     };
11639 
dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)11640     private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
11641             long realtime, boolean isCheckinRequest, boolean isCompact) {
11642         if (isCompact) {
11643             pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION);
11644         }
11645         if (isCheckinRequest || isCompact) {
11646             // short checkin version
11647             pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
11648         } else {
11649             pw.println("Applications Memory Usage (in Kilobytes):");
11650             pw.println("Uptime: " + uptime + " Realtime: " + realtime);
11651         }
11652     }
11653 
11654     static final int KSM_SHARED = 0;
11655     static final int KSM_SHARING = 1;
11656     static final int KSM_UNSHARED = 2;
11657     static final int KSM_VOLATILE = 3;
11658 
getKsmInfo()11659     static final long[] getKsmInfo() {
11660         long[] longOut = new long[4];
11661         final int[] SINGLE_LONG_FORMAT = new int[] {
11662             PROC_SPACE_TERM| PROC_OUT_LONG
11663         };
11664         long[] longTmp = new long[1];
11665         readProcFile("/sys/kernel/mm/ksm/pages_shared",
11666                 SINGLE_LONG_FORMAT, null, longTmp, null);
11667         longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11668         longTmp[0] = 0;
11669         readProcFile("/sys/kernel/mm/ksm/pages_sharing",
11670                 SINGLE_LONG_FORMAT, null, longTmp, null);
11671         longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11672         longTmp[0] = 0;
11673         readProcFile("/sys/kernel/mm/ksm/pages_unshared",
11674                 SINGLE_LONG_FORMAT, null, longTmp, null);
11675         longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11676         longTmp[0] = 0;
11677         readProcFile("/sys/kernel/mm/ksm/pages_volatile",
11678                 SINGLE_LONG_FORMAT, null, longTmp, null);
11679         longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
11680         return longOut;
11681     }
11682 
stringifySize(long size, int order)11683     static String stringifySize(long size, int order) {
11684         Locale locale = Locale.US;
11685         switch (order) {
11686             case 1:
11687                 return String.format(locale, "%,13d", size);
11688             case 1024:
11689                 return String.format(locale, "%,9dK", size / 1024);
11690             case 1024 * 1024:
11691                 return String.format(locale, "%,5dM", size / 1024 / 1024);
11692             case 1024 * 1024 * 1024:
11693                 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024);
11694             default:
11695                 throw new IllegalArgumentException("Invalid size order");
11696         }
11697     }
11698 
stringifyKBSize(long size)11699     static String stringifyKBSize(long size) {
11700         return stringifySize(size * 1024, 1024);
11701     }
11702 
11703     // Update this version number if you change the 'compact' format.
11704     private static final int MEMINFO_COMPACT_VERSION = 1;
11705 
11706     private static class MemoryUsageDumpOptions {
11707         boolean dumpDetails;
11708         boolean dumpFullDetails;
11709         boolean dumpDalvik;
11710         boolean dumpSummaryOnly;
11711         boolean dumpUnreachable;
11712         boolean oomOnly;
11713         boolean isCompact;
11714         boolean localOnly;
11715         boolean packages;
11716         boolean isCheckinRequest;
11717         boolean dumpSwapPss;
11718         boolean dumpProto;
11719     }
11720 
11721     @NeverCompile // Avoid size overhead of debugging code.
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)11722     final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
11723             String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) {
11724         MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions();
11725         opts.dumpDetails = false;
11726         opts.dumpFullDetails = false;
11727         opts.dumpDalvik = false;
11728         opts.dumpSummaryOnly = false;
11729         opts.dumpUnreachable = false;
11730         opts.oomOnly = false;
11731         opts.isCompact = false;
11732         opts.localOnly = false;
11733         opts.packages = false;
11734         opts.isCheckinRequest = false;
11735         opts.dumpSwapPss = false;
11736         opts.dumpProto = asProto;
11737 
11738         int opti = 0;
11739         while (opti < args.length) {
11740             String opt = args[opti];
11741             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11742                 break;
11743             }
11744             opti++;
11745             if ("-a".equals(opt)) {
11746                 opts.dumpDetails = true;
11747                 opts.dumpFullDetails = true;
11748                 opts.dumpDalvik = true;
11749                 opts.dumpSwapPss = true;
11750             } else if ("-d".equals(opt)) {
11751                 opts.dumpDalvik = true;
11752             } else if ("-c".equals(opt)) {
11753                 opts.isCompact = true;
11754             } else if ("-s".equals(opt)) {
11755                 opts.dumpDetails = true;
11756                 opts.dumpSummaryOnly = true;
11757             } else if ("-S".equals(opt)) {
11758                 opts.dumpSwapPss = true;
11759             } else if ("--unreachable".equals(opt)) {
11760                 opts.dumpUnreachable = true;
11761             } else if ("--oom".equals(opt)) {
11762                 opts.oomOnly = true;
11763             } else if ("--local".equals(opt)) {
11764                 opts.localOnly = true;
11765             } else if ("--package".equals(opt)) {
11766                 opts.packages = true;
11767             } else if ("--checkin".equals(opt)) {
11768                 opts.isCheckinRequest = true;
11769             } else if ("--proto".equals(opt)) {
11770                 opts.dumpProto = true;
11771 
11772             } else if ("-h".equals(opt)) {
11773                 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
11774                 pw.println("  -a: include all available information for each process.");
11775                 pw.println("  -d: include dalvik details.");
11776                 pw.println("  -c: dump in a compact machine-parseable representation.");
11777                 pw.println("  -s: dump only summary of application memory usage.");
11778                 pw.println("  -S: dump also SwapPss.");
11779                 pw.println("  --oom: only show processes organized by oom adj.");
11780                 pw.println("  --local: only collect details locally, don't call process.");
11781                 pw.println("  --package: interpret process arg as package, dumping all");
11782                 pw.println("             processes that have loaded that package.");
11783                 pw.println("  --checkin: dump data for a checkin");
11784                 pw.println("  --proto: dump data to proto");
11785                 pw.println("If [process] is specified it can be the name or ");
11786                 pw.println("pid of a specific process to dump.");
11787                 return;
11788             } else {
11789                 pw.println("Unknown argument: " + opt + "; use -h for help");
11790             }
11791         }
11792 
11793         String[] innerArgs = new String[args.length-opti];
11794         System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
11795 
11796         ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args);
11797         if (opts.dumpProto) {
11798             dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs);
11799         } else {
11800             dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw);
11801         }
11802     }
11803 
11804     @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)11805     private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
11806             MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief,
11807             ArrayList<ProcessRecord> procs, PrintWriter categoryPw) {
11808         long uptime = SystemClock.uptimeMillis();
11809         long realtime = SystemClock.elapsedRealtime();
11810         final long[] tmpLong = new long[3];
11811 
11812         if (procs == null) {
11813             // No Java processes.  Maybe they want to print a native process.
11814             String proc = "N/A";
11815             if (innerArgs.length > 0) {
11816                 proc = innerArgs[0];
11817                 if (proc.charAt(0) != '-') {
11818                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
11819                             = new ArrayList<ProcessCpuTracker.Stats>();
11820                     updateCpuStatsNow();
11821                     int findPid = -1;
11822                     try {
11823                         findPid = Integer.parseInt(innerArgs[0]);
11824                     } catch (NumberFormatException e) {
11825                     }
11826                     final int fFindPid = findPid;
11827                     mAppProfiler.forAllCpuStats((st) -> {
11828                         if (st.pid == fFindPid || (st.baseName != null
11829                                 && st.baseName.equals(innerArgs[0]))) {
11830                             nativeProcs.add(st);
11831                         }
11832                     });
11833                     if (nativeProcs.size() > 0) {
11834                         dumpApplicationMemoryUsageHeader(pw, uptime, realtime,
11835                                 opts.isCheckinRequest, opts.isCompact);
11836                         Debug.MemoryInfo mi = null;
11837                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
11838                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
11839                             final int pid = r.pid;
11840                             if (mi == null) {
11841                                 mi = new Debug.MemoryInfo();
11842                             }
11843                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
11844                                 if (!Debug.getMemoryInfo(pid, mi)) {
11845                                     continue;
11846                                 }
11847                             } else {
11848                                 long pss = Debug.getPss(pid, tmpLong, null);
11849                                 if (pss == 0) {
11850                                     continue;
11851                                 }
11852                                 mi.nativePss = (int) pss;
11853                                 mi.nativePrivateDirty = (int) tmpLong[0];
11854                                 mi.nativeRss = (int) tmpLong[2];
11855                             }
11856                             if (!opts.isCheckinRequest && opts.dumpDetails) {
11857                                 pw.println("\n** MEMINFO in pid " + pid + " ["
11858                                         + r.baseName + "] **");
11859                             }
11860                             ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest,
11861                                     opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
11862                                     pid, r.baseName, 0, 0, 0, 0, 0, 0);
11863                             if (opts.isCheckinRequest) {
11864                                 pw.println();
11865                             }
11866                         }
11867                         return;
11868                     }
11869                 }
11870             }
11871             pw.println("No process found for: " + proc);
11872             return;
11873         }
11874 
11875         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
11876             opts.dumpDetails = true;
11877         }
11878         final int numProcs = procs.size();
11879         final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages;
11880         if (collectNative) {
11881             // If we are showing aggregations, also look for native processes to
11882             // include so that our aggregations are more accurate.
11883             updateCpuStatsNow();
11884         }
11885 
11886         dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact);
11887 
11888         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
11889         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
11890         final long[] ss = new long[INDEX_LAST];
11891         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11892                 EmptyArray.LONG;
11893         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11894                 EmptyArray.LONG;
11895         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11896                 EmptyArray.LONG;
11897         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11898         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11899         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11900         long[] memtrackTmp = new long[4];
11901 
11902         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
11903         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
11904         long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
11905         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
11906                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
11907 
11908         long totalSwapPss = 0;
11909         long totalRss = 0;
11910         long cachedPss = 0;
11911         long cachedSwapPss = 0;
11912         boolean hasSwapPss = false;
11913 
11914         Debug.MemoryInfo mi = null;
11915         for (int i = numProcs - 1; i >= 0; i--) {
11916             final ProcessRecord r = procs.get(i);
11917             final IApplicationThread thread;
11918             final int pid;
11919             final int oomAdj;
11920             final boolean hasActivities;
11921             synchronized (mProcLock) {
11922                 thread = r.getThread();
11923                 pid = r.getPid();
11924                 oomAdj = r.mState.getSetAdjWithServices();
11925                 hasActivities = r.hasActivities();
11926             }
11927             if (thread != null) {
11928                 if (mi == null) {
11929                     mi = new Debug.MemoryInfo();
11930                 }
11931                 final int reportType;
11932                 final long startTime;
11933                 final long endTime;
11934                 long memtrackGraphics = 0;
11935                 long memtrackGl = 0;
11936                 if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
11937                     reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
11938                     startTime = SystemClock.currentThreadTimeMillis();
11939                     if (!Debug.getMemoryInfo(pid, mi)) {
11940                         continue;
11941                     }
11942                     endTime = SystemClock.currentThreadTimeMillis();
11943                     hasSwapPss = mi.hasSwappedOutPss;
11944                     memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS);
11945                     memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL);
11946                 } else {
11947                     reportType = ProcessStats.ADD_PSS_EXTERNAL;
11948                     startTime = SystemClock.currentThreadTimeMillis();
11949                     long pss = Debug.getPss(pid, tmpLong, memtrackTmp);
11950                     if (pss == 0) {
11951                         continue;
11952                     }
11953                     mi.dalvikPss = (int) pss;
11954                     endTime = SystemClock.currentThreadTimeMillis();
11955                     mi.dalvikPrivateDirty = (int) tmpLong[0];
11956                     mi.dalvikRss = (int) tmpLong[2];
11957                     memtrackGraphics = memtrackTmp[1];
11958                     memtrackGl = memtrackTmp[2];
11959                 }
11960                 if (!opts.isCheckinRequest && opts.dumpDetails) {
11961                     pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
11962                 }
11963                 if (opts.dumpDetails) {
11964                     if (opts.localOnly) {
11965                         ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails,
11966                                 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
11967                         if (opts.isCheckinRequest) {
11968                             pw.println();
11969                         }
11970                     } else {
11971                         pw.flush();
11972                         try {
11973                             TransferPipe tp = new TransferPipe();
11974                             try {
11975                                 thread.dumpMemInfo(tp.getWriteFd(),
11976                                         mi, opts.isCheckinRequest, opts.dumpFullDetails,
11977                                         opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs);
11978                                 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000);
11979                             } finally {
11980                                 tp.kill();
11981                             }
11982                         } catch (IOException e) {
11983                             if (!opts.isCheckinRequest) {
11984                                 pw.println("Got IoException! " + e);
11985                                 pw.flush();
11986                             }
11987                         } catch (RemoteException e) {
11988                             if (!opts.isCheckinRequest) {
11989                                 pw.println("Got RemoteException! " + e);
11990                                 pw.flush();
11991                             }
11992                         }
11993                     }
11994                 }
11995 
11996                 final long myTotalPss = mi.getTotalPss();
11997                 final long myTotalUss = mi.getTotalUss();
11998                 final long myTotalRss = mi.getTotalRss();
11999                 final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12000 
12001                 synchronized (mProcLock) {
12002                     if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) {
12003                         // Record this for posterity if the process has been stable.
12004                         r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
12005                                 reportType, endTime - startTime);
12006                         r.getPkgList().forEachPackageProcessStats(holder -> {
12007                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
12008                                     r.info.uid,
12009                                     holder.state.getName(),
12010                                     holder.state.getPackage(),
12011                                     myTotalPss, myTotalUss, myTotalRss, reportType,
12012                                     endTime-startTime,
12013                                     holder.appVersion,
12014                                     r.mProfile.getCurrentHostingComponentTypes(),
12015                                     r.mProfile.getHistoricalHostingComponentTypes());
12016                         });
12017                     }
12018                 }
12019 
12020                 if (!opts.isCheckinRequest && mi != null) {
12021                     ss[INDEX_TOTAL_PSS] += myTotalPss;
12022                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12023                     ss[INDEX_TOTAL_RSS] += myTotalRss;
12024                     ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics;
12025                     ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl;
12026                     MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
12027                             (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
12028                             myTotalSwapPss, myTotalRss, pid, r.userId, hasActivities);
12029                     procMems.add(pssItem);
12030                     procMemsMap.put(pid, pssItem);
12031 
12032                     ss[INDEX_NATIVE_PSS] += mi.nativePss;
12033                     ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss;
12034                     ss[INDEX_NATIVE_RSS] += mi.nativeRss;
12035                     ss[INDEX_DALVIK_PSS] += mi.dalvikPss;
12036                     ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss;
12037                     ss[INDEX_DALVIK_RSS] += mi.dalvikRss;
12038                     for (int j=0; j<dalvikSubitemPss.length; j++) {
12039                         dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12040                         dalvikSubitemSwapPss[j] +=
12041                                 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12042                         dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12043                     }
12044                     ss[INDEX_OTHER_PSS] += mi.otherPss;
12045                     ss[INDEX_OTHER_RSS] += mi.otherRss;
12046                     ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss;
12047                     for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12048                         long mem = mi.getOtherPss(j);
12049                         miscPss[j] += mem;
12050                         ss[INDEX_OTHER_PSS] -= mem;
12051                         mem = mi.getOtherSwappedOutPss(j);
12052                         miscSwapPss[j] += mem;
12053                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
12054                         mem = mi.getOtherRss(j);
12055                         miscRss[j] += mem;
12056                         ss[INDEX_OTHER_RSS] -= mem;
12057                     }
12058 
12059                     if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
12060                         cachedPss += myTotalPss;
12061                         cachedSwapPss += myTotalSwapPss;
12062                     }
12063 
12064                     for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
12065                         if (oomIndex == (oomPss.length - 1)
12066                                 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
12067                                         && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
12068                             oomPss[oomIndex] += myTotalPss;
12069                             oomSwapPss[oomIndex] += myTotalSwapPss;
12070                             if (oomProcs[oomIndex] == null) {
12071                                 oomProcs[oomIndex] = new ArrayList<MemItem>();
12072                             }
12073                             oomProcs[oomIndex].add(pssItem);
12074                             oomRss[oomIndex] += myTotalRss;
12075                             break;
12076                         }
12077                     }
12078                 }
12079             }
12080         }
12081 
12082         long nativeProcTotalPss = 0;
12083 
12084         if (collectNative) {
12085             mi = null;
12086             final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1];
12087             mAppProfiler.forAllCpuStats((st) -> {
12088                 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
12089                     long memtrackGraphics = 0;
12090                     long memtrackGl = 0;
12091                     if (memInfos[0] == null) {
12092                         memInfos[0] = new Debug.MemoryInfo();
12093                     }
12094                     final Debug.MemoryInfo info = memInfos[0];
12095                     if (!brief && !opts.oomOnly) {
12096                         if (!Debug.getMemoryInfo(st.pid, info)) {
12097                             return;
12098                         }
12099                         memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS);
12100                         memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL);
12101                     } else {
12102                         long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp);
12103                         if (pss == 0) {
12104                             return;
12105                         }
12106                         info.nativePss = (int) pss;
12107                         info.nativePrivateDirty = (int) tmpLong[0];
12108                         info.nativeRss = (int) tmpLong[2];
12109                         memtrackGraphics = memtrackTmp[1];
12110                         memtrackGl = memtrackTmp[2];
12111                     }
12112 
12113                     final long myTotalPss = info.getTotalPss();
12114                     final long myTotalSwapPss = info.getTotalSwappedOutPss();
12115                     final long myTotalRss = info.getTotalRss();
12116                     ss[INDEX_TOTAL_PSS] += myTotalPss;
12117                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12118                     ss[INDEX_TOTAL_RSS] += myTotalRss;
12119                     ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss;
12120                     ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics;
12121                     ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl;
12122 
12123                     MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
12124                             st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss,
12125                             st.pid, UserHandle.getUserId(st.uid), false);
12126                     procMems.add(pssItem);
12127 
12128                     ss[INDEX_NATIVE_PSS] += info.nativePss;
12129                     ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss;
12130                     ss[INDEX_NATIVE_RSS] += info.nativeRss;
12131                     ss[INDEX_DALVIK_PSS] += info.dalvikPss;
12132                     ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss;
12133                     ss[INDEX_DALVIK_RSS] += info.dalvikRss;
12134                     for (int j = 0; j < dalvikSubitemPss.length; j++) {
12135                         dalvikSubitemPss[j] += info.getOtherPss(
12136                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12137                         dalvikSubitemSwapPss[j] +=
12138                                 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12139                         dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
12140                                 + j);
12141                     }
12142                     ss[INDEX_OTHER_PSS] += info.otherPss;
12143                     ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss;
12144                     ss[INDEX_OTHER_RSS] += info.otherRss;
12145                     for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12146                         long mem = info.getOtherPss(j);
12147                         miscPss[j] += mem;
12148                         ss[INDEX_OTHER_PSS] -= mem;
12149                         mem = info.getOtherSwappedOutPss(j);
12150                         miscSwapPss[j] += mem;
12151                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
12152                         mem = info.getOtherRss(j);
12153                         miscRss[j] += mem;
12154                         ss[INDEX_OTHER_RSS] -= mem;
12155                     }
12156                     oomPss[0] += myTotalPss;
12157                     oomSwapPss[0] += myTotalSwapPss;
12158                     if (oomProcs[0] == null) {
12159                         oomProcs[0] = new ArrayList<MemItem>();
12160                     }
12161                     oomProcs[0].add(pssItem);
12162                     oomRss[0] += myTotalRss;
12163                 }
12164             });
12165 
12166             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
12167 
12168             catMems.add(new MemItem("Native", "Native",
12169                     ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1));
12170             final int dalvikId = -2;
12171             catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS],
12172                     ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId));
12173             catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS],
12174                     ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3));
12175             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12176                 String label = Debug.MemoryInfo.getOtherLabel(j);
12177                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j],  j));
12178             }
12179             if (dalvikSubitemPss.length > 0) {
12180                 // Add dalvik subitems.
12181                 for (MemItem memItem : catMems) {
12182                     int memItemStart = 0, memItemEnd = 0;
12183                     if (memItem.id == dalvikId) {
12184                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
12185                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
12186                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
12187                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
12188                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
12189                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
12190                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
12191                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
12192                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
12193                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
12194                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
12195                     } else {
12196                         continue;  // No subitems, continue.
12197                     }
12198                     memItem.subitems = new ArrayList<MemItem>();
12199                     for (int j=memItemStart; j<=memItemEnd; j++) {
12200                         final String name = Debug.MemoryInfo.getOtherLabel(
12201                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12202                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
12203                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
12204                     }
12205                 }
12206             }
12207 
12208             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
12209             for (int j=0; j<oomPss.length; j++) {
12210                 if (oomPss[j] != 0) {
12211                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
12212                             : DUMP_MEM_OOM_LABEL[j];
12213                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
12214                             DUMP_MEM_OOM_ADJ[j]);
12215                     item.subitems = oomProcs[j];
12216                     oomMems.add(item);
12217                 }
12218             }
12219             if (!opts.isCompact) {
12220                 pw.println();
12221             }
12222             if (!brief && !opts.oomOnly && !opts.isCompact) {
12223                 pw.println();
12224                 pw.println("Total RSS by process:");
12225                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, false, false);
12226                 pw.println();
12227             }
12228             if (!opts.isCompact) {
12229                 pw.println("Total RSS by OOM adjustment:");
12230             }
12231             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, false, false);
12232             if (!brief && !opts.oomOnly) {
12233                 PrintWriter out = categoryPw != null ? categoryPw : pw;
12234                 if (!opts.isCompact) {
12235                     out.println();
12236                     out.println("Total RSS by category:");
12237                 }
12238                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, false, false);
12239             }
12240             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0;
12241             if (!brief && !opts.oomOnly && !opts.isCompact) {
12242                 pw.println();
12243                 pw.println("Total PSS by process:");
12244                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, true,
12245                         opts.dumpSwapPss);
12246                 pw.println();
12247             }
12248             if (!opts.isCompact) {
12249                 pw.println("Total PSS by OOM adjustment:");
12250             }
12251             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss);
12252             if (!brief && !opts.oomOnly) {
12253                 PrintWriter out = categoryPw != null ? categoryPw : pw;
12254                 if (!opts.isCompact) {
12255                     out.println();
12256                     out.println("Total PSS by category:");
12257                 }
12258                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, true,
12259                         opts.dumpSwapPss);
12260             }
12261             if (!opts.isCompact) {
12262                 pw.println();
12263             }
12264             MemInfoReader memInfo = new MemInfoReader();
12265             memInfo.readMemInfo();
12266             if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) {
12267                 synchronized (mProcessStats.mLock) {
12268                     final long cachedKb = memInfo.getCachedSizeKb();
12269                     final long freeKb = memInfo.getFreeSizeKb();
12270                     final long zramKb = memInfo.getZramTotalSizeKb();
12271                     final long kernelKb = memInfo.getKernelUsedSizeKb();
12272                     EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
12273                             kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024);
12274                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
12275                             ss[INDEX_TOTAL_NATIVE_PSS]);
12276                 }
12277             }
12278             if (!brief) {
12279                 if (!opts.isCompact) {
12280                     pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
12281                     pw.print(" (status ");
12282                     mAppProfiler.dumpLastMemoryLevelLocked(pw);
12283                     pw.print(" Free RAM: ");
12284                     pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
12285                             + memInfo.getFreeSizeKb()));
12286                     pw.print(" (");
12287                     pw.print(stringifyKBSize(cachedPss));
12288                     pw.print(" cached pss + ");
12289                     pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
12290                     pw.print(" cached kernel + ");
12291                     pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
12292                     pw.println(" free)");
12293                 } else {
12294                     pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
12295                     pw.print(cachedPss + memInfo.getCachedSizeKb()
12296                             + memInfo.getFreeSizeKb()); pw.print(",");
12297                     pw.println(ss[INDEX_TOTAL_PSS] - cachedPss);
12298                 }
12299             }
12300             long kernelUsed = memInfo.getKernelUsedSizeKb();
12301             final long ionHeap = Debug.getIonHeapsSizeKb();
12302             final long ionPool = Debug.getIonPoolsSizeKb();
12303             final long dmabufMapped = Debug.getDmabufMappedSizeKb();
12304             if (ionHeap >= 0 && ionPool >= 0) {
12305                 final long ionUnmapped = ionHeap - dmabufMapped;
12306                 pw.print("      ION: ");
12307                         pw.print(stringifyKBSize(ionHeap + ionPool));
12308                         pw.print(" (");
12309                         pw.print(stringifyKBSize(dmabufMapped));
12310                         pw.print(" mapped + ");
12311                         pw.print(stringifyKBSize(ionUnmapped));
12312                         pw.print(" unmapped + ");
12313                         pw.print(stringifyKBSize(ionPool));
12314                         pw.println(" pools)");
12315                 kernelUsed += ionUnmapped;
12316                 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
12317                 // set on ION VMAs, however it might be included by the memtrack HAL.
12318                 // Replace memtrack HAL reported Graphics category with mapped dmabufs
12319                 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS];
12320                 ss[INDEX_TOTAL_PSS] += dmabufMapped;
12321             } else {
12322                 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb();
12323                 if (totalExportedDmabuf >= 0) {
12324                     final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped;
12325                     pw.print("DMA-BUF: ");
12326                     pw.print(stringifyKBSize(totalExportedDmabuf));
12327                     pw.print(" (");
12328                     pw.print(stringifyKBSize(dmabufMapped));
12329                     pw.print(" mapped + ");
12330                     pw.print(stringifyKBSize(dmabufUnmapped));
12331                     pw.println(" unmapped)");
12332                     // Account unmapped dmabufs as part of kernel memory allocations
12333                     kernelUsed += dmabufUnmapped;
12334                     // Replace memtrack HAL reported Graphics category with mapped dmabufs
12335                     ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS];
12336                     ss[INDEX_TOTAL_PSS] += dmabufMapped;
12337                 }
12338 
12339                 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not
12340                 // need to be added to kernelUsed.
12341                 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb();
12342                 if (totalDmabufHeapExported >= 0) {
12343                     pw.print("DMA-BUF Heaps: ");
12344                     pw.println(stringifyKBSize(totalDmabufHeapExported));
12345                 }
12346 
12347                 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb();
12348                 if (totalDmabufHeapPool >= 0) {
12349                     pw.print("DMA-BUF Heaps pool: ");
12350                     pw.println(stringifyKBSize(totalDmabufHeapPool));
12351                 }
12352             }
12353             final long gpuUsage = Debug.getGpuTotalUsageKb();
12354             if (gpuUsage >= 0) {
12355                 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb();
12356                 if (gpuPrivateUsage >= 0) {
12357                     final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage;
12358                     pw.print("      GPU: ");
12359                     pw.print(stringifyKBSize(gpuUsage));
12360                     pw.print(" (");
12361                     pw.print(stringifyKBSize(gpuDmaBufUsage));
12362                     pw.print(" dmabuf + ");
12363                     pw.print(stringifyKBSize(gpuPrivateUsage));
12364                     pw.println(" private)");
12365                     // Replace memtrack HAL reported GL category with private GPU allocations and
12366                     // account it as part of kernel memory allocations
12367                     ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL];
12368                     kernelUsed += gpuPrivateUsage;
12369                 } else {
12370                     pw.print("      GPU: "); pw.println(stringifyKBSize(gpuUsage));
12371                 }
12372             }
12373 
12374              // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of
12375              // memInfo.getCachedSizeKb().
12376             final long lostRAM = memInfo.getTotalSizeKb()
12377                     - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS])
12378                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
12379                     - kernelUsed - memInfo.getZramTotalSizeKb();
12380             if (!opts.isCompact) {
12381                 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss
12382                         + kernelUsed)); pw.print(" (");
12383                 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); pw.print(" used pss + ");
12384                 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n");
12385                 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM));
12386             } else {
12387                 pw.print("lostram,"); pw.println(lostRAM);
12388             }
12389             if (!brief) {
12390                 if (memInfo.getZramTotalSizeKb() != 0) {
12391                     if (!opts.isCompact) {
12392                         pw.print("     ZRAM: ");
12393                         pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
12394                                 pw.print(" physical used for ");
12395                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()
12396                                         - memInfo.getSwapFreeSizeKb()));
12397                                 pw.print(" in swap (");
12398                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
12399                                 pw.println(" total swap)");
12400                     } else {
12401                         pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
12402                                 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
12403                                 pw.println(memInfo.getSwapFreeSizeKb());
12404                     }
12405                 }
12406                 final long[] ksm = getKsmInfo();
12407                 if (!opts.isCompact) {
12408                     if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
12409                             || ksm[KSM_VOLATILE] != 0) {
12410                         pw.print("      KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING]));
12411                                 pw.print(" saved from shared ");
12412                                 pw.print(stringifyKBSize(ksm[KSM_SHARED]));
12413                         pw.print("           "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
12414                                 pw.print(" unshared; ");
12415                                 pw.print(stringifyKBSize(
12416                                              ksm[KSM_VOLATILE])); pw.println(" volatile");
12417                     }
12418                     pw.print("   Tuning: ");
12419                     pw.print(ActivityManager.staticGetMemoryClass());
12420                     pw.print(" (large ");
12421                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12422                     pw.print("), oom ");
12423                     pw.print(stringifySize(
12424                                 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
12425                     pw.print(", restore limit ");
12426                     pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
12427                     if (ActivityManager.isLowRamDeviceStatic()) {
12428                         pw.print(" (low-ram)");
12429                     }
12430                     if (ActivityManager.isHighEndGfx()) {
12431                         pw.print(" (high-end-gfx)");
12432                     }
12433                     pw.println();
12434                 } else {
12435                     pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(",");
12436                     pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]);
12437                     pw.print(","); pw.println(ksm[KSM_VOLATILE]);
12438                     pw.print("tuning,");
12439                     pw.print(ActivityManager.staticGetMemoryClass());
12440                     pw.print(',');
12441                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12442                     pw.print(',');
12443                     pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
12444                     if (ActivityManager.isLowRamDeviceStatic()) {
12445                         pw.print(",low-ram");
12446                     }
12447                     if (ActivityManager.isHighEndGfx()) {
12448                         pw.print(",high-end-gfx");
12449                     }
12450                     pw.println();
12451                 }
12452             }
12453         }
12454     }
12455 
12456     @NeverCompile // Avoid size overhead of debugging code.
dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)12457     private final void dumpApplicationMemoryUsage(FileDescriptor fd,
12458             MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief,
12459             ArrayList<ProcessRecord> procs) {
12460         final long uptimeMs = SystemClock.uptimeMillis();
12461         final long realtimeMs = SystemClock.elapsedRealtime();
12462         final long[] tmpLong = new long[3];
12463 
12464         if (procs == null) {
12465             // No Java processes.  Maybe they want to print a native process.
12466             String proc = "N/A";
12467             if (innerArgs.length > 0) {
12468                 proc = innerArgs[0];
12469                 if (proc.charAt(0) != '-') {
12470                     final ArrayList<ProcessCpuTracker.Stats> nativeProcs
12471                             = new ArrayList<ProcessCpuTracker.Stats>();
12472                     updateCpuStatsNow();
12473                     int findPid = -1;
12474                     try {
12475                         findPid = Integer.parseInt(innerArgs[0]);
12476                     } catch (NumberFormatException e) {
12477                     }
12478                     final int fFindPid = findPid;
12479                     mAppProfiler.forAllCpuStats((st) -> {
12480                         if (st.pid == fFindPid || (st.baseName != null
12481                                 && st.baseName.equals(innerArgs[0]))) {
12482                             nativeProcs.add(st);
12483                         }
12484                     });
12485                     if (nativeProcs.size() > 0) {
12486                         ProtoOutputStream proto = new ProtoOutputStream(fd);
12487 
12488                         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12489                         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12490                         Debug.MemoryInfo mi = null;
12491                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12492                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12493                             final int pid = r.pid;
12494 
12495                             if (mi == null) {
12496                                 mi = new Debug.MemoryInfo();
12497                             }
12498                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12499                                 if (!Debug.getMemoryInfo(pid, mi)) {
12500                                     continue;
12501                                 }
12502                             } else {
12503                                 long pss = Debug.getPss(pid, tmpLong, null);
12504                                 if (pss == 0) {
12505                                     continue;
12506                                 }
12507                                 mi.nativePss = (int) pss;
12508                                 mi.nativePrivateDirty = (int) tmpLong[0];
12509                                 mi.nativeRss = (int) tmpLong[2];
12510                             }
12511 
12512                             final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES);
12513 
12514                             proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
12515                             proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName);
12516 
12517                             ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
12518                                     opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
12519 
12520                             proto.end(nToken);
12521                         }
12522 
12523                         proto.flush();
12524                         return;
12525                     }
12526                 }
12527             }
12528             Log.d(TAG, "No process found for: " + innerArgs[0]);
12529             return;
12530         }
12531 
12532         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
12533             opts.dumpDetails = true;
12534         }
12535         final int numProcs = procs.size();
12536         final boolean collectNative = numProcs > 1 && !opts.packages;
12537         if (collectNative) {
12538             // If we are showing aggregations, also look for native processes to
12539             // include so that our aggregations are more accurate.
12540             updateCpuStatsNow();
12541         }
12542 
12543         ProtoOutputStream proto = new ProtoOutputStream(fd);
12544 
12545         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12546         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12547 
12548         final ArrayList<MemItem> procMems = new ArrayList<MemItem>();
12549         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
12550         final long[] ss = new long[INDEX_LAST];
12551         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12552                 EmptyArray.LONG;
12553         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12554                 EmptyArray.LONG;
12555         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12556                 EmptyArray.LONG;
12557         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12558         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12559         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12560 
12561         final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length];
12562         final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length];
12563         final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
12564         final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
12565                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
12566 
12567         long cachedPss = 0;
12568         long cachedSwapPss = 0;
12569         boolean hasSwapPss = false;
12570 
12571         Debug.MemoryInfo mi = null;
12572         for (int i = numProcs - 1; i >= 0; i--) {
12573             final ProcessRecord r = procs.get(i);
12574             final IApplicationThread thread;
12575             final int pid;
12576             final int oomAdj;
12577             final boolean hasActivities;
12578             synchronized (mProcLock) {
12579                 thread = r.getThread();
12580                 pid = r.getPid();
12581                 oomAdj = r.mState.getSetAdjWithServices();
12582                 hasActivities = r.hasActivities();
12583             }
12584             if (thread == null) {
12585                 continue;
12586             }
12587             if (mi == null) {
12588                 mi = new Debug.MemoryInfo();
12589             }
12590             final int reportType;
12591             final long startTime;
12592             final long endTime;
12593             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12594                 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
12595                 startTime = SystemClock.currentThreadTimeMillis();
12596                 if (!Debug.getMemoryInfo(pid, mi)) {
12597                     continue;
12598                 }
12599                 endTime = SystemClock.currentThreadTimeMillis();
12600                 hasSwapPss = mi.hasSwappedOutPss;
12601             } else {
12602                 reportType = ProcessStats.ADD_PSS_EXTERNAL;
12603                 startTime = SystemClock.currentThreadTimeMillis();
12604                 long pss = Debug.getPss(pid, tmpLong, null);
12605                 if (pss == 0) {
12606                     continue;
12607                 }
12608                 mi.dalvikPss = (int) pss;
12609                 endTime = SystemClock.currentThreadTimeMillis();
12610                 mi.dalvikPrivateDirty = (int) tmpLong[0];
12611                 mi.dalvikRss = (int) tmpLong[2];
12612             }
12613             if (opts.dumpDetails) {
12614                 if (opts.localOnly) {
12615                     final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES);
12616                     final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
12617                     proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
12618                     proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName);
12619                     ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
12620                             opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
12621                     proto.end(mToken);
12622                     proto.end(aToken);
12623                 } else {
12624                     try {
12625                         ByteTransferPipe tp = new ByteTransferPipe();
12626                         try {
12627                             thread.dumpMemInfoProto(tp.getWriteFd(),
12628                                 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
12629                                 opts.dumpUnreachable, innerArgs);
12630                             proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get());
12631                         } finally {
12632                             tp.kill();
12633                         }
12634                     } catch (IOException e) {
12635                         Log.e(TAG, "Got IOException!", e);
12636                     } catch (RemoteException e) {
12637                         Log.e(TAG, "Got RemoteException!", e);
12638                     }
12639                 }
12640             }
12641 
12642             final long myTotalPss = mi.getTotalPss();
12643             final long myTotalUss = mi.getTotalUss();
12644             final long myTotalRss = mi.getTotalRss();
12645             final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12646 
12647             synchronized (mProcLock) {
12648                 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) {
12649                     // Record this for posterity if the process has been stable.
12650                     r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
12651                                 reportType, endTime - startTime);
12652                     r.getPkgList().forEachPackageProcessStats(holder -> {
12653                         FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
12654                                 r.info.uid,
12655                                 holder.state.getName(),
12656                                 holder.state.getPackage(),
12657                                 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
12658                                 holder.appVersion,
12659                                 r.mProfile.getCurrentHostingComponentTypes(),
12660                                 r.mProfile.getHistoricalHostingComponentTypes());
12661                     });
12662                 }
12663             }
12664 
12665             if (!opts.isCheckinRequest && mi != null) {
12666                 ss[INDEX_TOTAL_PSS] += myTotalPss;
12667                 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12668                 ss[INDEX_TOTAL_RSS] += myTotalRss;
12669                 MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
12670                         (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
12671                         myTotalSwapPss, myTotalRss, pid, r.userId, hasActivities);
12672                 procMems.add(pssItem);
12673                 procMemsMap.put(pid, pssItem);
12674 
12675                 ss[INDEX_NATIVE_PSS] += mi.nativePss;
12676                 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss;
12677                 ss[INDEX_NATIVE_RSS] += mi.nativeRss;
12678                 ss[INDEX_DALVIK_PSS] += mi.dalvikPss;
12679                 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss;
12680                 ss[INDEX_DALVIK_RSS] += mi.dalvikRss;
12681                 for (int j=0; j<dalvikSubitemPss.length; j++) {
12682                     dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12683                     dalvikSubitemSwapPss[j] +=
12684                             mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12685                     dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12686                 }
12687                 ss[INDEX_OTHER_PSS] += mi.otherPss;
12688                 ss[INDEX_OTHER_RSS] += mi.otherRss;
12689                 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss;
12690                 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12691                     long mem = mi.getOtherPss(j);
12692                     miscPss[j] += mem;
12693                     ss[INDEX_OTHER_PSS] -= mem;
12694                     mem = mi.getOtherSwappedOutPss(j);
12695                     miscSwapPss[j] += mem;
12696                     ss[INDEX_OTHER_SWAP_PSS] -= mem;
12697                     mem = mi.getOtherRss(j);
12698                     miscRss[j] += mem;
12699                     ss[INDEX_OTHER_RSS] -= mem;
12700                 }
12701 
12702                 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
12703                     cachedPss += myTotalPss;
12704                     cachedSwapPss += myTotalSwapPss;
12705                 }
12706 
12707                 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
12708                     if (oomIndex == (oomPss.length - 1)
12709                             || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
12710                                     && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
12711                         oomPss[oomIndex] += myTotalPss;
12712                         oomSwapPss[oomIndex] += myTotalSwapPss;
12713                         if (oomProcs[oomIndex] == null) {
12714                             oomProcs[oomIndex] = new ArrayList<MemItem>();
12715                         }
12716                         oomProcs[oomIndex].add(pssItem);
12717                         oomRss[oomIndex] += myTotalRss;
12718                         break;
12719                     }
12720                 }
12721             }
12722         }
12723 
12724         long nativeProcTotalPss = 0;
12725 
12726         if (collectNative) {
12727             mi = null;
12728             final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1];
12729             mAppProfiler.forAllCpuStats((st) -> {
12730                 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
12731                     if (memInfos[0] == null) {
12732                         memInfos[0] = new Debug.MemoryInfo();
12733                     }
12734                     final Debug.MemoryInfo info = memInfos[0];
12735                     if (!brief && !opts.oomOnly) {
12736                         if (!Debug.getMemoryInfo(st.pid, info)) {
12737                             return;
12738                         }
12739                     } else {
12740                         long pss = Debug.getPss(st.pid, tmpLong, null);
12741                         if (pss == 0) {
12742                             return;
12743                         }
12744                         info.nativePss = (int) pss;
12745                         info.nativePrivateDirty = (int) tmpLong[0];
12746                         info.nativeRss = (int) tmpLong[2];
12747                     }
12748 
12749                     final long myTotalPss = info.getTotalPss();
12750                     final long myTotalSwapPss = info.getTotalSwappedOutPss();
12751                     final long myTotalRss = info.getTotalRss();
12752                     ss[INDEX_TOTAL_PSS] += myTotalPss;
12753                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
12754                     ss[INDEX_TOTAL_RSS] += myTotalRss;
12755                     ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss;
12756 
12757                     MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
12758                             st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss,
12759                             st.pid, UserHandle.getUserId(st.uid), false);
12760                     procMems.add(pssItem);
12761 
12762                     ss[INDEX_NATIVE_PSS] += info.nativePss;
12763                     ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss;
12764                     ss[INDEX_NATIVE_RSS] += info.nativeRss;
12765                     ss[INDEX_DALVIK_PSS] += info.dalvikPss;
12766                     ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss;
12767                     ss[INDEX_DALVIK_RSS] += info.dalvikRss;
12768                     for (int j = 0; j < dalvikSubitemPss.length; j++) {
12769                         dalvikSubitemPss[j] += info.getOtherPss(
12770                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12771                         dalvikSubitemSwapPss[j] +=
12772                                 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12773                         dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
12774                                 + j);
12775                     }
12776                     ss[INDEX_OTHER_PSS] += info.otherPss;
12777                     ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss;
12778                     ss[INDEX_OTHER_RSS] += info.otherRss;
12779                     for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12780                         long mem = info.getOtherPss(j);
12781                         miscPss[j] += mem;
12782                         ss[INDEX_OTHER_PSS] -= mem;
12783                         mem = info.getOtherSwappedOutPss(j);
12784                         miscSwapPss[j] += mem;
12785                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
12786                         mem = info.getOtherRss(j);
12787                         miscRss[j] += mem;
12788                         ss[INDEX_OTHER_RSS] -= mem;
12789                     }
12790                     oomPss[0] += myTotalPss;
12791                     oomSwapPss[0] += myTotalSwapPss;
12792                     if (oomProcs[0] == null) {
12793                         oomProcs[0] = new ArrayList<MemItem>();
12794                     }
12795                     oomProcs[0].add(pssItem);
12796                     oomRss[0] += myTotalRss;
12797                 }
12798             });
12799 
12800             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
12801 
12802             catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS],
12803                     ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1));
12804             final int dalvikId = -2;
12805             catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS],
12806                     ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId));
12807             catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS],
12808                     ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3));
12809             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12810                 String label = Debug.MemoryInfo.getOtherLabel(j);
12811                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j));
12812             }
12813             if (dalvikSubitemPss.length > 0) {
12814                 // Add dalvik subitems.
12815                 for (MemItem memItem : catMems) {
12816                     int memItemStart = 0, memItemEnd = 0;
12817                     if (memItem.id == dalvikId) {
12818                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
12819                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
12820                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
12821                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
12822                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
12823                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
12824                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
12825                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
12826                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
12827                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
12828                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
12829                     } else {
12830                         continue;  // No subitems, continue.
12831                     }
12832                     memItem.subitems = new ArrayList<MemItem>();
12833                     for (int j=memItemStart; j<=memItemEnd; j++) {
12834                         final String name = Debug.MemoryInfo.getOtherLabel(
12835                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12836                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
12837                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
12838                     }
12839                 }
12840             }
12841 
12842             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
12843             for (int j=0; j<oomPss.length; j++) {
12844                 if (oomPss[j] != 0) {
12845                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
12846                             : DUMP_MEM_OOM_LABEL[j];
12847                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
12848                             DUMP_MEM_OOM_ADJ[j]);
12849                     item.subitems = oomProcs[j];
12850                     oomMems.add(item);
12851                 }
12852             }
12853 
12854             if (!opts.oomOnly) {
12855                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc",
12856                         procMems, true, false, false);
12857             }
12858             dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom",
12859                     oomMems, false, false, false);
12860             if (!brief && !opts.oomOnly) {
12861                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat",
12862                         catMems, true, false, false);
12863             }
12864 
12865             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0;
12866             if (!opts.oomOnly) {
12867                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc",
12868                         procMems, true, true, opts.dumpSwapPss);
12869             }
12870             dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom",
12871                     oomMems, false, true, opts.dumpSwapPss);
12872             if (!brief && !opts.oomOnly) {
12873                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat",
12874                         catMems, true, true, opts.dumpSwapPss);
12875             }
12876             MemInfoReader memInfo = new MemInfoReader();
12877             memInfo.readMemInfo();
12878             if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) {
12879                 synchronized (mProcessStats.mLock) {
12880                     final long cachedKb = memInfo.getCachedSizeKb();
12881                     final long freeKb = memInfo.getFreeSizeKb();
12882                     final long zramKb = memInfo.getZramTotalSizeKb();
12883                     final long kernelKb = memInfo.getKernelUsedSizeKb();
12884                     EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
12885                             kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024);
12886                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
12887                             ss[INDEX_TOTAL_NATIVE_PSS]);
12888                 }
12889             }
12890             if (!brief) {
12891                 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb());
12892                 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked());
12893                 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss);
12894                 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb());
12895                 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb());
12896             }
12897             long lostRAM = memInfo.getTotalSizeKb()
12898                     - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS])
12899                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
12900                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
12901             proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss);
12902             proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb());
12903             proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM);
12904             if (!brief) {
12905                 if (memInfo.getZramTotalSizeKb() != 0) {
12906                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb());
12907                     proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB,
12908                             memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb());
12909                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb());
12910                 }
12911                 final long[] ksm = getKsmInfo();
12912                 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]);
12913                 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]);
12914                 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]);
12915                 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]);
12916 
12917                 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass());
12918                 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass());
12919                 proto.write(MemInfoDumpProto.OOM_KB,
12920                         mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
12921                 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB,
12922                         mProcessList.getCachedRestoreThresholdKb());
12923 
12924                 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic());
12925                 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx());
12926             }
12927         }
12928 
12929         proto.flush();
12930     }
12931 
appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)12932     static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss,
12933             long memtrack, String name) {
12934         sb.append("  ");
12935         sb.append(ProcessList.makeOomAdjString(oomAdj, false));
12936         sb.append(' ');
12937         sb.append(ProcessList.makeProcStateString(procState));
12938         sb.append(' ');
12939         ProcessList.appendRamKb(sb, pss);
12940         sb.append(": ");
12941         sb.append(name);
12942         if (memtrack > 0) {
12943             sb.append(" (");
12944             sb.append(stringifyKBSize(memtrack));
12945             sb.append(" memtrack)");
12946         }
12947     }
12948 
appendMemInfo(StringBuilder sb, ProcessMemInfo mi)12949     static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) {
12950         appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name);
12951         sb.append(" (pid ");
12952         sb.append(mi.pid);
12953         sb.append(") ");
12954         sb.append(mi.adjType);
12955         sb.append('\n');
12956         if (mi.adjReason != null) {
12957             sb.append("                      ");
12958             sb.append(mi.adjReason);
12959             sb.append('\n');
12960         }
12961     }
12962 
12963     /**
12964      * Searches array of arguments for the specified string
12965      * @param args array of argument strings
12966      * @param value value to search for
12967      * @return true if the value is contained in the array
12968      */
scanArgs(String[] args, String value)12969     private static boolean scanArgs(String[] args, String value) {
12970         if (args != null) {
12971             for (String arg : args) {
12972                 if (value.equals(arg)) {
12973                     return true;
12974                 }
12975             }
12976         }
12977         return false;
12978     }
12979 
12980     /**
12981      * Filters out non-exported components in a given list of broadcast filters
12982      * @param intent the original intent
12983      * @param callingUid the calling UID
12984      * @param query the list of broadcast filters
12985      * @param platformCompat the instance of platform compat
12986      */
filterNonExportedComponents(Intent intent, int callingUid, int callingPid, List query, PlatformCompat platformCompat, String callerPackage, String resolvedType)12987     private void filterNonExportedComponents(Intent intent, int callingUid, int callingPid,
12988             List query, PlatformCompat platformCompat, String callerPackage, String resolvedType) {
12989         if (query == null
12990                 || intent.getPackage() != null
12991                 || intent.getComponent() != null
12992                 || ActivityManager.canAccessUnexportedComponents(callingUid)) {
12993             return;
12994         }
12995         IUnsafeIntentStrictModeCallback callback = mStrictModeCallbacks.get(callingPid);
12996         for (int i = query.size() - 1; i >= 0; i--) {
12997             String componentInfo;
12998             ResolveInfo resolveInfo;
12999             BroadcastFilter broadcastFilter;
13000             if (query.get(i) instanceof ResolveInfo) {
13001                 resolveInfo = (ResolveInfo) query.get(i);
13002                 if (resolveInfo.getComponentInfo().exported) {
13003                     continue;
13004                 }
13005                 componentInfo = resolveInfo.getComponentInfo()
13006                         .getComponentName().flattenToShortString();
13007             } else if (query.get(i) instanceof BroadcastFilter) {
13008                 broadcastFilter = (BroadcastFilter) query.get(i);
13009                 if (broadcastFilter.exported) {
13010                     continue;
13011                 }
13012                 componentInfo = broadcastFilter.packageName;
13013             } else {
13014                 continue;
13015             }
13016             if (callback != null) {
13017                 mHandler.post(() -> {
13018                     try {
13019                         callback.onImplicitIntentMatchedInternalComponent(intent.cloneFilter());
13020                     } catch (RemoteException e) {
13021                         mStrictModeCallbacks.remove(callingPid);
13022                     }
13023                 });
13024             }
13025             boolean hasToBeExportedToMatch = platformCompat.isChangeEnabledByUid(
13026                     ActivityManagerService.IMPLICIT_INTENTS_ONLY_MATCH_EXPORTED_COMPONENTS,
13027                     callingUid);
13028             ActivityManagerUtils.logUnsafeIntentEvent(
13029                     UNSAFE_INTENT_EVENT_REPORTED__EVENT_TYPE__INTERNAL_NON_EXPORTED_COMPONENT_MATCH,
13030                     callingUid, intent, resolvedType, hasToBeExportedToMatch);
13031             if (!hasToBeExportedToMatch) {
13032                 return;
13033             }
13034             query.remove(i);
13035         }
13036     }
13037 
13038     /**
13039      * Main code for cleaning up a process when it has gone away.  This is
13040      * called both as a result of the process dying, or directly when stopping
13041      * a process when running in single process mode.
13042      *
13043      * @return Returns true if the given process has been restarted, so the
13044      * app that was passed in must remain on the process lists.
13045      */
13046     @GuardedBy("this")
cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)13047     final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid,
13048             boolean restarting, boolean allowRestart, int index, boolean replacingPid,
13049             boolean fromBinderDied) {
13050         boolean restart;
13051         synchronized (mProcLock) {
13052             if (index >= 0) {
13053                 removeLruProcessLocked(app);
13054                 ProcessList.remove(pid);
13055             }
13056 
13057             // We don't want to unlinkDeathRecipient immediately, if it's not called from binder
13058             // and it's not isolated, as we'd need the signal to bookkeeping the dying process list.
13059             restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart,
13060                     fromBinderDied || app.isolated /* unlinkDeath */);
13061 
13062             // Cancel pending frozen task and clean up frozen record if there is any.
13063             mOomAdjuster.mCachedAppOptimizer.onCleanupApplicationRecordLocked(app);
13064         }
13065         mAppProfiler.onCleanupApplicationRecordLocked(app);
13066         for (BroadcastQueue queue : mBroadcastQueues) {
13067             queue.onApplicationCleanupLocked(app);
13068         }
13069         clearProcessForegroundLocked(app);
13070         mServices.killServicesLocked(app, allowRestart);
13071         mPhantomProcessList.onAppDied(pid);
13072 
13073         // If the app is undergoing backup, tell the backup manager about it
13074         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
13075         if (backupTarget != null && pid == backupTarget.app.getPid()) {
13076             if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App "
13077                     + backupTarget.appInfo + " died during backup");
13078             mHandler.post(new Runnable() {
13079                 @Override
13080                 public void run() {
13081                     try {
13082                         IBackupManager bm = IBackupManager.Stub.asInterface(
13083                                 ServiceManager.getService(Context.BACKUP_SERVICE));
13084                         bm.agentDisconnectedForUser(app.userId, app.info.packageName);
13085                     } catch (RemoteException e) {
13086                         // can't happen; backup manager is local
13087                     }
13088                 }
13089             });
13090         }
13091 
13092         mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid);
13093 
13094         // If this is a preceding instance of another process instance
13095         allowRestart = mProcessList.handlePrecedingAppDiedLocked(app);
13096 
13097         // If somehow this process was still waiting for the death of its predecessor,
13098         // (probably it's "killed" before starting for real), reset the bookkeeping.
13099         final ProcessRecord predecessor = app.mPredecessor;
13100         if (predecessor != null) {
13101             predecessor.mSuccessor = null;
13102             predecessor.mSuccessorStartRunnable = null;
13103             app.mPredecessor = null;
13104         }
13105 
13106         // If the caller is restarting this app, then leave it in its
13107         // current lists and let the caller take care of it.
13108         if (restarting) {
13109             return false;
13110         }
13111 
13112         if (!app.isPersistent() || app.isolated) {
13113             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
13114                     "Removing non-persistent process during cleanup: " + app);
13115             if (!replacingPid) {
13116                 mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
13117             }
13118             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
13119         } else if (!app.isRemoved()) {
13120             // This app is persistent, so we need to keep its record around.
13121             // If it is not already on the pending app list, add it there
13122             // and start a new process for it.
13123             if (mPersistentStartingProcesses.indexOf(app) < 0) {
13124                 mPersistentStartingProcesses.add(app);
13125                 restart = true;
13126             }
13127         }
13128         if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(
13129                 TAG_CLEANUP, "Clean-up removing on hold: " + app);
13130         mProcessesOnHold.remove(app);
13131 
13132         mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController());
13133         mProcessList.noteProcessDiedLocked(app);
13134 
13135         if (restart && allowRestart && !app.isolated) {
13136             // We have components that still need to be running in the
13137             // process, so re-launch it.
13138             if (index < 0) {
13139                 ProcessList.remove(pid);
13140             }
13141 
13142             // Remove provider publish timeout because we will start a new timeout when the
13143             // restarted process is attaching (if the process contains launching providers).
13144             mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app);
13145 
13146             mProcessList.addProcessNameLocked(app);
13147             app.setPendingStart(false);
13148             mProcessList.startProcessLocked(app, new HostingRecord(
13149                     HostingRecord.HOSTING_TYPE_RESTART, app.processName),
13150                     ZYGOTE_POLICY_FLAG_EMPTY);
13151             return true;
13152         } else if (pid > 0 && pid != MY_PID) {
13153             // Goodbye!
13154             removePidLocked(pid, app);
13155             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
13156             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
13157             if (app.isolated) {
13158                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
13159             }
13160             app.setPid(0);
13161         }
13162         return false;
13163     }
13164 
13165     // =========================================================
13166     // SERVICES
13167     // =========================================================
13168 
13169     @Override
getServices(int maxNum, int flags)13170     public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) {
13171         enforceNotIsolatedCaller("getServices");
13172 
13173         final int callingUid = Binder.getCallingUid();
13174         final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission(
13175             INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED);
13176         final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices",
13177                 Binder.getCallingPid(), callingUid);
13178         synchronized (this) {
13179             return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid,
13180                 allowed, canInteractAcrossUsers);
13181         }
13182     }
13183 
13184     @Override
getRunningServiceControlPanel(ComponentName name)13185     public PendingIntent getRunningServiceControlPanel(ComponentName name) {
13186         enforceNotIsolatedCaller("getRunningServiceControlPanel");
13187         final int callingUid = Binder.getCallingUid();
13188         final int callingUserId = UserHandle.getUserId(callingUid);
13189         if (name == null || getPackageManagerInternal()
13190                 .filterAppAccess(name.getPackageName(), callingUid, callingUserId)) {
13191             return null;
13192         }
13193         synchronized (this) {
13194             return mServices.getRunningServiceControlPanelLocked(name);
13195         }
13196     }
13197 
13198     @Override
logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)13199     public void logFgsApiBegin(@ForegroundServiceApiType int apiType,
13200             int uid, int pid) {
13201         enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE,
13202                 "logFgsApiBegin");
13203         synchronized (this) {
13204             mServices.logFgsApiBeginLocked(apiType, uid, pid);
13205         }
13206     }
13207 
13208     @Override
logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)13209     public void logFgsApiEnd(@ForegroundServiceApiType int apiType,
13210             int uid, int pid) {
13211         enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE,
13212                 "logFgsApiEnd");
13213         synchronized (this) {
13214             mServices.logFgsApiEndLocked(apiType, uid, pid);
13215         }
13216     }
13217 
13218     @Override
logFgsApiStateChanged(@oregroundServiceApiType int apiType, int state, int uid, int pid)13219     public void logFgsApiStateChanged(@ForegroundServiceApiType int apiType,
13220             int state, int uid, int pid) {
13221         enforceCallingPermission(android.Manifest.permission.LOG_FOREGROUND_RESOURCE_USE,
13222                 "logFgsApiEvent");
13223         synchronized (this) {
13224             mServices.logFgsApiStateChangedLocked(apiType, uid, pid, state);
13225         }
13226     }
13227 
13228     @Override
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)13229     public ComponentName startService(IApplicationThread caller, Intent service,
13230             String resolvedType, boolean requireForeground, String callingPackage,
13231             String callingFeatureId, int userId)
13232             throws TransactionTooLargeException {
13233         return startService(caller, service, resolvedType, requireForeground, callingPackage,
13234                 callingFeatureId, userId, false /* isSdkSandboxService */, INVALID_UID, null, null);
13235     }
13236 
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13237     private ComponentName startService(IApplicationThread caller, Intent service,
13238             String resolvedType, boolean requireForeground, String callingPackage,
13239             String callingFeatureId, int userId, boolean isSdkSandboxService,
13240             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)
13241             throws TransactionTooLargeException {
13242         enforceNotIsolatedCaller("startService");
13243         enforceAllowedToStartOrBindServiceIfSdkSandbox(service);
13244         // Refuse possible leaked file descriptors
13245         if (service != null && service.hasFileDescriptors() == true) {
13246             throw new IllegalArgumentException("File descriptors passed in Intent");
13247         }
13248 
13249         if (callingPackage == null) {
13250             throw new IllegalArgumentException("callingPackage cannot be null");
13251         }
13252 
13253         if (isSdkSandboxService && instanceName == null) {
13254             throw new IllegalArgumentException("No instance name provided for SDK sandbox process");
13255         }
13256         validateServiceInstanceName(instanceName);
13257 
13258         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
13259                 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
13260         final int callingPid = Binder.getCallingPid();
13261         final int callingUid = Binder.getCallingUid();
13262         final long origId = Binder.clearCallingIdentity();
13263         ComponentName res;
13264         try {
13265             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13266                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startService: "
13267                         + "intent=" + service + ", caller=" + callingPackage
13268                         + ", fgRequired=" + requireForeground);
13269             }
13270             synchronized (this) {
13271                 res = mServices.startServiceLocked(caller, service,
13272                         resolvedType, callingPid, callingUid,
13273                         requireForeground, callingPackage, callingFeatureId, userId,
13274                         isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
13275                         instanceName);
13276             }
13277         } finally {
13278             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13279             Binder.restoreCallingIdentity(origId);
13280         }
13281         return res;
13282     }
13283 
validateServiceInstanceName(String instanceName)13284     private void validateServiceInstanceName(String instanceName) {
13285         // Ensure that instanceName, which is caller provided, does not contain
13286         // unusual characters.
13287         if (instanceName != null) {
13288             if (!instanceName.matches("[a-zA-Z0-9_.]+")) {
13289                 throw new IllegalArgumentException("Illegal instanceName");
13290             }
13291         }
13292     }
13293 
13294     @Override
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)13295     public int stopService(IApplicationThread caller, Intent service,
13296             String resolvedType, int userId) {
13297         return stopService(caller, service, resolvedType, userId, false /* isSdkSandboxService */,
13298                 INVALID_UID, null, null);
13299     }
13300 
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)13301     private int stopService(IApplicationThread caller, Intent service, String resolvedType,
13302             int userId, boolean isSdkSandboxService,
13303             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) {
13304         enforceNotIsolatedCaller("stopService");
13305         // Refuse possible leaked file descriptors
13306         if (service != null && service.hasFileDescriptors() == true) {
13307             throw new IllegalArgumentException("File descriptors passed in Intent");
13308         }
13309 
13310         try {
13311             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13312                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopService: " + service);
13313             }
13314             synchronized (this) {
13315                 return mServices.stopServiceLocked(caller, service, resolvedType, userId,
13316                         isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
13317                         instanceName);
13318             }
13319         } finally {
13320             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13321         }
13322     }
13323 
13324     @Override
peekService(Intent service, String resolvedType, String callingPackage)13325     public IBinder peekService(Intent service, String resolvedType, String callingPackage) {
13326         enforceNotIsolatedCaller("peekService");
13327         // Refuse possible leaked file descriptors
13328         if (service != null && service.hasFileDescriptors() == true) {
13329             throw new IllegalArgumentException("File descriptors passed in Intent");
13330         }
13331 
13332         if (callingPackage == null) {
13333             throw new IllegalArgumentException("callingPackage cannot be null");
13334         }
13335 
13336         synchronized(this) {
13337             return mServices.peekServiceLocked(service, resolvedType, callingPackage);
13338         }
13339     }
13340 
13341     @Override
stopServiceToken(ComponentName className, IBinder token, int startId)13342     public boolean stopServiceToken(ComponentName className, IBinder token,
13343             int startId) {
13344         try {
13345             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13346                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopServiceToken: "
13347                         + (className != null ? className.toShortString()
13348                         : ("from " + Binder.getCallingPid())));
13349             }
13350             synchronized (this) {
13351                 return mServices.stopServiceTokenLocked(className, token, startId);
13352             }
13353         } finally {
13354             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13355         }
13356     }
13357 
13358     @Override
setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)13359     public void setServiceForeground(ComponentName className, IBinder token,
13360             int id, Notification notification, int flags, int foregroundServiceType) {
13361         synchronized(this) {
13362             mServices.setServiceForegroundLocked(className, token, id, notification, flags,
13363                     foregroundServiceType);
13364         }
13365     }
13366 
13367     @Override
getForegroundServiceType(ComponentName className, IBinder token)13368     public int getForegroundServiceType(ComponentName className, IBinder token) {
13369         synchronized (this) {
13370             return mServices.getForegroundServiceTypeLocked(className, token);
13371         }
13372     }
13373 
13374     @Override
shouldServiceTimeOut(ComponentName className, IBinder token)13375     public boolean shouldServiceTimeOut(ComponentName className, IBinder token) {
13376         synchronized (this) {
13377             return mServices.shouldServiceTimeOutLocked(className, token);
13378         }
13379     }
13380 
13381     @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)13382     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
13383             boolean requireFull, String name, String callerPackage) {
13384         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
13385                 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
13386     }
13387 
isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)13388     boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
13389             String className, int flags) {
13390         boolean result = false;
13391         // For apps that don't have pre-defined UIDs, check for permission
13392         if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) {
13393             if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
13394                 if (ActivityManager.checkUidPermission(
13395                         INTERACT_ACROSS_USERS,
13396                         aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
13397                     ComponentName comp = new ComponentName(aInfo.packageName, className);
13398                     String msg = "Permission Denial: Component " + comp.flattenToShortString()
13399                             + " requests FLAG_SINGLE_USER, but app does not hold "
13400                             + INTERACT_ACROSS_USERS;
13401                     Slog.w(TAG, msg);
13402                     throw new SecurityException(msg);
13403                 }
13404                 // Permission passed
13405                 result = true;
13406             }
13407         } else if ("system".equals(componentProcessName)) {
13408             result = true;
13409         } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
13410             // Phone app and persistent apps are allowed to export singleuser providers.
13411             result = UserHandle.isSameApp(aInfo.uid, PHONE_UID)
13412                     || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
13413         }
13414         if (DEBUG_MU) Slog.v(TAG_MU,
13415                 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x"
13416                 + Integer.toHexString(flags) + ") = " + result);
13417         return result;
13418     }
13419 
13420     /**
13421      * Checks to see if the caller is in the same app as the singleton
13422      * component, or the component is in a special app. It allows special apps
13423      * to export singleton components but prevents exporting singleton
13424      * components for regular apps.
13425      */
isValidSingletonCall(int callingUid, int componentUid)13426     boolean isValidSingletonCall(int callingUid, int componentUid) {
13427         int componentAppId = UserHandle.getAppId(componentUid);
13428         return UserHandle.isSameApp(callingUid, componentUid)
13429                 || componentAppId == SYSTEM_UID
13430                 || componentAppId == PHONE_UID
13431                 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
13432                         == PackageManager.PERMISSION_GRANTED;
13433     }
13434 
bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String callingPackage, int userId)13435     public int bindService(IApplicationThread caller, IBinder token, Intent service,
13436             String resolvedType, IServiceConnection connection, long flags,
13437             String callingPackage, int userId) throws TransactionTooLargeException {
13438         return bindServiceInstance(caller, token, service, resolvedType, connection, flags,
13439                 null, callingPackage, userId);
13440     }
13441 
13442     /**
13443      * Binds to a service with a given instanceName, creating it if it does not already exist.
13444      * If the instanceName field is not supplied, binding to the service occurs as usual.
13445      */
bindServiceInstance(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, long flags, String instanceName, String callingPackage, int userId)13446     public int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service,
13447             String resolvedType, IServiceConnection connection, long flags, String instanceName,
13448             String callingPackage, int userId) throws TransactionTooLargeException {
13449         return bindServiceInstance(caller, token, service, resolvedType, connection, flags,
13450                 instanceName, false, INVALID_UID, null, null, callingPackage, userId);
13451     }
13452 
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)13453     private int bindServiceInstance(IApplicationThread caller, IBinder token, Intent service,
13454             String resolvedType, IServiceConnection connection, long flags, String instanceName,
13455             boolean isSdkSandboxService, int sdkSandboxClientAppUid,
13456             String sdkSandboxClientAppPackage,
13457             IApplicationThread sdkSandboxClientApplicationThread,
13458             String callingPackage, int userId)
13459             throws TransactionTooLargeException {
13460         enforceNotIsolatedCaller("bindService");
13461         enforceAllowedToStartOrBindServiceIfSdkSandbox(service);
13462 
13463         // Refuse possible leaked file descriptors
13464         if (service != null && service.hasFileDescriptors() == true) {
13465             throw new IllegalArgumentException("File descriptors passed in Intent");
13466         }
13467 
13468         if (callingPackage == null) {
13469             throw new IllegalArgumentException("callingPackage cannot be null");
13470         }
13471 
13472         if (isSdkSandboxService && instanceName == null) {
13473             throw new IllegalArgumentException("No instance name provided for isolated process");
13474         }
13475 
13476         validateServiceInstanceName(instanceName);
13477 
13478         try {
13479             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13480                 final ComponentName cn = service.getComponent();
13481                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindService:"
13482                         + (cn != null ? cn.toShortString() : service.getAction()));
13483             }
13484             synchronized (this) {
13485                 return mServices.bindServiceLocked(caller, token, service, resolvedType, connection,
13486                         flags, instanceName, isSdkSandboxService, sdkSandboxClientAppUid,
13487                         sdkSandboxClientAppPackage, sdkSandboxClientApplicationThread,
13488                         callingPackage, userId);
13489             }
13490         } finally {
13491             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13492         }
13493     }
13494 
updateServiceGroup(IServiceConnection connection, int group, int importance)13495     public void updateServiceGroup(IServiceConnection connection, int group, int importance) {
13496         synchronized (this) {
13497             mServices.updateServiceGroupLocked(connection, group, importance);
13498         }
13499     }
13500 
unbindService(IServiceConnection connection)13501     public boolean unbindService(IServiceConnection connection) {
13502         try {
13503             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
13504                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "unbindService");
13505             }
13506             synchronized (this) {
13507                 return mServices.unbindServiceLocked(connection);
13508             }
13509         } finally {
13510             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
13511         }
13512     }
13513 
publishService(IBinder token, Intent intent, IBinder service)13514     public void publishService(IBinder token, Intent intent, IBinder service) {
13515         // Refuse possible leaked file descriptors
13516         if (intent != null && intent.hasFileDescriptors() == true) {
13517             throw new IllegalArgumentException("File descriptors passed in Intent");
13518         }
13519 
13520         synchronized(this) {
13521             if (!(token instanceof ServiceRecord)) {
13522                 throw new IllegalArgumentException("Invalid service token");
13523             }
13524             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
13525         }
13526     }
13527 
unbindFinished(IBinder token, Intent intent, boolean doRebind)13528     public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
13529         // Refuse possible leaked file descriptors
13530         if (intent != null && intent.hasFileDescriptors() == true) {
13531             throw new IllegalArgumentException("File descriptors passed in Intent");
13532         }
13533 
13534         synchronized(this) {
13535             mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
13536         }
13537     }
13538 
serviceDoneExecuting(IBinder token, int type, int startId, int res)13539     public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
13540         synchronized(this) {
13541             if (!(token instanceof ServiceRecord)) {
13542                 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
13543                 throw new IllegalArgumentException("Invalid service token");
13544             }
13545             mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false);
13546         }
13547     }
13548 
13549     // =========================================================
13550     // BACKUP AND RESTORE
13551     // =========================================================
13552 
13553     // Cause the target app to be launched if necessary and its backup agent
13554     // instantiated.  The backup agent will invoke backupAgentCreated() on the
13555     // activity manager to announce its creation.
bindBackupAgent(String packageName, int backupMode, int targetUserId, @BackupDestination int backupDestination)13556     public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId,
13557             @BackupDestination int backupDestination) {
13558         if (DEBUG_BACKUP) {
13559             Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
13560                     + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
13561                     + " uid = " + Process.myUid());
13562         }
13563         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
13564 
13565         // The instantiatedUserId is the user of the process the backup agent is started in. This is
13566         // different from the targetUserId which is the user whose data is to be backed up or
13567         // restored. This distinction is important for system-process packages that live in the
13568         // system user's process but backup/restore data for non-system users.
13569         // TODO (b/123688746): Handle all system-process packages with singleton check.
13570         boolean useSystemUser = PLATFORM_PACKAGE_NAME.equals(packageName)
13571                 || getPackageManagerInternal().getSystemUiServiceComponent().getPackageName()
13572                         .equals(packageName);
13573         final int instantiatedUserId = useSystemUser ? UserHandle.USER_SYSTEM : targetUserId;
13574 
13575         IPackageManager pm = AppGlobals.getPackageManager();
13576         ApplicationInfo app = null;
13577         try {
13578             app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
13579         } catch (RemoteException e) {
13580             // can't happen; package manager is process-local
13581         }
13582         if (app == null) {
13583             Slog.w(TAG, "Unable to bind backup agent for " + packageName);
13584             return false;
13585         }
13586         if (app.backupAgentName != null) {
13587             final ComponentName backupAgentName = new ComponentName(
13588                     app.packageName, app.backupAgentName);
13589             int enableState = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
13590             try {
13591                 enableState = pm.getComponentEnabledSetting(backupAgentName, instantiatedUserId);
13592             } catch (RemoteException e) {
13593                 // can't happen; package manager is process-local
13594             }
13595             switch (enableState) {
13596                 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
13597                 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER:
13598                 case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED:
13599                     Slog.w(TAG, "Unable to bind backup agent for " + backupAgentName
13600                             + ", the backup agent component is disabled.");
13601                     return false;
13602 
13603                 case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
13604                 case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
13605                 default:
13606                     // Since there's no way to declare a backup agent disabled in the manifest,
13607                     // assume the case COMPONENT_ENABLED_STATE_DEFAULT to be enabled.
13608                     break;
13609             }
13610         }
13611 
13612         int oldBackupUid;
13613         int newBackupUid;
13614 
13615         synchronized(this) {
13616             // !!! TODO: currently no check here that we're already bound
13617             // Backup agent is now in use, its package can't be stopped.
13618             try {
13619                 mPackageManagerInt.setPackageStoppedState(
13620                         app.packageName, false, UserHandle.getUserId(app.uid));
13621             } catch (IllegalArgumentException e) {
13622                 Slog.w(TAG, "Failed trying to unstop package "
13623                         + app.packageName + ": " + e);
13624             }
13625 
13626             BackupRecord r = new BackupRecord(app, backupMode, targetUserId, backupDestination);
13627             ComponentName hostingName =
13628                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL
13629                             || backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE)
13630                             ? new ComponentName(app.packageName, app.backupAgentName)
13631                             : new ComponentName("android", "FullBackupAgent");
13632 
13633             // startProcessLocked() returns existing proc's record if it's already running
13634             ProcessRecord proc = startProcessLocked(app.processName, app,
13635                     false, 0,
13636                     new HostingRecord(HostingRecord.HOSTING_TYPE_BACKUP, hostingName),
13637                     ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false);
13638             if (proc == null) {
13639                 Slog.e(TAG, "Unable to start backup agent process " + r);
13640                 return false;
13641             }
13642 
13643             // If the app is a regular app (uid >= 10000) and not the system server or phone
13644             // process, etc, then mark it as being in full backup so that certain calls to the
13645             // process can be blocked. This is not reset to false anywhere because we kill the
13646             // process after the full backup is done and the ProcessRecord will vaporize anyway.
13647             if (UserHandle.isApp(app.uid) &&
13648                     backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) {
13649                 proc.setInFullBackup(true);
13650             }
13651             r.app = proc;
13652             final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
13653             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
13654             newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1;
13655             mBackupTargets.put(targetUserId, r);
13656 
13657             proc.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP);
13658 
13659             // Try not to kill the process during backup
13660             updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP);
13661 
13662             // If the process is already attached, schedule the creation of the backup agent now.
13663             // If it is not yet live, this will be done when it attaches to the framework.
13664             final IApplicationThread thread = proc.getThread();
13665             if (thread != null) {
13666                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
13667                 try {
13668                     thread.scheduleCreateBackupAgent(app, backupMode, targetUserId,
13669                             backupDestination);
13670                 } catch (RemoteException e) {
13671                     // Will time out on the backup manager side
13672                 }
13673             } else {
13674                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach");
13675             }
13676             // Invariants: at this point, the target app process exists and the application
13677             // is either already running or in the process of coming up.  mBackupTarget and
13678             // mBackupAppName describe the app, so that when it binds back to the AM we
13679             // know that it's scheduled for a backup-agent operation.
13680         }
13681 
13682         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
13683         if (oldBackupUid != -1) {
13684             js.removeBackingUpUid(oldBackupUid);
13685         }
13686         if (newBackupUid != -1) {
13687             js.addBackingUpUid(newBackupUid);
13688         }
13689 
13690         return true;
13691     }
13692 
clearPendingBackup(int userId)13693     private void clearPendingBackup(int userId) {
13694         if (DEBUG_BACKUP) {
13695             Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = "
13696                     + Binder.getCallingUid() + " uid = " + Process.myUid());
13697         }
13698 
13699         synchronized (this) {
13700             final int indexOfKey = mBackupTargets.indexOfKey(userId);
13701             if (indexOfKey >= 0) {
13702                 final BackupRecord backupTarget = mBackupTargets.valueAt(indexOfKey);
13703                 if (backupTarget != null && backupTarget.app != null) {
13704                     backupTarget.app.mProfile.clearHostingComponentType(
13705                             HOSTING_COMPONENT_TYPE_BACKUP);
13706                 }
13707                 mBackupTargets.removeAt(indexOfKey);
13708             }
13709         }
13710 
13711         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
13712         js.clearAllBackingUpUids();
13713     }
13714 
13715     // A backup agent has just come up
13716     @Override
backupAgentCreated(String agentPackageName, IBinder agent, int userId)13717     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
13718         final int callingUid = Binder.getCallingUid();
13719         enforceCallingPackage(agentPackageName, callingUid);
13720 
13721         // Resolve the target user id and enforce permissions.
13722         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid,
13723                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
13724         if (DEBUG_BACKUP) {
13725             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
13726                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
13727                     + " callingUid = " + callingUid + " uid = " + Process.myUid());
13728         }
13729 
13730         synchronized(this) {
13731             final BackupRecord backupTarget = mBackupTargets.get(userId);
13732             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
13733             if (!agentPackageName.equals(backupAppName)) {
13734                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
13735                 return;
13736             }
13737         }
13738 
13739         final long oldIdent = Binder.clearCallingIdentity();
13740         try {
13741             IBackupManager bm = IBackupManager.Stub.asInterface(
13742                     ServiceManager.getService(Context.BACKUP_SERVICE));
13743             bm.agentConnectedForUser(userId, agentPackageName, agent);
13744         } catch (RemoteException e) {
13745             // can't happen; the backup manager service is local
13746         } catch (Exception e) {
13747             Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
13748             e.printStackTrace();
13749         } finally {
13750             Binder.restoreCallingIdentity(oldIdent);
13751         }
13752     }
13753 
13754     // done with this agent
unbindBackupAgent(ApplicationInfo appInfo)13755     public void unbindBackupAgent(ApplicationInfo appInfo) {
13756         if (DEBUG_BACKUP) {
13757             Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = "
13758                     + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = "
13759                     + Process.myUid());
13760         }
13761 
13762         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent");
13763         if (appInfo == null) {
13764             Slog.w(TAG, "unbind backup agent for null app");
13765             return;
13766         }
13767 
13768         int oldBackupUid;
13769 
13770         final int userId = UserHandle.getUserId(appInfo.uid);
13771         synchronized(this) {
13772             final BackupRecord backupTarget = mBackupTargets.get(userId);
13773             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
13774             try {
13775                 if (backupAppName == null) {
13776                     Slog.w(TAG, "Unbinding backup agent with no active backup");
13777                     return;
13778                 }
13779 
13780                 if (!backupAppName.equals(appInfo.packageName)) {
13781                     Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
13782                     return;
13783                 }
13784 
13785                 // Not backing this app up any more; reset its OOM adjustment
13786                 final ProcessRecord proc = backupTarget.app;
13787                 updateOomAdjLocked(proc, OOM_ADJ_REASON_BACKUP);
13788                 proc.setInFullBackup(false);
13789                 proc.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_BACKUP);
13790 
13791                 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
13792 
13793                 // If the app crashed during backup, 'thread' will be null here
13794                 final IApplicationThread thread = proc.getThread();
13795                 if (thread != null) {
13796                     try {
13797                         thread.scheduleDestroyBackupAgent(appInfo, userId);
13798                     } catch (Exception e) {
13799                         Slog.e(TAG, "Exception when unbinding backup agent:");
13800                         e.printStackTrace();
13801                     }
13802                 }
13803             } finally {
13804                 mBackupTargets.delete(userId);
13805             }
13806         }
13807 
13808         if (oldBackupUid != -1) {
13809             JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
13810             js.removeBackingUpUid(oldBackupUid);
13811         }
13812     }
13813 
13814     // =========================================================
13815     // BROADCASTS
13816     // =========================================================
13817 
isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)13818     private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) {
13819         if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) {
13820             return false;
13821         }
13822         // Easy case -- we have the app's ProcessRecord.
13823         if (record != null) {
13824             return record.info.isInstantApp();
13825         }
13826         // Otherwise check with PackageManager.
13827         IPackageManager pm = AppGlobals.getPackageManager();
13828         try {
13829             if (callerPackage == null) {
13830                 final String[] packageNames = pm.getPackagesForUid(uid);
13831                 if (packageNames == null || packageNames.length == 0) {
13832                     throw new IllegalArgumentException("Unable to determine caller package name");
13833                 }
13834                 // Instant Apps can't use shared uids, so its safe to only check the first package.
13835                 callerPackage = packageNames[0];
13836             }
13837             mAppOpsService.checkPackage(uid, callerPackage);
13838             return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid));
13839         } catch (RemoteException e) {
13840             Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e);
13841             return true;
13842         }
13843     }
13844 
13845     /**
13846      * @deprecated Use {@link #registerReceiverWithFeature}
13847      */
13848     @Deprecated
registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)13849     public Intent registerReceiver(IApplicationThread caller, String callerPackage,
13850             IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
13851             int flags) {
13852         return registerReceiverWithFeature(caller, callerPackage, null, null,
13853                 receiver, filter, permission, userId, flags);
13854     }
13855 
registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)13856     public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage,
13857             String callerFeatureId, String receiverId, IIntentReceiver receiver,
13858             IntentFilter filter, String permission, int userId, int flags) {
13859         enforceNotIsolatedCaller("registerReceiver");
13860         ArrayList<StickyBroadcast> stickyBroadcasts = null;
13861         ProcessRecord callerApp = null;
13862         final boolean visibleToInstantApps
13863                 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
13864 
13865         int callingUid;
13866         int callingPid;
13867         boolean instantApp;
13868         synchronized(this) {
13869             callerApp = getRecordForAppLOSP(caller);
13870             if (callerApp == null) {
13871                 Slog.w(TAG, "registerReceiverWithFeature: no app for " + caller);
13872                 return null;
13873             }
13874             if (callerApp.info.uid != SYSTEM_UID
13875                     && !callerApp.getPkgList().containsKey(callerPackage)
13876                     && !"android".equals(callerPackage)) {
13877                 throw new SecurityException("Given caller package " + callerPackage
13878                         + " is not running in process " + callerApp);
13879             }
13880             callingUid = callerApp.info.uid;
13881             callingPid = callerApp.getPid();
13882 
13883             instantApp = isInstantApp(callerApp, callerPackage, callingUid);
13884             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
13885                     ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
13886 
13887             // Warn if system internals are registering for important broadcasts
13888             // without also using a priority to ensure they process the event
13889             // before normal apps hear about it
13890             if (UserHandle.isCore(callingUid)) {
13891                 final int priority = filter.getPriority();
13892                 final boolean systemPriority = (priority >= IntentFilter.SYSTEM_HIGH_PRIORITY)
13893                         || (priority <= IntentFilter.SYSTEM_LOW_PRIORITY);
13894                 if (!systemPriority) {
13895                     final int N = filter.countActions();
13896                     for (int i = 0; i < N; i++) {
13897                         // TODO: expand to additional important broadcasts over time
13898                         final String action = filter.getAction(i);
13899                         if (action.startsWith("android.intent.action.USER_")
13900                                 || action.startsWith("android.intent.action.PACKAGE_")
13901                                 || action.startsWith("android.intent.action.UID_")
13902                                 || action.startsWith("android.intent.action.EXTERNAL_")
13903                                 || action.startsWith("android.bluetooth.")) {
13904                             if (DEBUG_BROADCAST) {
13905                                 Slog.wtf(TAG,
13906                                         "System internals registering for " + filter.toLongString()
13907                                                 + " with app priority; this will race with apps!",
13908                                         new Throwable());
13909                             }
13910 
13911                             // When undefined, assume that system internals need
13912                             // to hear about the event first; they can use
13913                             // SYSTEM_LOW_PRIORITY if they need to hear last
13914                             if (priority == 0) {
13915                                 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
13916                             }
13917                             break;
13918                         }
13919                     }
13920                 }
13921             }
13922 
13923             Iterator<String> actions = filter.actionsIterator();
13924             if (actions == null) {
13925                 ArrayList<String> noAction = new ArrayList<String>(1);
13926                 noAction.add(null);
13927                 actions = noAction.iterator();
13928             }
13929             boolean onlyProtectedBroadcasts = true;
13930 
13931             // Collect stickies of users and check if broadcast is only registered for protected
13932             // broadcasts
13933             int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) };
13934             while (actions.hasNext()) {
13935                 String action = actions.next();
13936                 for (int id : userIds) {
13937                     ArrayMap<String, ArrayList<StickyBroadcast>> stickies =
13938                             mStickyBroadcasts.get(id);
13939                     if (stickies != null) {
13940                         ArrayList<StickyBroadcast> broadcasts = stickies.get(action);
13941                         if (broadcasts != null) {
13942                             if (stickyBroadcasts == null) {
13943                                 stickyBroadcasts = new ArrayList<>();
13944                             }
13945                             stickyBroadcasts.addAll(broadcasts);
13946                         }
13947                     }
13948                 }
13949                 if (onlyProtectedBroadcasts) {
13950                     try {
13951                         onlyProtectedBroadcasts &=
13952                                 AppGlobals.getPackageManager().isProtectedBroadcast(action);
13953                     } catch (RemoteException e) {
13954                         onlyProtectedBroadcasts = false;
13955                         Slog.w(TAG, "Remote exception", e);
13956                     }
13957                 }
13958             }
13959 
13960             if (Process.isSdkSandboxUid(Binder.getCallingUid())) {
13961                 SdkSandboxManagerLocal sdkSandboxManagerLocal =
13962                         LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
13963                 if (sdkSandboxManagerLocal == null) {
13964                     throw new IllegalStateException("SdkSandboxManagerLocal not found when checking"
13965                             + " whether SDK sandbox uid can register to broadcast receivers.");
13966                 }
13967                 if (!sdkSandboxManagerLocal.canRegisterBroadcastReceiver(
13968                         /*IntentFilter=*/ filter, flags, onlyProtectedBroadcasts)) {
13969                     throw new SecurityException("SDK sandbox not allowed to register receiver"
13970                             + " with the given IntentFilter: " + filter.toLongString());
13971                 }
13972             }
13973 
13974             // If the change is enabled, but neither exported or not exported is set, we need to log
13975             // an error so the consumer can know to explicitly set the value for their flag.
13976             // If the caller is registering for a sticky broadcast with a null receiver, we won't
13977             // require a flag
13978             final boolean explicitExportStateDefined =
13979                     (flags & (Context.RECEIVER_EXPORTED | Context.RECEIVER_NOT_EXPORTED)) != 0;
13980             if (((flags & Context.RECEIVER_EXPORTED) != 0) && (
13981                     (flags & Context.RECEIVER_NOT_EXPORTED) != 0)) {
13982                 throw new IllegalArgumentException(
13983                         "Receiver can't specify both RECEIVER_EXPORTED and RECEIVER_NOT_EXPORTED"
13984                                 + "flag");
13985             }
13986 
13987             // Don't enforce the flag check if we're EITHER registering for only protected
13988             // broadcasts, or the receiver is null (a sticky broadcast). Sticky broadcasts should
13989             // not be used generally, so we will be marking them as exported by default
13990             boolean requireExplicitFlagForDynamicReceivers = CompatChanges.isChangeEnabled(
13991                     DYNAMIC_RECEIVER_EXPLICIT_EXPORT_REQUIRED, callingUid);
13992 
13993             // A receiver that is visible to instant apps must also be exported.
13994             final boolean unexportedReceiverVisibleToInstantApps =
13995                     ((flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0) && (
13996                             (flags & Context.RECEIVER_NOT_EXPORTED) != 0);
13997             if (unexportedReceiverVisibleToInstantApps && requireExplicitFlagForDynamicReceivers) {
13998                 throw new IllegalArgumentException(
13999                         "Receiver can't specify both RECEIVER_VISIBLE_TO_INSTANT_APPS and "
14000                                 + "RECEIVER_NOT_EXPORTED flag");
14001             }
14002 
14003             if (!onlyProtectedBroadcasts) {
14004                 if (receiver == null && !explicitExportStateDefined) {
14005                     // sticky broadcast, no flag specified (flag isn't required)
14006                     flags |= Context.RECEIVER_EXPORTED;
14007                 } else if (requireExplicitFlagForDynamicReceivers && !explicitExportStateDefined) {
14008                     throw new SecurityException(
14009                             callerPackage + ": One of RECEIVER_EXPORTED or "
14010                                     + "RECEIVER_NOT_EXPORTED should be specified when a receiver "
14011                                     + "isn't being registered exclusively for system broadcasts");
14012                     // Assume default behavior-- flag check is not enforced
14013                 } else if (!requireExplicitFlagForDynamicReceivers && (
14014                         (flags & Context.RECEIVER_NOT_EXPORTED) == 0)) {
14015                     // Change is not enabled, assume exported unless otherwise specified.
14016                     flags |= Context.RECEIVER_EXPORTED;
14017                 }
14018             } else if ((flags & Context.RECEIVER_NOT_EXPORTED) == 0) {
14019                 flags |= Context.RECEIVER_EXPORTED;
14020             }
14021         }
14022 
14023         // Dynamic receivers are exported by default for versions prior to T
14024         final boolean exported = (flags & Context.RECEIVER_EXPORTED) != 0;
14025 
14026         ArrayList<StickyBroadcast> allSticky = null;
14027         if (stickyBroadcasts != null) {
14028             final ContentResolver resolver = mContext.getContentResolver();
14029             // Look for any matching sticky broadcasts...
14030             for (int i = 0, N = stickyBroadcasts.size(); i < N; i++) {
14031                 final StickyBroadcast broadcast = stickyBroadcasts.get(i);
14032                 Intent intent = broadcast.intent;
14033                 // Don't provided intents that aren't available to instant apps.
14034                 if (instantApp &&
14035                         (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) {
14036                     continue;
14037                 }
14038                 // If intent has scheme "content", it will need to access
14039                 // provider that needs to lock mProviderMap in ActivityThread
14040                 // and also it may need to wait application response, so we
14041                 // cannot lock ActivityManagerService here.
14042                 if (filter.match(resolver, intent, true, TAG) >= 0) {
14043                     if (allSticky == null) {
14044                         allSticky = new ArrayList<>();
14045                     }
14046                     allSticky.add(broadcast);
14047                 }
14048             }
14049         }
14050 
14051         // The first sticky in the list is returned directly back to the client.
14052         Intent sticky = allSticky != null ? allSticky.get(0).intent : null;
14053         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky);
14054         if (receiver == null) {
14055             return sticky;
14056         }
14057 
14058         // SafetyNet logging for b/177931370. If any process other than system_server tries to
14059         // listen to this broadcast action, then log it.
14060         if (callingPid != Process.myPid()) {
14061             if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING")
14062                     || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) {
14063                 EventLog.writeEvent(0x534e4554, "177931370", callingUid, "");
14064             }
14065         }
14066 
14067         synchronized (this) {
14068             IApplicationThread thread;
14069             if (callerApp != null && ((thread = callerApp.getThread()) == null
14070                     || thread.asBinder() != caller.asBinder())) {
14071                 // Original caller already died
14072                 return null;
14073             }
14074             ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14075             if (rl == null) {
14076                 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
14077                         userId, receiver);
14078                 if (rl.app != null) {
14079                     final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers();
14080                     if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) {
14081                         throw new IllegalStateException("Too many receivers, total of "
14082                                 + totalReceiversForApp + ", registered for pid: "
14083                                 + rl.pid + ", callerPackage: " + callerPackage);
14084                     }
14085                     rl.app.mReceivers.addReceiver(rl);
14086                 } else {
14087                     try {
14088                         receiver.asBinder().linkToDeath(rl, 0);
14089                     } catch (RemoteException e) {
14090                         return sticky;
14091                     }
14092                     rl.linkedToDeath = true;
14093                 }
14094                 mRegisteredReceivers.put(receiver.asBinder(), rl);
14095             } else if (rl.uid != callingUid) {
14096                 throw new IllegalArgumentException(
14097                         "Receiver requested to register for uid " + callingUid
14098                         + " was previously registered for uid " + rl.uid
14099                         + " callerPackage is " + callerPackage);
14100             } else if (rl.pid != callingPid) {
14101                 throw new IllegalArgumentException(
14102                         "Receiver requested to register for pid " + callingPid
14103                         + " was previously registered for pid " + rl.pid
14104                         + " callerPackage is " + callerPackage);
14105             } else if (rl.userId != userId) {
14106                 throw new IllegalArgumentException(
14107                         "Receiver requested to register for user " + userId
14108                         + " was previously registered for user " + rl.userId
14109                         + " callerPackage is " + callerPackage);
14110             }
14111             BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId,
14112                     receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps,
14113                     exported);
14114             if (rl.containsFilter(filter)) {
14115                 Slog.w(TAG, "Receiver with filter " + filter
14116                         + " already registered for pid " + rl.pid
14117                         + ", callerPackage is " + callerPackage);
14118             } else {
14119                 rl.add(bf);
14120                 if (!bf.debugCheck()) {
14121                     Slog.w(TAG, "==> For Dynamic broadcast");
14122                 }
14123                 mReceiverResolver.addFilter(getPackageManagerInternal().snapshot(), bf);
14124             }
14125 
14126             // Enqueue broadcasts for all existing stickies that match
14127             // this filter.
14128             if (allSticky != null) {
14129                 ArrayList receivers = new ArrayList();
14130                 receivers.add(bf);
14131                 sticky = null;
14132 
14133                 final int stickyCount = allSticky.size();
14134                 for (int i = 0; i < stickyCount; i++) {
14135                     final StickyBroadcast broadcast = allSticky.get(i);
14136                     final int originalStickyCallingUid = allSticky.get(i).originalCallingUid;
14137                     // TODO(b/281889567): consider using checkComponentPermission instead of
14138                     //  canAccessUnexportedComponents
14139                     if (sticky == null && (exported || originalStickyCallingUid == callingUid
14140                             || ActivityManager.canAccessUnexportedComponents(
14141                             originalStickyCallingUid))) {
14142                         sticky = broadcast.intent;
14143                     }
14144                     BroadcastQueue queue = broadcastQueueForIntent(broadcast.intent);
14145                     BroadcastRecord r = new BroadcastRecord(queue, broadcast.intent, null,
14146                             null, null, -1, -1, false, null, null, null, null, OP_NONE,
14147                             BroadcastOptions.makeWithDeferUntilActive(broadcast.deferUntilActive),
14148                             receivers, null, null, 0, null, null, false, true, true, -1,
14149                             originalStickyCallingUid, BackgroundStartPrivileges.NONE,
14150                             false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */,
14151                             null /* filterExtrasForReceiver */,
14152                             broadcast.originalCallingAppProcessState);
14153                     queue.enqueueBroadcastLocked(r);
14154                 }
14155             }
14156 
14157             return sticky;
14158         }
14159     }
14160 
unregisterReceiver(IIntentReceiver receiver)14161     public void unregisterReceiver(IIntentReceiver receiver) {
14162         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver);
14163 
14164         final long origId = Binder.clearCallingIdentity();
14165         try {
14166             boolean doTrim = false;
14167             synchronized(this) {
14168                 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14169                 if (rl != null) {
14170                     final BroadcastRecord r = rl.curBroadcast;
14171                     if (r != null) {
14172                         final boolean doNext = r.queue.finishReceiverLocked(
14173                                 rl.app, r.resultCode, r.resultData, r.resultExtras,
14174                                 r.resultAbort, false);
14175                         if (doNext) {
14176                             doTrim = true;
14177                         }
14178                     }
14179                     if (rl.app != null) {
14180                         rl.app.mReceivers.removeReceiver(rl);
14181                     }
14182                     removeReceiverLocked(rl);
14183                     if (rl.linkedToDeath) {
14184                         rl.linkedToDeath = false;
14185                         rl.receiver.asBinder().unlinkToDeath(rl, 0);
14186                     }
14187                 }
14188 
14189                 // If we actually concluded any broadcasts, we might now be able
14190                 // to trim the recipients' apps from our working set
14191                 if (doTrim) {
14192                     trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER);
14193                     return;
14194                 }
14195             }
14196 
14197         } finally {
14198             Binder.restoreCallingIdentity(origId);
14199         }
14200     }
14201 
removeReceiverLocked(ReceiverList rl)14202     void removeReceiverLocked(ReceiverList rl) {
14203         mRegisteredReceivers.remove(rl.receiver.asBinder());
14204         for (int i = rl.size() - 1; i >= 0; i--) {
14205             mReceiverResolver.removeFilter(rl.get(i));
14206         }
14207     }
14208 
sendPackageBroadcastLocked(int cmd, String[] packages, int userId)14209     private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
14210         mProcessList.sendPackageBroadcastLocked(cmd, packages, userId);
14211     }
14212 
collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users, int[] broadcastAllowList)14213     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
14214             int callingUid, int[] users, int[] broadcastAllowList) {
14215         // TODO: come back and remove this assumption to triage all broadcasts
14216         int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
14217 
14218         List<ResolveInfo> receivers = null;
14219         HashSet<ComponentName> singleUserReceivers = null;
14220         boolean scannedFirstReceivers = false;
14221         for (int user : users) {
14222             // Skip users that have Shell restrictions
14223             if (callingUid == SHELL_UID
14224                     && mUserController.hasUserRestriction(
14225                     UserManager.DISALLOW_DEBUGGING_FEATURES, user)) {
14226                 continue;
14227             }
14228             List<ResolveInfo> newReceivers = mPackageManagerInt.queryIntentReceivers(
14229                     intent, resolvedType, pmFlags, callingUid, user, true /* forSend */);
14230             if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
14231                 // If this is not the system user, we need to check for
14232                 // any receivers that should be filtered out.
14233                 for (int i = 0; i < newReceivers.size(); i++) {
14234                     ResolveInfo ri = newReceivers.get(i);
14235                     if ((ri.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
14236                         newReceivers.remove(i);
14237                         i--;
14238                     }
14239                 }
14240             }
14241             // Replace the alias receivers with their targets.
14242             if (newReceivers != null) {
14243                 for (int i = newReceivers.size() - 1; i >= 0; i--) {
14244                     final ResolveInfo ri = newReceivers.get(i);
14245                     final Resolution<ResolveInfo> resolution =
14246                             mComponentAliasResolver.resolveReceiver(intent, ri, resolvedType,
14247                                     pmFlags, user, callingUid, true /* forSend */);
14248                     if (resolution == null) {
14249                         // It was an alias, but the target was not found.
14250                         newReceivers.remove(i);
14251                         continue;
14252                     }
14253                     if (resolution.isAlias()) {
14254                         newReceivers.set(i, resolution.getTarget());
14255                     }
14256                 }
14257             }
14258             if (newReceivers != null && newReceivers.size() == 0) {
14259                 newReceivers = null;
14260             }
14261 
14262             if (receivers == null) {
14263                 receivers = newReceivers;
14264             } else if (newReceivers != null) {
14265                 // We need to concatenate the additional receivers
14266                 // found with what we have do far.  This would be easy,
14267                 // but we also need to de-dup any receivers that are
14268                 // singleUser.
14269                 if (!scannedFirstReceivers) {
14270                     // Collect any single user receivers we had already retrieved.
14271                     scannedFirstReceivers = true;
14272                     for (int i = 0; i < receivers.size(); i++) {
14273                         ResolveInfo ri = receivers.get(i);
14274                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14275                             ComponentName cn = new ComponentName(
14276                                     ri.activityInfo.packageName, ri.activityInfo.name);
14277                             if (singleUserReceivers == null) {
14278                                 singleUserReceivers = new HashSet<ComponentName>();
14279                             }
14280                             singleUserReceivers.add(cn);
14281                         }
14282                     }
14283                 }
14284                 // Add the new results to the existing results, tracking
14285                 // and de-dupping single user receivers.
14286                 for (int i = 0; i < newReceivers.size(); i++) {
14287                     ResolveInfo ri = newReceivers.get(i);
14288                     if ((ri.activityInfo.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
14289                         ComponentName cn = new ComponentName(
14290                                 ri.activityInfo.packageName, ri.activityInfo.name);
14291                         if (singleUserReceivers == null) {
14292                             singleUserReceivers = new HashSet<ComponentName>();
14293                         }
14294                         if (!singleUserReceivers.contains(cn)) {
14295                             singleUserReceivers.add(cn);
14296                             receivers.add(ri);
14297                         }
14298                     } else {
14299                         receivers.add(ri);
14300                     }
14301                 }
14302             }
14303         }
14304         if (receivers != null && broadcastAllowList != null) {
14305             for (int i = receivers.size() - 1; i >= 0; i--) {
14306                 final int receiverAppId = UserHandle.getAppId(
14307                         receivers.get(i).activityInfo.applicationInfo.uid);
14308                 if (receiverAppId >= Process.FIRST_APPLICATION_UID
14309                         && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) {
14310                     receivers.remove(i);
14311                 }
14312             }
14313         }
14314         return receivers;
14315     }
14316 
checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)14317     private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp,
14318             String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) {
14319         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
14320             // Don't yell about broadcasts sent via shell
14321             return;
14322         }
14323 
14324         final String action = intent.getAction();
14325         if (isProtectedBroadcast
14326                 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
14327                 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
14328                 || Intent.ACTION_MEDIA_BUTTON.equals(action)
14329                 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
14330                 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
14331                 || Intent.ACTION_MASTER_CLEAR.equals(action)
14332                 || Intent.ACTION_FACTORY_RESET.equals(action)
14333                 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14334                 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
14335                 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action)
14336                 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action)
14337                 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action)
14338                 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) {
14339             // Broadcast is either protected, or it's a public action that
14340             // we've relaxed, so it's fine for system internals to send.
14341             return;
14342         }
14343 
14344         // This broadcast may be a problem...  but there are often system components that
14345         // want to send an internal broadcast to themselves, which is annoying to have to
14346         // explicitly list each action as a protected broadcast, so we will check for that
14347         // one safe case and allow it: an explicit broadcast, only being received by something
14348         // that has protected itself.
14349         if (intent.getPackage() != null || intent.getComponent() != null) {
14350             if (receivers == null || receivers.size() == 0) {
14351                 // Intent is explicit and there's no receivers.
14352                 // This happens, e.g. , when a system component sends a broadcast to
14353                 // its own runtime receiver, and there's no manifest receivers for it,
14354                 // because this method is called twice for each broadcast,
14355                 // for runtime receivers and manifest receivers and the later check would find
14356                 // no receivers.
14357                 return;
14358             }
14359             boolean allProtected = true;
14360             for (int i = receivers.size()-1; i >= 0; i--) {
14361                 Object target = receivers.get(i);
14362                 if (target instanceof ResolveInfo) {
14363                     ResolveInfo ri = (ResolveInfo)target;
14364                     if (ri.activityInfo.exported && ri.activityInfo.permission == null) {
14365                         allProtected = false;
14366                         break;
14367                     }
14368                 } else {
14369                     BroadcastFilter bf = (BroadcastFilter)target;
14370                     if (bf.exported && bf.requiredPermission == null) {
14371                         allProtected = false;
14372                         break;
14373                     }
14374                 }
14375             }
14376             if (allProtected) {
14377                 // All safe!
14378                 return;
14379             }
14380         }
14381 
14382         // The vast majority of broadcasts sent from system internals
14383         // should be protected to avoid security holes, so yell loudly
14384         // to ensure we examine these cases.
14385         if (callerApp != null) {
14386             Log.wtf(TAG, "Sending non-protected broadcast " + action
14387                             + " from system " + callerApp.toShortString() + " pkg " + callerPackage,
14388                     new Throwable());
14389         } else {
14390             Log.wtf(TAG, "Sending non-protected broadcast " + action
14391                             + " from system uid " + UserHandle.formatUid(callingUid)
14392                             + " pkg " + callerPackage,
14393                     new Throwable());
14394         }
14395     }
14396 
14397     // Apply permission policy around the use of specific broadcast options
enforceBroadcastOptionPermissionsInternal( @ullable Bundle options, int callingUid)14398     void enforceBroadcastOptionPermissionsInternal(
14399             @Nullable Bundle options, int callingUid) {
14400         enforceBroadcastOptionPermissionsInternal(BroadcastOptions.fromBundleNullable(options),
14401                 callingUid);
14402     }
14403 
enforceBroadcastOptionPermissionsInternal( @ullable BroadcastOptions options, int callingUid)14404     void enforceBroadcastOptionPermissionsInternal(
14405             @Nullable BroadcastOptions options, int callingUid) {
14406         if (options != null && callingUid != Process.SYSTEM_UID) {
14407             if (options.isAlarmBroadcast()) {
14408                 if (DEBUG_BROADCAST_LIGHT) {
14409                     Slog.w(TAG, "Non-system caller " + callingUid
14410                             + " may not flag broadcast as alarm");
14411                 }
14412                 throw new SecurityException(
14413                         "Non-system callers may not flag broadcasts as alarm");
14414             }
14415             if (options.isInteractive()) {
14416                 enforceCallingPermission(
14417                         android.Manifest.permission.BROADCAST_OPTION_INTERACTIVE,
14418                         "setInteractive");
14419             }
14420         }
14421     }
14422 
14423     @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)14424     final int broadcastIntentLocked(ProcessRecord callerApp,
14425             String callerPackage, String callerFeatureId, Intent intent, String resolvedType,
14426             IIntentReceiver resultTo, int resultCode, String resultData,
14427             Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions,
14428             String[] excludedPackages, int appOp, Bundle bOptions, boolean ordered,
14429             boolean sticky, int callingPid,
14430             int callingUid, int realCallingUid, int realCallingPid, int userId) {
14431         return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent,
14432                 resolvedType, null, resultTo, resultCode, resultData, resultExtras,
14433                 requiredPermissions, excludedPermissions, excludedPackages, appOp, bOptions,
14434                 ordered, sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId,
14435                 BackgroundStartPrivileges.NONE,
14436                 null /* broadcastAllowList */, null /* filterExtrasForReceiver */);
14437     }
14438 
14439     @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)14440     final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage,
14441             @Nullable String callerFeatureId, Intent intent, String resolvedType,
14442             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData,
14443             Bundle resultExtras, String[] requiredPermissions,
14444             String[] excludedPermissions, String[] excludedPackages, int appOp, Bundle bOptions,
14445             boolean ordered, boolean sticky, int callingPid, int callingUid,
14446             int realCallingUid, int realCallingPid, int userId,
14447             BackgroundStartPrivileges backgroundStartPrivileges,
14448             @Nullable int[] broadcastAllowList,
14449             @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) {
14450         final int cookie = BroadcastQueue.traceBegin("broadcastIntentLockedTraced");
14451         final int res = broadcastIntentLockedTraced(callerApp, callerPackage, callerFeatureId,
14452                 intent, resolvedType, resultToApp, resultTo, resultCode, resultData, resultExtras,
14453                 requiredPermissions, excludedPermissions, excludedPackages, appOp,
14454                 BroadcastOptions.fromBundleNullable(bOptions), ordered, sticky,
14455                 callingPid, callingUid, realCallingUid, realCallingPid, userId,
14456                 backgroundStartPrivileges, broadcastAllowList, filterExtrasForReceiver);
14457         BroadcastQueue.traceEnd(cookie);
14458         return res;
14459     }
14460 
14461     @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)14462     final int broadcastIntentLockedTraced(ProcessRecord callerApp, String callerPackage,
14463             @Nullable String callerFeatureId, Intent intent, String resolvedType,
14464             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode, String resultData,
14465             Bundle resultExtras, String[] requiredPermissions,
14466             String[] excludedPermissions, String[] excludedPackages, int appOp,
14467             BroadcastOptions brOptions, boolean ordered, boolean sticky, int callingPid,
14468             int callingUid, int realCallingUid, int realCallingPid, int userId,
14469             BackgroundStartPrivileges backgroundStartPrivileges,
14470             @Nullable int[] broadcastAllowList,
14471             @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver) {
14472         // Ensure all internal loopers are registered for idle checks
14473         BroadcastLoopers.addMyLooper();
14474 
14475         if (Process.isSdkSandboxUid(realCallingUid)) {
14476             final SdkSandboxManagerLocal sdkSandboxManagerLocal = LocalManagerRegistry.getManager(
14477                     SdkSandboxManagerLocal.class);
14478             if (sdkSandboxManagerLocal == null) {
14479                 throw new IllegalStateException("SdkSandboxManagerLocal not found when sending"
14480                         + " a broadcast from an SDK sandbox uid.");
14481             }
14482             if (!sdkSandboxManagerLocal.canSendBroadcast(intent)) {
14483                 throw new SecurityException(
14484                         "Intent " + intent.getAction() + " may not be broadcast from an SDK sandbox"
14485                         + " uid. Given caller package " + callerPackage + " (pid=" + callingPid
14486                         + ", realCallingUid=" + realCallingUid + ", callingUid= " + callingUid
14487                         + ")");
14488             }
14489         }
14490 
14491         if ((resultTo != null) && (resultToApp == null)) {
14492             if (resultTo.asBinder() instanceof BinderProxy) {
14493                 // Warn when requesting results without a way to deliver them
14494                 Slog.wtf(TAG, "Sending broadcast " + intent.getAction()
14495                         + " with resultTo requires resultToApp", new Throwable());
14496             } else {
14497                 // If not a BinderProxy above, then resultTo is an in-process
14498                 // receiver, so splice in system_server process
14499                 resultToApp = getProcessRecordLocked("system", SYSTEM_UID);
14500             }
14501         }
14502 
14503         intent = new Intent(intent);
14504 
14505         final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
14506         // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
14507         if (callerInstantApp) {
14508             intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
14509         }
14510 
14511         if (userId == UserHandle.USER_ALL && broadcastAllowList != null) {
14512                 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. "
14513                         + "Assuming restrictive whitelist.");
14514                 broadcastAllowList = new int[]{};
14515         }
14516 
14517         // By default broadcasts do not go to stopped apps.
14518         intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
14519 
14520         // If we have not finished booting, don't allow this to launch new processes.
14521         if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
14522             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14523         }
14524 
14525         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
14526                 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
14527                         + " ordered=" + ordered + " userid=" + userId
14528                         + " options=" + (brOptions == null ? "null" : brOptions.toBundle()));
14529         if ((resultTo != null) && !ordered) {
14530             if (!mEnableModernQueue) {
14531                 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
14532             }
14533             if (!UserHandle.isCore(callingUid)) {
14534                 String msg = "Unauthorized unordered resultTo broadcast "
14535                              + intent + " sent from uid " + callingUid;
14536                 Slog.w(TAG, msg);
14537                 throw new SecurityException(msg);
14538             }
14539         }
14540 
14541         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
14542                 ALLOW_NON_FULL, "broadcast", callerPackage);
14543 
14544         // Make sure that the user who is receiving this broadcast or its parent is running.
14545         // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
14546         if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
14547             if ((callingUid != SYSTEM_UID
14548                     || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)
14549                     && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
14550                 Slog.w(TAG, "Skipping broadcast of " + intent
14551                         + ": user " + userId + " and its parent (if any) are stopped");
14552                 scheduleCanceledResultTo(resultToApp, resultTo, intent, userId,
14553                         brOptions, callingUid, callerPackage);
14554                 return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
14555             }
14556         }
14557 
14558         final String action = intent.getAction();
14559         if (brOptions != null) {
14560             if (brOptions.getTemporaryAppAllowlistDuration() > 0) {
14561                 // See if the caller is allowed to do this.  Note we are checking against
14562                 // the actual real caller (not whoever provided the operation as say a
14563                 // PendingIntent), because that who is actually supplied the arguments.
14564                 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
14565                         realCallingPid, realCallingUid, -1, true)
14566                         != PackageManager.PERMISSION_GRANTED
14567                         && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND,
14568                         realCallingPid, realCallingUid, -1, true)
14569                         != PackageManager.PERMISSION_GRANTED
14570                         && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND,
14571                         realCallingPid, realCallingUid, -1, true)
14572                         != PackageManager.PERMISSION_GRANTED) {
14573                     String msg = "Permission Denial: " + intent.getAction()
14574                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14575                             + ", uid=" + callingUid + ")"
14576                             + " requires "
14577                             + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or "
14578                             + START_ACTIVITIES_FROM_BACKGROUND + " or "
14579                             + START_FOREGROUND_SERVICES_FROM_BACKGROUND;
14580                     Slog.w(TAG, msg);
14581                     throw new SecurityException(msg);
14582                 }
14583             }
14584             if (brOptions.isDontSendToRestrictedApps()
14585                     && !isUidActiveLOSP(callingUid)
14586                     && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
14587                 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
14588                         + " has background restrictions");
14589                 return ActivityManager.START_CANCELED;
14590             }
14591             if (brOptions.allowsBackgroundActivityStarts()) {
14592                 // See if the caller is allowed to do this.  Note we are checking against
14593                 // the actual real caller (not whoever provided the operation as say a
14594                 // PendingIntent), because that who is actually supplied the arguments.
14595                 if (checkComponentPermission(
14596                         android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
14597                         realCallingPid, realCallingUid, -1, true)
14598                         != PackageManager.PERMISSION_GRANTED) {
14599                     String msg = "Permission Denial: " + intent.getAction()
14600                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14601                             + ", uid=" + callingUid + ")"
14602                             + " requires "
14603                             + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
14604                     Slog.w(TAG, msg);
14605                     throw new SecurityException(msg);
14606                 } else {
14607                     // We set the token to null since if it wasn't for it we'd allow anyway here
14608                     backgroundStartPrivileges = BackgroundStartPrivileges.ALLOW_BAL;
14609                 }
14610             }
14611 
14612             if (brOptions.getIdForResponseEvent() > 0) {
14613                 enforcePermission(android.Manifest.permission.ACCESS_BROADCAST_RESPONSE_STATS,
14614                         callingPid, callingUid, "recordResponseEventWhileInBackground");
14615             }
14616         }
14617 
14618         // Verify that protected broadcasts are only being sent by system code,
14619         // and that system code is only sending protected broadcasts.
14620         final boolean isProtectedBroadcast;
14621         try {
14622             isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
14623         } catch (RemoteException e) {
14624             Slog.w(TAG, "Remote exception", e);
14625             scheduleCanceledResultTo(resultToApp, resultTo, intent,
14626                     userId, brOptions, callingUid, callerPackage);
14627             return ActivityManager.BROADCAST_SUCCESS;
14628         }
14629 
14630         final boolean isCallerSystem;
14631         switch (UserHandle.getAppId(callingUid)) {
14632             case ROOT_UID:
14633             case SYSTEM_UID:
14634             case PHONE_UID:
14635             case BLUETOOTH_UID:
14636             case NFC_UID:
14637             case SE_UID:
14638             case NETWORK_STACK_UID:
14639                 isCallerSystem = true;
14640                 break;
14641             default:
14642                 isCallerSystem = (callerApp != null) && callerApp.isPersistent();
14643                 break;
14644         }
14645 
14646         // First line security check before anything else: stop non-system apps from
14647         // sending protected broadcasts.
14648         if (!isCallerSystem) {
14649             if (isProtectedBroadcast) {
14650                 String msg = "Permission Denial: not allowed to send broadcast "
14651                         + action + " from pid="
14652                         + callingPid + ", uid=" + callingUid;
14653                 Slog.w(TAG, msg);
14654                 throw new SecurityException(msg);
14655 
14656             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14657                     || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
14658                 // Special case for compatibility: we don't want apps to send this,
14659                 // but historically it has not been protected and apps may be using it
14660                 // to poke their own app widget.  So, instead of making it protected,
14661                 // just limit it to the caller.
14662                 if (callerPackage == null) {
14663                     String msg = "Permission Denial: not allowed to send broadcast "
14664                             + action + " from unknown caller.";
14665                     Slog.w(TAG, msg);
14666                     throw new SecurityException(msg);
14667                 } else if (intent.getComponent() != null) {
14668                     // They are good enough to send to an explicit component...  verify
14669                     // it is being sent to the calling app.
14670                     if (!intent.getComponent().getPackageName().equals(
14671                             callerPackage)) {
14672                         String msg = "Permission Denial: not allowed to send broadcast "
14673                                 + action + " to "
14674                                 + intent.getComponent().getPackageName() + " from "
14675                                 + callerPackage;
14676                         Slog.w(TAG, msg);
14677                         throw new SecurityException(msg);
14678                     }
14679                 } else {
14680                     // Limit broadcast to their own package.
14681                     intent.setPackage(callerPackage);
14682                 }
14683             }
14684         }
14685 
14686         boolean timeoutExempt = false;
14687 
14688         if (action != null) {
14689             if (getBackgroundLaunchBroadcasts().contains(action)) {
14690                 if (DEBUG_BACKGROUND_CHECK) {
14691                     Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
14692                 }
14693                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
14694             }
14695 
14696             switch (action) {
14697                 case Intent.ACTION_MEDIA_SCANNER_SCAN_FILE:
14698                     UserManagerInternal umInternal = LocalServices.getService(
14699                             UserManagerInternal.class);
14700                     UserInfo userInfo = umInternal.getUserInfo(userId);
14701                     if (userInfo != null && userInfo.isCloneProfile()) {
14702                         userId = umInternal.getProfileParentId(userId);
14703                     }
14704                     break;
14705                 case Intent.ACTION_UID_REMOVED:
14706                 case Intent.ACTION_PACKAGE_REMOVED:
14707                 case Intent.ACTION_PACKAGE_CHANGED:
14708                 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
14709                 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
14710                 case Intent.ACTION_PACKAGES_SUSPENDED:
14711                 case Intent.ACTION_PACKAGES_UNSUSPENDED:
14712                     // Handle special intents: if this broadcast is from the package
14713                     // manager about a package being removed, we need to remove all of
14714                     // its activities from the history stack.
14715                     if (checkComponentPermission(
14716                             android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
14717                             callingPid, callingUid, -1, true)
14718                             != PackageManager.PERMISSION_GRANTED) {
14719                         String msg = "Permission Denial: " + intent.getAction()
14720                                 + " broadcast from " + callerPackage + " (pid=" + callingPid
14721                                 + ", uid=" + callingUid + ")"
14722                                 + " requires "
14723                                 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
14724                         Slog.w(TAG, msg);
14725                         throw new SecurityException(msg);
14726                     }
14727                     switch (action) {
14728                         case Intent.ACTION_UID_REMOVED:
14729                             final int uid = getUidFromIntent(intent);
14730                             if (uid >= 0) {
14731                                 mBatteryStatsService.removeUid(uid);
14732                                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
14733                                     mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
14734                                             intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
14735                                 } else {
14736                                     mAppOpsService.uidRemoved(uid);
14737                                 }
14738                             }
14739                             break;
14740                         case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
14741                             // If resources are unavailable just force stop all those packages
14742                             // and flush the attribute cache as well.
14743                             String list[] =
14744                                     intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
14745                             if (list != null && list.length > 0) {
14746                                 for (int i = 0; i < list.length; i++) {
14747                                     forceStopPackageLocked(list[i], -1, false, true, true,
14748                                             false, false, userId, "storage unmount");
14749                                 }
14750                                 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
14751                                 sendPackageBroadcastLocked(
14752                                         ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
14753                                         list, userId);
14754                             }
14755                             break;
14756                         case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
14757                             mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
14758                             break;
14759                         case Intent.ACTION_PACKAGE_REMOVED:
14760                         case Intent.ACTION_PACKAGE_CHANGED:
14761                             Uri data = intent.getData();
14762                             String ssp;
14763                             if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
14764                                 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
14765                                 final boolean replacing =
14766                                         intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
14767                                 final boolean killProcess =
14768                                         !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
14769                                 final boolean fullUninstall = removed && !replacing;
14770 
14771                                 if (removed) {
14772                                     if (killProcess) {
14773                                         forceStopPackageLocked(ssp, UserHandle.getAppId(
14774                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
14775                                                 false, true, true, false, fullUninstall, userId,
14776                                                 "pkg removed");
14777                                         getPackageManagerInternal()
14778                                                 .onPackageProcessKilledForUninstall(ssp);
14779                                     } else {
14780                                         // Kill any app zygotes always, since they can't fork new
14781                                         // processes with references to the old code
14782                                         forceStopAppZygoteLocked(ssp, UserHandle.getAppId(
14783                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
14784                                                 userId);
14785                                     }
14786                                     final int cmd = killProcess
14787                                             ? ApplicationThreadConstants.PACKAGE_REMOVED
14788                                             : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
14789                                     sendPackageBroadcastLocked(cmd,
14790                                             new String[] {ssp}, userId);
14791                                     if (fullUninstall) {
14792                                         // Remove all permissions granted from/to this package
14793                                         mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
14794                                                 true, false);
14795 
14796                                         mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
14797 
14798                                         mServices.forceStopPackageLocked(ssp, userId);
14799                                         mAtmInternal.onPackageUninstalled(ssp, userId);
14800                                         mBatteryStatsService.notePackageUninstalled(ssp);
14801                                     }
14802                                 } else {
14803                                     if (killProcess) {
14804                                         int reason;
14805                                         int subReason;
14806                                         if (replacing) {
14807                                             reason = ApplicationExitInfo.REASON_PACKAGE_UPDATED;
14808                                             subReason = ApplicationExitInfo.SUBREASON_UNKNOWN;
14809                                         } else {
14810                                             reason =
14811                                                     ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE;
14812                                             subReason = ApplicationExitInfo.SUBREASON_UNKNOWN;
14813                                         }
14814 
14815                                         final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
14816                                                 -1);
14817                                         synchronized (mProcLock) {
14818                                             mProcessList.killPackageProcessesLSP(ssp,
14819                                                     UserHandle.getAppId(extraUid),
14820                                                     userId, ProcessList.INVALID_ADJ,
14821                                                     reason,
14822                                                     subReason,
14823                                                     "change " + ssp);
14824                                         }
14825                                     }
14826                                     cleanupDisabledPackageComponentsLocked(ssp, userId,
14827                                             intent.getStringArrayExtra(
14828                                                     Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
14829                                     mServices.schedulePendingServiceStartLocked(ssp, userId);
14830                                 }
14831                             }
14832                             break;
14833                         case Intent.ACTION_PACKAGES_SUSPENDED:
14834                         case Intent.ACTION_PACKAGES_UNSUSPENDED:
14835                             final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
14836                                     intent.getAction());
14837                             final String[] packageNames = intent.getStringArrayExtra(
14838                                     Intent.EXTRA_CHANGED_PACKAGE_LIST);
14839                             final int userIdExtra = intent.getIntExtra(
14840                                     Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
14841 
14842                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
14843                                     userIdExtra);
14844                             break;
14845                     }
14846                     break;
14847                 case Intent.ACTION_PACKAGE_REPLACED:
14848                 {
14849                     final Uri data = intent.getData();
14850                     final String ssp;
14851                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
14852                         ApplicationInfo aInfo = null;
14853                         try {
14854                             aInfo = AppGlobals.getPackageManager()
14855                                     .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
14856                         } catch (RemoteException ignore) {}
14857                         if (aInfo == null) {
14858                             Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
14859                                     + " ssp=" + ssp + " data=" + data);
14860                             scheduleCanceledResultTo(resultToApp, resultTo, intent,
14861                                     userId, brOptions, callingUid, callerPackage);
14862                             return ActivityManager.BROADCAST_SUCCESS;
14863                         }
14864                         updateAssociationForApp(aInfo);
14865                         mAtmInternal.onPackageReplaced(aInfo);
14866                         mServices.updateServiceApplicationInfoLocked(aInfo);
14867                         sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
14868                                 new String[] {ssp}, userId);
14869                     }
14870                     break;
14871                 }
14872                 case Intent.ACTION_PACKAGE_ADDED:
14873                 {
14874                     // Special case for adding a package: by default turn on compatibility mode.
14875                     Uri data = intent.getData();
14876                     String ssp;
14877                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
14878                         final boolean replacing =
14879                                 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
14880                         mAtmInternal.onPackageAdded(ssp, replacing);
14881 
14882                         try {
14883                             ApplicationInfo ai = AppGlobals.getPackageManager().
14884                                     getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
14885                             mBatteryStatsService.notePackageInstalled(ssp,
14886                                     ai != null ? ai.longVersionCode : 0);
14887                         } catch (RemoteException e) {
14888                         }
14889                     }
14890                     break;
14891                 }
14892                 case Intent.ACTION_PACKAGE_DATA_CLEARED:
14893                 {
14894                     Uri data = intent.getData();
14895                     String ssp;
14896                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
14897                         mAtmInternal.onPackageDataCleared(ssp, userId);
14898                     }
14899                     break;
14900                 }
14901                 case Intent.ACTION_TIMEZONE_CHANGED:
14902                     // If this is the time zone changed action, queue up a message that will reset
14903                     // the timezone of all currently running processes. This message will get
14904                     // queued up before the broadcast happens.
14905                     mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
14906                     break;
14907                 case Intent.ACTION_TIME_CHANGED:
14908                     // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
14909                     // the tri-state value it may contain and "unknown".
14910                     // For convenience we re-use the Intent extra values.
14911                     final int NO_EXTRA_VALUE_FOUND = -1;
14912                     final int timeFormatPreferenceMsgValue = intent.getIntExtra(
14913                             Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
14914                             NO_EXTRA_VALUE_FOUND /* defaultValue */);
14915                     // Only send a message if the time preference is available.
14916                     if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
14917                         Message updateTimePreferenceMsg =
14918                                 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
14919                                         timeFormatPreferenceMsgValue, 0);
14920                         mHandler.sendMessage(updateTimePreferenceMsg);
14921                     }
14922                     mBatteryStatsService.noteCurrentTimeChanged();
14923                     break;
14924                 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE:
14925                     mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
14926                     break;
14927                 case Proxy.PROXY_CHANGE_ACTION:
14928                     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
14929                     break;
14930                 case android.hardware.Camera.ACTION_NEW_PICTURE:
14931                 case android.hardware.Camera.ACTION_NEW_VIDEO:
14932                     // In N we just turned these off; in O we are turing them back on partly,
14933                     // only for registered receivers.  This will still address the main problem
14934                     // (a spam of apps waking up when a picture is taken putting significant
14935                     // memory pressure on the system at a bad point), while still allowing apps
14936                     // that are already actively running to know about this happening.
14937                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14938                     break;
14939                 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
14940                     mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
14941                     break;
14942                 case "com.android.launcher.action.INSTALL_SHORTCUT":
14943                     // As of O, we no longer support this broadcasts, even for pre-O apps.
14944                     // Apps should now be using ShortcutManager.pinRequestShortcut().
14945                     Log.w(TAG, "Broadcast " + action
14946                             + " no longer supported. It will not be delivered.");
14947                     scheduleCanceledResultTo(resultToApp, resultTo, intent,
14948                             userId, brOptions, callingUid, callerPackage);
14949                     return ActivityManager.BROADCAST_SUCCESS;
14950                 case Intent.ACTION_PRE_BOOT_COMPLETED:
14951                     timeoutExempt = true;
14952                     break;
14953                 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
14954                     if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid,
14955                             callerPackage)) {
14956                         scheduleCanceledResultTo(resultToApp, resultTo, intent,
14957                                 userId, brOptions, callingUid, callerPackage);
14958                         // Returning success seems to be the pattern here
14959                         return ActivityManager.BROADCAST_SUCCESS;
14960                     }
14961                     break;
14962             }
14963 
14964             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
14965                     Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
14966                     Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
14967                 final int uid = getUidFromIntent(intent);
14968                 if (uid != -1) {
14969                     final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
14970                     if (uidRec != null) {
14971                         uidRec.updateHasInternetPermission();
14972                     }
14973                 }
14974             }
14975         }
14976 
14977         final int callerAppProcessState = getRealProcessStateLocked(callerApp, realCallingPid);
14978         // Add to the sticky list if requested.
14979         if (sticky) {
14980             if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
14981                     callingPid, callingUid)
14982                     != PackageManager.PERMISSION_GRANTED) {
14983                 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
14984                         + callingPid + ", uid=" + callingUid
14985                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
14986                 Slog.w(TAG, msg);
14987                 throw new SecurityException(msg);
14988             }
14989             if (requiredPermissions != null && requiredPermissions.length > 0) {
14990                 Slog.w(TAG, "Can't broadcast sticky intent " + intent
14991                         + " and enforce permissions " + Arrays.toString(requiredPermissions));
14992                 scheduleCanceledResultTo(resultToApp, resultTo, intent,
14993                         userId, brOptions, callingUid, callerPackage);
14994                 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
14995             }
14996             if (intent.getComponent() != null) {
14997                 throw new SecurityException(
14998                         "Sticky broadcasts can't target a specific component");
14999             }
15000             // We use userId directly here, since the "all" target is maintained
15001             // as a separate set of sticky broadcasts.
15002             if (userId != UserHandle.USER_ALL) {
15003                 // But first, if this is not a broadcast to all users, then
15004                 // make sure it doesn't conflict with an existing broadcast to
15005                 // all users.
15006                 ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(
15007                         UserHandle.USER_ALL);
15008                 if (stickies != null) {
15009                     ArrayList<StickyBroadcast> list = stickies.get(intent.getAction());
15010                     if (list != null) {
15011                         int N = list.size();
15012                         int i;
15013                         for (i=0; i<N; i++) {
15014                             if (intent.filterEquals(list.get(i).intent)) {
15015                                 throw new IllegalArgumentException(
15016                                         "Sticky broadcast " + intent + " for user "
15017                                         + userId + " conflicts with existing global broadcast");
15018                             }
15019                         }
15020                     }
15021                 }
15022             }
15023             ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(userId);
15024             if (stickies == null) {
15025                 stickies = new ArrayMap<>();
15026                 mStickyBroadcasts.put(userId, stickies);
15027             }
15028             ArrayList<StickyBroadcast> list = stickies.get(intent.getAction());
15029             if (list == null) {
15030                 list = new ArrayList<>();
15031                 stickies.put(intent.getAction(), list);
15032             }
15033             final boolean deferUntilActive = BroadcastRecord.calculateDeferUntilActive(
15034                     callingUid, brOptions, resultTo, ordered,
15035                     BroadcastRecord.calculateUrgent(intent, brOptions));
15036             final int stickiesCount = list.size();
15037             int i;
15038             for (i = 0; i < stickiesCount; i++) {
15039                 if (intent.filterEquals(list.get(i).intent)) {
15040                     // This sticky already exists, replace it.
15041                     list.set(i, StickyBroadcast.create(new Intent(intent), deferUntilActive,
15042                             callingUid, callerAppProcessState));
15043                     break;
15044                 }
15045             }
15046             if (i >= stickiesCount) {
15047                 list.add(StickyBroadcast.create(new Intent(intent), deferUntilActive, callingUid,
15048                         callerAppProcessState));
15049             }
15050         }
15051 
15052         int[] users;
15053         if (userId == UserHandle.USER_ALL) {
15054             // Caller wants broadcast to go to all started users.
15055             users = mUserController.getStartedUserArray();
15056         } else {
15057             // Caller wants broadcast to go to one specific user.
15058             users = new int[] {userId};
15059         }
15060 
15061         // Figure out who all will receive this broadcast.
15062         final int cookie = BroadcastQueue.traceBegin("queryReceivers");
15063         List receivers = null;
15064         List<BroadcastFilter> registeredReceivers = null;
15065         // Need to resolve the intent to interested receivers...
15066         if ((intent.getFlags() & Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15067             receivers = collectReceiverComponents(
15068                     intent, resolvedType, callingUid, users, broadcastAllowList);
15069         }
15070         if (intent.getComponent() == null) {
15071             final PackageDataSnapshot snapshot = getPackageManagerInternal().snapshot();
15072             if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
15073                 // Query one target user at a time, excluding shell-restricted users
15074                 for (int i = 0; i < users.length; i++) {
15075                     if (mUserController.hasUserRestriction(
15076                             UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
15077                         continue;
15078                     }
15079                     List<BroadcastFilter> registeredReceiversForUser =
15080                             mReceiverResolver.queryIntent(snapshot, intent,
15081                                     resolvedType, false /*defaultOnly*/, users[i]);
15082                     if (registeredReceivers == null) {
15083                         registeredReceivers = registeredReceiversForUser;
15084                     } else if (registeredReceiversForUser != null) {
15085                         registeredReceivers.addAll(registeredReceiversForUser);
15086                     }
15087                 }
15088             } else {
15089                 registeredReceivers = mReceiverResolver.queryIntent(snapshot, intent,
15090                         resolvedType, false /*defaultOnly*/, userId);
15091             }
15092         }
15093         BroadcastQueue.traceEnd(cookie);
15094 
15095         final boolean replacePending =
15096                 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
15097 
15098         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
15099                 + " replacePending=" + replacePending);
15100         if (registeredReceivers != null && broadcastAllowList != null) {
15101             // if a uid whitelist was provided, remove anything in the application space that wasn't
15102             // in it.
15103             for (int i = registeredReceivers.size() - 1; i >= 0; i--) {
15104                 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid);
15105                 if (owningAppId >= Process.FIRST_APPLICATION_UID
15106                         && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) {
15107                     registeredReceivers.remove(i);
15108                 }
15109             }
15110         }
15111 
15112         filterNonExportedComponents(intent, callingUid, callingPid, registeredReceivers,
15113                 mPlatformCompat, callerPackage, resolvedType);
15114         int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
15115         if (!ordered && NR > 0 && !mEnableModernQueue) {
15116             // If we are not serializing this broadcast, then send the
15117             // registered receivers separately so they don't wait for the
15118             // components to be launched. We don't do this split for the modern
15119             // queue because delivery to registered receivers isn't blocked
15120             // behind manifest receivers.
15121             if (isCallerSystem) {
15122                 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15123                         isProtectedBroadcast, registeredReceivers);
15124             }
15125             final BroadcastQueue queue = broadcastQueueForIntent(intent);
15126             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
15127                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
15128                     requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
15129                     registeredReceivers, resultToApp, resultTo, resultCode, resultData,
15130                     resultExtras, ordered, sticky, false, userId,
15131                     backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver,
15132                     callerAppProcessState);
15133             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
15134             queue.enqueueBroadcastLocked(r);
15135             registeredReceivers = null;
15136             NR = 0;
15137         }
15138 
15139         // Merge into one list.
15140         int ir = 0;
15141         if (receivers != null) {
15142             // A special case for PACKAGE_ADDED: do not allow the package
15143             // being added to see this broadcast.  This prevents them from
15144             // using this as a back door to get run as soon as they are
15145             // installed.  Maybe in the future we want to have a special install
15146             // broadcast or such for apps, but we'd like to deliberately make
15147             // this decision.
15148             String skipPackages[] = null;
15149             if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
15150                     || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
15151                     || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
15152                 Uri data = intent.getData();
15153                 if (data != null) {
15154                     String pkgName = data.getSchemeSpecificPart();
15155                     if (pkgName != null) {
15156                         skipPackages = new String[] { pkgName };
15157                     }
15158                 }
15159             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
15160                 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15161             }
15162             if (skipPackages != null && (skipPackages.length > 0)) {
15163                 for (String skipPackage : skipPackages) {
15164                     if (skipPackage != null) {
15165                         int NT = receivers.size();
15166                         for (int it=0; it<NT; it++) {
15167                             ResolveInfo curt = (ResolveInfo)receivers.get(it);
15168                             if (curt.activityInfo.packageName.equals(skipPackage)) {
15169                                 receivers.remove(it);
15170                                 it--;
15171                                 NT--;
15172                             }
15173                         }
15174                     }
15175                 }
15176             }
15177 
15178             int NT = receivers != null ? receivers.size() : 0;
15179             int it = 0;
15180             ResolveInfo curt = null;
15181             BroadcastFilter curr = null;
15182             while (it < NT && ir < NR) {
15183                 if (curt == null) {
15184                     curt = (ResolveInfo)receivers.get(it);
15185                 }
15186                 if (curr == null) {
15187                     curr = registeredReceivers.get(ir);
15188                 }
15189                 if (curr.getPriority() >= curt.priority) {
15190                     // Insert this broadcast record into the final list.
15191                     receivers.add(it, curr);
15192                     ir++;
15193                     curr = null;
15194                     it++;
15195                     NT++;
15196                 } else {
15197                     // Skip to the next ResolveInfo in the final list.
15198                     it++;
15199                     curt = null;
15200                 }
15201             }
15202         }
15203         while (ir < NR) {
15204             if (receivers == null) {
15205                 receivers = new ArrayList();
15206             }
15207             receivers.add(registeredReceivers.get(ir));
15208             ir++;
15209         }
15210 
15211         if (isCallerSystem) {
15212             checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15213                     isProtectedBroadcast, receivers);
15214         }
15215 
15216         if ((receivers != null && receivers.size() > 0)
15217                 || resultTo != null) {
15218             BroadcastQueue queue = broadcastQueueForIntent(intent);
15219             filterNonExportedComponents(intent, callingUid, callingPid, receivers,
15220                     mPlatformCompat, callerPackage, resolvedType);
15221             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
15222                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
15223                     requiredPermissions, excludedPermissions, excludedPackages, appOp, brOptions,
15224                     receivers, resultToApp, resultTo, resultCode, resultData, resultExtras,
15225                     ordered, sticky, false, userId,
15226                     backgroundStartPrivileges, timeoutExempt, filterExtrasForReceiver,
15227                     callerAppProcessState);
15228 
15229             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
15230             queue.enqueueBroadcastLocked(r);
15231         } else {
15232             // There was nobody interested in the broadcast, but we still want to record
15233             // that it happened.
15234             if (intent.getComponent() == null && intent.getPackage() == null
15235                     && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15236                 // This was an implicit broadcast... let's record it for posterity.
15237                 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
15238             }
15239         }
15240 
15241         return ActivityManager.BROADCAST_SUCCESS;
15242     }
15243 
15244     @GuardedBy("this")
scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo, Intent intent, int userId, BroadcastOptions options, int callingUid, String callingPackage)15245     private void scheduleCanceledResultTo(ProcessRecord resultToApp, IIntentReceiver resultTo,
15246             Intent intent, int userId, BroadcastOptions options, int callingUid,
15247             String callingPackage) {
15248         if (resultTo == null) {
15249             return;
15250         }
15251         final ProcessRecord app = resultToApp;
15252         final IApplicationThread thread  = (app != null) ? app.getOnewayThread() : null;
15253         if (thread != null) {
15254             try {
15255                 final boolean shareIdentity = (options != null && options.isShareIdentityEnabled());
15256                 thread.scheduleRegisteredReceiver(
15257                         resultTo, intent, Activity.RESULT_CANCELED, null, null,
15258                         false, false, true, userId, app.mState.getReportedProcState(),
15259                         shareIdentity ? callingUid : Process.INVALID_UID,
15260                         shareIdentity ? callingPackage : null);
15261             } catch (RemoteException e) {
15262                 final String msg = "Failed to schedule result of " + intent + " via "
15263                         + app + ": " + e;
15264                 app.killLocked("Can't schedule resultTo", ApplicationExitInfo.REASON_OTHER,
15265                         ApplicationExitInfo.SUBREASON_UNDELIVERED_BROADCAST, true);
15266                 Slog.d(TAG, msg);
15267             }
15268         }
15269     }
15270 
15271     @GuardedBy("this")
getRealProcessStateLocked(ProcessRecord app, int pid)15272     private int getRealProcessStateLocked(ProcessRecord app, int pid) {
15273         if (app == null) {
15274             synchronized (mPidsSelfLocked) {
15275                 app = mPidsSelfLocked.get(pid);
15276             }
15277         }
15278         if (app != null && app.getThread() != null && !app.isKilled()) {
15279             return app.mState.getCurProcState();
15280         }
15281         return PROCESS_STATE_NONEXISTENT;
15282     }
15283 
15284     @VisibleForTesting
getStickyBroadcasts(String action, int userId)15285     ArrayList<StickyBroadcast> getStickyBroadcasts(String action, int userId) {
15286         final ArrayMap<String, ArrayList<StickyBroadcast>> stickyBroadcasts =
15287                 mStickyBroadcasts.get(userId);
15288         if (stickyBroadcasts == null) {
15289             return null;
15290         }
15291         return stickyBroadcasts.get(action);
15292     }
15293 
15294     /**
15295      * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1
15296      */
getUidFromIntent(Intent intent)15297     private int getUidFromIntent(Intent intent) {
15298         if (intent == null) {
15299             return -1;
15300         }
15301         final Bundle intentExtras = intent.getExtras();
15302         return intent.hasExtra(Intent.EXTRA_UID)
15303                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
15304     }
15305 
rotateBroadcastStatsIfNeededLocked()15306     final void rotateBroadcastStatsIfNeededLocked() {
15307         final long now = SystemClock.elapsedRealtime();
15308         if (mCurBroadcastStats == null ||
15309                 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) {
15310             mLastBroadcastStats = mCurBroadcastStats;
15311             if (mLastBroadcastStats != null) {
15312                 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime();
15313                 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis();
15314             }
15315             mCurBroadcastStats = new BroadcastStats();
15316         }
15317     }
15318 
addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)15319     final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount,
15320             int skipCount, long dispatchTime) {
15321         rotateBroadcastStatsIfNeededLocked();
15322         mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime);
15323     }
15324 
addBackgroundCheckViolationLocked(String action, String targetPackage)15325     final void addBackgroundCheckViolationLocked(String action, String targetPackage) {
15326         rotateBroadcastStatsIfNeededLocked();
15327         mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage);
15328     }
15329 
notifyBroadcastFinishedLocked(@onNull BroadcastRecord original)15330     final void notifyBroadcastFinishedLocked(@NonNull BroadcastRecord original) {
15331         final ApplicationInfo info = original.callerApp != null ? original.callerApp.info : null;
15332         final String callerPackage = info != null ? info.packageName : original.callerPackage;
15333         if (callerPackage != null) {
15334             mHandler.obtainMessage(ActivityManagerService.DISPATCH_SENDING_BROADCAST_EVENT,
15335                     original.callingUid, 0, callerPackage).sendToTarget();
15336         }
15337     }
15338 
verifyBroadcastLocked(Intent intent)15339     final Intent verifyBroadcastLocked(Intent intent) {
15340         // Refuse possible leaked file descriptors
15341         if (intent != null && intent.hasFileDescriptors() == true) {
15342             throw new IllegalArgumentException("File descriptors passed in Intent");
15343         }
15344 
15345         int flags = intent.getFlags();
15346 
15347         if (!mProcessesReady) {
15348             // if the caller really truly claims to know what they're doing, go
15349             // ahead and allow the broadcast without launching any receivers
15350             if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
15351                 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
15352             } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15353                 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
15354                         + " before boot completion");
15355                 throw new IllegalStateException("Cannot broadcast before boot completed");
15356             }
15357         }
15358 
15359         if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
15360             throw new IllegalArgumentException(
15361                     "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
15362         }
15363 
15364         if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
15365             switch (Binder.getCallingUid()) {
15366                 case ROOT_UID:
15367                 case SHELL_UID:
15368                     break;
15369                 default:
15370                     Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
15371                             + Binder.getCallingUid());
15372                     intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
15373                     break;
15374             }
15375         }
15376 
15377         return intent;
15378     }
15379 
15380     /**
15381      * @deprecated Use {@link #broadcastIntentWithFeature}
15382      */
15383     @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)15384     public final int broadcastIntent(IApplicationThread caller,
15385             Intent intent, String resolvedType, IIntentReceiver resultTo,
15386             int resultCode, String resultData, Bundle resultExtras,
15387             String[] requiredPermissions, int appOp, Bundle bOptions,
15388             boolean serialized, boolean sticky, int userId) {
15389         return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode,
15390                 resultData, resultExtras, requiredPermissions, null, null, appOp, bOptions,
15391                 serialized, sticky, userId);
15392     }
15393 
15394     @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)15395     public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId,
15396             Intent intent, String resolvedType, IIntentReceiver resultTo,
15397             int resultCode, String resultData, Bundle resultExtras,
15398             String[] requiredPermissions, String[] excludedPermissions,
15399             String[] excludedPackages, int appOp, Bundle bOptions,
15400             boolean serialized, boolean sticky, int userId) {
15401         enforceNotIsolatedCaller("broadcastIntent");
15402         synchronized(this) {
15403             intent = verifyBroadcastLocked(intent);
15404 
15405             final ProcessRecord callerApp = getRecordForAppLOSP(caller);
15406             final int callingPid = Binder.getCallingPid();
15407             final int callingUid = Binder.getCallingUid();
15408 
15409             // We're delivering the result to the caller
15410             final ProcessRecord resultToApp = callerApp;
15411 
15412             // Permission regimes around sender-supplied broadcast options.
15413             enforceBroadcastOptionPermissionsInternal(bOptions, callingUid);
15414 
15415             final long origId = Binder.clearCallingIdentity();
15416             try {
15417                 return broadcastIntentLocked(callerApp,
15418                         callerApp != null ? callerApp.info.packageName : null, callingFeatureId,
15419                         intent, resolvedType, resultToApp, resultTo, resultCode, resultData,
15420                         resultExtras, requiredPermissions, excludedPermissions, excludedPackages,
15421                         appOp, bOptions, serialized, sticky, callingPid, callingUid, callingUid,
15422                         callingPid, userId, BackgroundStartPrivileges.NONE, null, null);
15423             } finally {
15424                 Binder.restoreCallingIdentity(origId);
15425             }
15426         }
15427     }
15428 
15429     // 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)15430     int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
15431             int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
15432             ProcessRecord resultToApp, IIntentReceiver resultTo, int resultCode,
15433             String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions,
15434             boolean serialized, boolean sticky, int userId,
15435             BackgroundStartPrivileges backgroundStartPrivileges,
15436             @Nullable int[] broadcastAllowList) {
15437         synchronized(this) {
15438             intent = verifyBroadcastLocked(intent);
15439 
15440             final long origId = Binder.clearCallingIdentity();
15441             String[] requiredPermissions = requiredPermission == null ? null
15442                     : new String[] {requiredPermission};
15443             try {
15444                 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType,
15445                         resultToApp, resultTo, resultCode, resultData, resultExtras,
15446                         requiredPermissions, null, null, OP_NONE, bOptions, serialized, sticky, -1,
15447                         uid, realCallingUid, realCallingPid, userId,
15448                         backgroundStartPrivileges, broadcastAllowList,
15449                         null /* filterExtrasForReceiver */);
15450             } finally {
15451                 Binder.restoreCallingIdentity(origId);
15452             }
15453         }
15454     }
15455 
unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)15456     public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
15457         // Refuse possible leaked file descriptors
15458         if (intent != null && intent.hasFileDescriptors() == true) {
15459             throw new IllegalArgumentException("File descriptors passed in Intent");
15460         }
15461 
15462         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15463                 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
15464 
15465         synchronized(this) {
15466             if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
15467                     != PackageManager.PERMISSION_GRANTED) {
15468                 String msg = "Permission Denial: unbroadcastIntent() from pid="
15469                         + Binder.getCallingPid()
15470                         + ", uid=" + Binder.getCallingUid()
15471                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15472                 Slog.w(TAG, msg);
15473                 throw new SecurityException(msg);
15474             }
15475             ArrayMap<String, ArrayList<StickyBroadcast>> stickies = mStickyBroadcasts.get(userId);
15476             if (stickies != null) {
15477                 ArrayList<StickyBroadcast> list = stickies.get(intent.getAction());
15478                 if (list != null) {
15479                     int N = list.size();
15480                     int i;
15481                     for (i=0; i<N; i++) {
15482                         if (intent.filterEquals(list.get(i).intent)) {
15483                             list.remove(i);
15484                             break;
15485                         }
15486                     }
15487                     if (list.size() <= 0) {
15488                         stickies.remove(intent.getAction());
15489                     }
15490                 }
15491                 if (stickies.size() <= 0) {
15492                     mStickyBroadcasts.remove(userId);
15493                 }
15494             }
15495         }
15496     }
15497 
backgroundServicesFinishedLocked(int userId)15498     void backgroundServicesFinishedLocked(int userId) {
15499         for (BroadcastQueue queue : mBroadcastQueues) {
15500             queue.backgroundServicesFinishedLocked(userId);
15501         }
15502     }
15503 
finishReceiver(IBinder caller, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)15504     public void finishReceiver(IBinder caller, int resultCode, String resultData,
15505             Bundle resultExtras, boolean resultAbort, int flags) {
15506         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + caller);
15507 
15508         // Refuse possible leaked file descriptors
15509         if (resultExtras != null && resultExtras.hasFileDescriptors()) {
15510             throw new IllegalArgumentException("File descriptors passed in Bundle");
15511         }
15512 
15513         final long origId = Binder.clearCallingIdentity();
15514         try {
15515             synchronized(this) {
15516                 final ProcessRecord callerApp = getRecordForAppLOSP(caller);
15517                 if (callerApp == null) {
15518                     Slog.w(TAG, "finishReceiver: no app for " + caller);
15519                     return;
15520                 }
15521 
15522                 final BroadcastQueue queue = broadcastQueueForFlags(flags);
15523                 queue.finishReceiverLocked(callerApp, resultCode,
15524                         resultData, resultExtras, resultAbort, true);
15525                 // updateOomAdjLocked() will be done here
15526                 trimApplicationsLocked(false, OOM_ADJ_REASON_FINISH_RECEIVER);
15527             }
15528 
15529         } finally {
15530             Binder.restoreCallingIdentity(origId);
15531         }
15532     }
15533 
15534     // =========================================================
15535     // INSTRUMENTATION
15536     // =========================================================
15537 
startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)15538     public boolean startInstrumentation(ComponentName className,
15539             String profileFile, int flags, Bundle arguments,
15540             IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
15541             int userId, String abiOverride) {
15542         enforceNotIsolatedCaller("startInstrumentation");
15543         final int callingUid = Binder.getCallingUid();
15544         final int callingPid = Binder.getCallingPid();
15545         userId = mUserController.handleIncomingUser(callingPid, callingUid,
15546                 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
15547         // Refuse possible leaked file descriptors
15548         if (arguments != null && arguments.hasFileDescriptors()) {
15549             throw new IllegalArgumentException("File descriptors passed in Bundle");
15550         }
15551         final IPackageManager pm = AppGlobals.getPackageManager();
15552 
15553         synchronized(this) {
15554             InstrumentationInfo ii = null;
15555             ApplicationInfo ai = null;
15556 
15557             boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0;
15558 
15559             try {
15560                 ii = pm.getInstrumentationInfoAsUser(className, STOCK_PM_FLAGS, userId);
15561                 if (ii == null) {
15562                     reportStartInstrumentationFailureLocked(watcher, className,
15563                             "Unable to find instrumentation info for: " + className);
15564                     return false;
15565                 }
15566                 ai = pm.getApplicationInfo(ii.targetPackage, STOCK_PM_FLAGS, userId);
15567                 if (ai == null) {
15568                     reportStartInstrumentationFailureLocked(watcher, className,
15569                             "Unable to find instrumentation target package: " + ii.targetPackage);
15570                     return false;
15571                 }
15572             } catch (RemoteException e) {
15573             }
15574 
15575             if (ii.targetPackage.equals("android")) {
15576                 if (!noRestart) {
15577                     reportStartInstrumentationFailureLocked(watcher, className,
15578                             "Cannot instrument system server without 'no-restart'");
15579                     return false;
15580                 }
15581             } else if (!ai.hasCode()) {
15582                 reportStartInstrumentationFailureLocked(watcher, className,
15583                         "Instrumentation target has no code: " + ii.targetPackage);
15584                 return false;
15585             }
15586 
15587             int match = SIGNATURE_NO_MATCH;
15588             try {
15589                 match = pm.checkSignatures(ii.targetPackage, ii.packageName, userId);
15590             } catch (RemoteException e) {
15591             }
15592             if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
15593                 if (Build.IS_DEBUGGABLE && (callingUid == Process.ROOT_UID)
15594                         && (flags & INSTR_FLAG_ALWAYS_CHECK_SIGNATURE) == 0) {
15595                     Slog.w(TAG, "Instrumentation test " + ii.packageName
15596                             + " doesn't have a signature matching the target " + ii.targetPackage
15597                             + ", which would not be allowed on the production Android builds");
15598                 } else {
15599                     String msg = "Permission Denial: starting instrumentation "
15600                             + className + " from pid="
15601                             + Binder.getCallingPid()
15602                             + ", uid=" + Binder.getCallingUid()
15603                             + " not allowed because package " + ii.packageName
15604                             + " does not have a signature matching the target "
15605                             + ii.targetPackage;
15606                     reportStartInstrumentationFailureLocked(watcher, className, msg);
15607                     throw new SecurityException(msg);
15608                 }
15609             }
15610 
15611             if (!Build.IS_DEBUGGABLE && callingUid != ROOT_UID && callingUid != SHELL_UID
15612                     && callingUid != SYSTEM_UID && !hasActiveInstrumentationLocked(callingPid)) {
15613                 // If it's not debug build and not called from root/shell/system uid, reject it.
15614                 final String msg = "Permission Denial: instrumentation test "
15615                         + className + " from pid=" + callingPid + ", uid=" + callingUid
15616                         + ", pkgName=" + mInternal.getPackageNameByPid(callingPid)
15617                         + " not allowed because it's not started from SHELL";
15618                 Slog.wtfQuiet(TAG, msg);
15619                 reportStartInstrumentationFailureLocked(watcher, className, msg);
15620                 throw new SecurityException(msg);
15621             }
15622 
15623             boolean disableHiddenApiChecks = ai.usesNonSdkApi()
15624                     || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
15625             boolean disableTestApiChecks = disableHiddenApiChecks
15626                     || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0;
15627 
15628             if (disableHiddenApiChecks || disableTestApiChecks) {
15629                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
15630                         "disable hidden API checks");
15631             }
15632 
15633             if ((flags & ActivityManager.INSTR_FLAG_INSTRUMENT_SDK_SANDBOX) != 0) {
15634                 return startInstrumentationOfSdkSandbox(
15635                         className,
15636                         profileFile,
15637                         arguments,
15638                         watcher,
15639                         uiAutomationConnection,
15640                         userId,
15641                         abiOverride,
15642                         ii,
15643                         ai,
15644                         noRestart,
15645                         disableHiddenApiChecks,
15646                         disableTestApiChecks);
15647             }
15648 
15649             ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
15650             activeInstr.mClass = className;
15651             String defProcess = ai.processName;;
15652             if (ii.targetProcesses == null) {
15653                 activeInstr.mTargetProcesses = new String[]{ai.processName};
15654             } else if (ii.targetProcesses.equals("*")) {
15655                 activeInstr.mTargetProcesses = new String[0];
15656             } else {
15657                 activeInstr.mTargetProcesses = ii.targetProcesses.split(",");
15658                 defProcess = activeInstr.mTargetProcesses[0];
15659             }
15660             activeInstr.mTargetInfo = ai;
15661             activeInstr.mProfileFile = profileFile;
15662             activeInstr.mArguments = arguments;
15663             activeInstr.mWatcher = watcher;
15664             activeInstr.mUiAutomationConnection = uiAutomationConnection;
15665             activeInstr.mResultClass = className;
15666             activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
15667                     START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
15668                             == PackageManager.PERMISSION_GRANTED;
15669             activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission(
15670                     START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid)
15671                             == PackageManager.PERMISSION_GRANTED;
15672             activeInstr.mNoRestart = noRestart;
15673 
15674             final long origId = Binder.clearCallingIdentity();
15675 
15676             ProcessRecord app;
15677             synchronized (mProcLock) {
15678                 if (noRestart) {
15679                     app = getProcessRecordLocked(ai.processName, ai.uid);
15680                 } else {
15681                     // Instrumentation can kill and relaunch even persistent processes
15682                     forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false,
15683                             userId, "start instr");
15684                     // Inform usage stats to make the target package active
15685                     if (mUsageStatsService != null) {
15686                         mUsageStatsService.reportEvent(ii.targetPackage, userId,
15687                                 UsageEvents.Event.SYSTEM_INTERACTION);
15688                     }
15689                     app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks,
15690                             disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY);
15691                     app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION);
15692                 }
15693 
15694                 app.setActiveInstrumentation(activeInstr);
15695                 activeInstr.mFinished = false;
15696                 activeInstr.mSourceUid = callingUid;
15697                 activeInstr.mRunningProcesses.add(app);
15698                 if (!mActiveInstrumentation.contains(activeInstr)) {
15699                     mActiveInstrumentation.add(activeInstr);
15700                 }
15701             }
15702 
15703             if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) {
15704                 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with
15705                 // --no-isolated-storage flag.
15706                 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid,
15707                         ii.packageName, AppOpsManager.MODE_ALLOWED);
15708             }
15709             Binder.restoreCallingIdentity(origId);
15710 
15711             if (noRestart) {
15712                 instrumentWithoutRestart(activeInstr, ai);
15713             }
15714         }
15715 
15716         return true;
15717     }
15718 
15719     @GuardedBy("this")
hasActiveInstrumentationLocked(int pid)15720     private boolean hasActiveInstrumentationLocked(int pid) {
15721         if (pid == 0) {
15722             return false;
15723         }
15724         synchronized (mPidsSelfLocked) {
15725             ProcessRecord process = mPidsSelfLocked.get(pid);
15726             return process != null && process.getActiveInstrumentation() != null;
15727         }
15728     }
15729 
15730     @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)15731     private boolean startInstrumentationOfSdkSandbox(
15732             ComponentName className,
15733             String profileFile,
15734             Bundle arguments,
15735             IInstrumentationWatcher watcher,
15736             IUiAutomationConnection uiAutomationConnection,
15737             int userId,
15738             String abiOverride,
15739             InstrumentationInfo instrumentationInfo,
15740             ApplicationInfo sdkSandboxClientAppInfo,
15741             boolean noRestart,
15742             boolean disableHiddenApiChecks,
15743             boolean disableTestApiChecks) {
15744 
15745         if (noRestart) {
15746             reportStartInstrumentationFailureLocked(
15747                     watcher,
15748                     className,
15749                     "Instrumenting sdk sandbox with --no-restart flag is not supported");
15750             return false;
15751         }
15752 
15753         final ApplicationInfo sdkSandboxInfo;
15754         try {
15755             final PackageManager pm = mContext.getPackageManager();
15756             sdkSandboxInfo = pm.getApplicationInfoAsUser(pm.getSdkSandboxPackageName(), 0, userId);
15757         } catch (NameNotFoundException e) {
15758             reportStartInstrumentationFailureLocked(
15759                     watcher, className, "Can't find SdkSandbox package");
15760             return false;
15761         }
15762 
15763         final SdkSandboxManagerLocal sandboxManagerLocal =
15764                 LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
15765         if (sandboxManagerLocal == null) {
15766             reportStartInstrumentationFailureLocked(
15767                     watcher, className, "Can't locate SdkSandboxManagerLocal");
15768             return false;
15769         }
15770 
15771         final String processName = sandboxManagerLocal.getSdkSandboxProcessNameForInstrumentation(
15772                 sdkSandboxClientAppInfo);
15773 
15774         ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
15775         activeInstr.mClass = className;
15776         activeInstr.mTargetProcesses = new String[]{processName};
15777         activeInstr.mTargetInfo = sdkSandboxInfo;
15778         activeInstr.mProfileFile = profileFile;
15779         activeInstr.mArguments = arguments;
15780         activeInstr.mWatcher = watcher;
15781         activeInstr.mUiAutomationConnection = uiAutomationConnection;
15782         activeInstr.mResultClass = className;
15783         activeInstr.mHasBackgroundActivityStartsPermission = false;
15784         activeInstr.mHasBackgroundForegroundServiceStartsPermission = false;
15785         // Instrumenting sdk sandbox without a restart is not supported
15786         activeInstr.mNoRestart = false;
15787 
15788         final int callingUid = Binder.getCallingUid();
15789         final long token = Binder.clearCallingIdentity();
15790         try {
15791             sandboxManagerLocal.notifyInstrumentationStarted(
15792                     sdkSandboxClientAppInfo.packageName, sdkSandboxClientAppInfo.uid);
15793             synchronized (mProcLock) {
15794                 int sdkSandboxUid = Process.toSdkSandboxUid(sdkSandboxClientAppInfo.uid);
15795                 // Kill the package sdk sandbox process belong to. At this point sdk sandbox is
15796                 // already killed.
15797                 forceStopPackageLocked(
15798                         instrumentationInfo.targetPackage,
15799                         /* appId= */ -1,
15800                         /* callerWillRestart= */ true,
15801                         /* purgeCache= */ false,
15802                         /* doIt= */ true,
15803                         /* evenPersistent= */ true,
15804                         /* uninstalling= */ false,
15805                         userId,
15806                         "start instr");
15807 
15808                 ProcessRecord app = addAppLocked(
15809                         sdkSandboxInfo,
15810                         processName,
15811                         /* isolated= */ false,
15812                         /* isSdkSandbox= */ true,
15813                         sdkSandboxUid,
15814                         sdkSandboxClientAppInfo.packageName,
15815                         disableHiddenApiChecks,
15816                         disableTestApiChecks,
15817                         abiOverride,
15818                         ZYGOTE_POLICY_FLAG_EMPTY);
15819 
15820                 app.setActiveInstrumentation(activeInstr);
15821                 activeInstr.mFinished = false;
15822                 activeInstr.mSourceUid = callingUid;
15823                 activeInstr.mRunningProcesses.add(app);
15824                 if (!mActiveInstrumentation.contains(activeInstr)) {
15825                     mActiveInstrumentation.add(activeInstr);
15826                 }
15827                 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION);
15828             }
15829         } finally {
15830             Binder.restoreCallingIdentity(token);
15831         }
15832 
15833         return true;
15834     }
15835 
instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)15836     private void instrumentWithoutRestart(ActiveInstrumentation activeInstr,
15837             ApplicationInfo targetInfo) {
15838         ProcessRecord pr;
15839         synchronized (this) {
15840             pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid);
15841         }
15842 
15843         try {
15844             pr.getThread().instrumentWithoutRestart(
15845                     activeInstr.mClass,
15846                     activeInstr.mArguments,
15847                     activeInstr.mWatcher,
15848                     activeInstr.mUiAutomationConnection,
15849                     targetInfo);
15850         } catch (RemoteException e) {
15851             Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e);
15852         }
15853     }
15854 
isCallerShell()15855     private boolean isCallerShell() {
15856         final int callingUid = Binder.getCallingUid();
15857         return callingUid == SHELL_UID || callingUid == ROOT_UID;
15858     }
15859 
15860     /**
15861      * Report errors that occur while attempting to start Instrumentation.  Always writes the
15862      * error to the logs, but if somebody is watching, send the report there too.  This enables
15863      * the "am" command to report errors with more information.
15864      *
15865      * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
15866      * @param cn The component name of the instrumentation.
15867      * @param report The error report.
15868      */
reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)15869     private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher,
15870             ComponentName cn, String report) {
15871         Slog.w(TAG, report);
15872         if (watcher != null) {
15873             Bundle results = new Bundle();
15874             results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
15875             results.putString("Error", report);
15876             mInstrumentationReporter.reportStatus(watcher, cn, -1, results);
15877         }
15878     }
15879 
addInstrumentationResultsLocked(ProcessRecord app, Bundle results)15880     void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) {
15881         final ActiveInstrumentation instr = app.getActiveInstrumentation();
15882         if (instr == null) {
15883             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15884             return;
15885         }
15886 
15887         if (!instr.mFinished && results != null) {
15888             if (instr.mCurResults == null) {
15889                 instr.mCurResults = new Bundle(results);
15890             } else {
15891                 instr.mCurResults.putAll(results);
15892             }
15893         }
15894     }
15895 
addInstrumentationResults(IApplicationThread target, Bundle results)15896     public void addInstrumentationResults(IApplicationThread target, Bundle results) {
15897         int userId = UserHandle.getCallingUserId();
15898         // Refuse possible leaked file descriptors
15899         if (results != null && results.hasFileDescriptors()) {
15900             throw new IllegalArgumentException("File descriptors passed in Intent");
15901         }
15902 
15903         synchronized(this) {
15904             ProcessRecord app = getRecordForAppLOSP(target);
15905             if (app == null) {
15906                 Slog.w(TAG, "addInstrumentationResults: no app for " + target);
15907                 return;
15908             }
15909             final long origId = Binder.clearCallingIdentity();
15910             try {
15911                 addInstrumentationResultsLocked(app, results);
15912             } finally {
15913                 Binder.restoreCallingIdentity(origId);
15914             }
15915         }
15916     }
15917 
15918     @GuardedBy("this")
finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)15919     void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
15920         try {
15921             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "finishInstrumentationLocked()");
15922             final ActiveInstrumentation instr = app.getActiveInstrumentation();
15923             if (instr == null) {
15924                 Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15925                 return;
15926             }
15927 
15928             synchronized (mProcLock) {
15929                 if (!instr.mFinished) {
15930                     if (instr.mWatcher != null) {
15931                         Bundle finalResults = instr.mCurResults;
15932                         if (finalResults != null) {
15933                             if (instr.mCurResults != null && results != null) {
15934                                 finalResults.putAll(results);
15935                             }
15936                         } else {
15937                             finalResults = results;
15938                         }
15939                         mInstrumentationReporter.reportFinished(instr.mWatcher,
15940                                 instr.mClass, resultCode, finalResults);
15941                     }
15942 
15943                     // Can't call out of the system process with a lock held, so post a message.
15944                     if (instr.mUiAutomationConnection != null) {
15945                         // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op.
15946                         mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid,
15947                                 app.info.packageName, AppOpsManager.MODE_ERRORED);
15948                         mAppOpsService.setAppOpsServiceDelegate(null);
15949                         getPermissionManagerInternal().stopShellPermissionIdentityDelegation();
15950                         mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
15951                                 instr.mUiAutomationConnection).sendToTarget();
15952                     }
15953                     instr.mFinished = true;
15954                 }
15955 
15956                 instr.removeProcess(app);
15957                 app.setActiveInstrumentation(null);
15958             }
15959             app.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_INSTRUMENTATION);
15960 
15961             if (app.isSdkSandbox) {
15962                 // For sharedUid apps this will kill all sdk sandbox processes, which is not ideal.
15963                 // TODO(b/209061624): should we call ProcessList.removeProcessLocked instead?
15964                 killUid(UserHandle.getAppId(app.uid), UserHandle.getUserId(app.uid),
15965                         "finished instr");
15966                 final SdkSandboxManagerLocal sandboxManagerLocal =
15967                         LocalManagerRegistry.getManager(SdkSandboxManagerLocal.class);
15968                 if (sandboxManagerLocal != null) {
15969                     sandboxManagerLocal.notifyInstrumentationFinished(
15970                             app.sdkSandboxClientAppPackage,
15971                             Process.getAppUidForSdkSandboxUid(app.uid));
15972                 }
15973             } else if (!instr.mNoRestart) {
15974                 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false,
15975                         app.userId,
15976                         "finished inst");
15977             }
15978         } finally {
15979             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
15980         }
15981     }
15982 
finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)15983     public void finishInstrumentation(IApplicationThread target,
15984             int resultCode, Bundle results) {
15985         int userId = UserHandle.getCallingUserId();
15986         // Refuse possible leaked file descriptors
15987         if (results != null && results.hasFileDescriptors()) {
15988             throw new IllegalArgumentException("File descriptors passed in Intent");
15989         }
15990 
15991         synchronized(this) {
15992             ProcessRecord app = getRecordForAppLOSP(target);
15993             if (app == null) {
15994                 Slog.w(TAG, "finishInstrumentation: no app for " + target);
15995                 return;
15996             }
15997             final long origId = Binder.clearCallingIdentity();
15998             finishInstrumentationLocked(app, resultCode, results);
15999             Binder.restoreCallingIdentity(origId);
16000         }
16001     }
16002 
16003     @Override
getFocusedRootTaskInfo()16004     public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException {
16005         return mActivityTaskManager.getFocusedRootTaskInfo();
16006     }
16007 
16008     @Override
getConfiguration()16009     public Configuration getConfiguration() {
16010         return mActivityTaskManager.getConfiguration();
16011     }
16012 
16013     @Override
suppressResizeConfigChanges(boolean suppress)16014     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
16015         mActivityTaskManager.suppressResizeConfigChanges(suppress);
16016     }
16017 
16018     @Override
updatePersistentConfiguration(Configuration values)16019     public void updatePersistentConfiguration(Configuration values) {
16020         updatePersistentConfigurationWithAttribution(values,
16021                 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null);
16022     }
16023 
16024     @Override
updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)16025     public void updatePersistentConfigurationWithAttribution(Configuration values,
16026             String callingPackage, String callingAttributionTag) {
16027         enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
16028         enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage,
16029                 callingAttributionTag);
16030         if (values == null) {
16031             throw new NullPointerException("Configuration must not be null");
16032         }
16033 
16034         int userId = UserHandle.getCallingUserId();
16035 
16036         mActivityTaskManager.updatePersistentConfiguration(values, userId);
16037     }
16038 
enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)16039     private void enforceWriteSettingsPermission(String func, String callingPackage,
16040             String callingAttributionTag) {
16041         int uid = Binder.getCallingUid();
16042         if (uid == ROOT_UID) {
16043             return;
16044         }
16045 
16046         if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
16047                 callingPackage, callingAttributionTag, false)) {
16048             return;
16049         }
16050 
16051         String msg = "Permission Denial: " + func + " from pid="
16052                 + Binder.getCallingPid()
16053                 + ", uid=" + uid
16054                 + " requires " + android.Manifest.permission.WRITE_SETTINGS;
16055         Slog.w(TAG, msg);
16056         throw new SecurityException(msg);
16057     }
16058 
16059     @Override
updateConfiguration(Configuration values)16060     public boolean updateConfiguration(Configuration values) {
16061         return mActivityTaskManager.updateConfiguration(values);
16062     }
16063 
16064     @Override
updateMccMncConfiguration(String mcc, String mnc)16065     public boolean updateMccMncConfiguration(String mcc, String mnc) {
16066         int mccInt, mncInt;
16067         try {
16068             mccInt = Integer.parseInt(mcc);
16069             mncInt = Integer.parseInt(mnc);
16070         } catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
16071             Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex);
16072             return false;
16073         }
16074         Configuration config = new Configuration();
16075         config.mcc = mccInt;
16076         config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;
16077         return mActivityTaskManager.updateConfiguration(config);
16078     }
16079 
16080     @Override
getLaunchedFromUid(IBinder activityToken)16081     public int getLaunchedFromUid(IBinder activityToken) {
16082         return ActivityClient.getInstance().getLaunchedFromUid(activityToken);
16083     }
16084 
getLaunchedFromPackage(IBinder activityToken)16085     public String getLaunchedFromPackage(IBinder activityToken) {
16086         return ActivityClient.getInstance().getLaunchedFromPackage(activityToken);
16087     }
16088 
16089     // =========================================================
16090     // LIFETIME MANAGEMENT
16091     // =========================================================
16092 
isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup)16093     boolean isReceivingBroadcastLocked(ProcessRecord app, int[] outSchedGroup) {
16094         int res = ProcessList.SCHED_GROUP_UNDEFINED;
16095         for (BroadcastQueue queue : mBroadcastQueues) {
16096             res = Math.max(res, queue.getPreferredSchedulingGroupLocked(app));
16097         }
16098         outSchedGroup[0] = res;
16099         return res != ProcessList.SCHED_GROUP_UNDEFINED;
16100     }
16101 
startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16102     Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState,
16103             int targetUid, long targetVersionCode, ComponentName targetComponent,
16104             String targetProcess) {
16105         if (!mTrackingAssociations) {
16106             return null;
16107         }
16108         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16109                 = mAssociations.get(targetUid);
16110         if (components == null) {
16111             components = new ArrayMap<>();
16112             mAssociations.put(targetUid, components);
16113         }
16114         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16115         if (sourceUids == null) {
16116             sourceUids = new SparseArray<>();
16117             components.put(targetComponent, sourceUids);
16118         }
16119         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16120         if (sourceProcesses == null) {
16121             sourceProcesses = new ArrayMap<>();
16122             sourceUids.put(sourceUid, sourceProcesses);
16123         }
16124         Association ass = sourceProcesses.get(sourceProcess);
16125         if (ass == null) {
16126             ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent,
16127                     targetProcess);
16128             sourceProcesses.put(sourceProcess, ass);
16129         }
16130         ass.mCount++;
16131         ass.mNesting++;
16132         if (ass.mNesting == 1) {
16133             ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis();
16134             ass.mLastState = sourceState;
16135         }
16136         return ass;
16137     }
16138 
stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16139     void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid,
16140             long targetVersionCode, ComponentName targetComponent, String targetProcess) {
16141         if (!mTrackingAssociations) {
16142             return;
16143         }
16144         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16145                 = mAssociations.get(targetUid);
16146         if (components == null) {
16147             return;
16148         }
16149         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16150         if (sourceUids == null) {
16151             return;
16152         }
16153         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16154         if (sourceProcesses == null) {
16155             return;
16156         }
16157         Association ass = sourceProcesses.get(sourceProcess);
16158         if (ass == null || ass.mNesting <= 0) {
16159             return;
16160         }
16161         ass.mNesting--;
16162         if (ass.mNesting == 0) {
16163             long uptime = SystemClock.uptimeMillis();
16164             ass.mTime += uptime - ass.mStartTime;
16165             ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16166                     += uptime - ass.mLastStateUptime;
16167             ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2;
16168         }
16169     }
16170 
noteUidProcessState(final int uid, final int state, final @ProcessCapability int capability)16171     void noteUidProcessState(final int uid, final int state,
16172                 final @ProcessCapability int capability) {
16173         mBatteryStatsService.noteUidProcessState(uid, state);
16174         mAppOpsService.updateUidProcState(uid, state, capability);
16175         if (mTrackingAssociations) {
16176             for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
16177                 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
16178                         = mAssociations.valueAt(i1);
16179                 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
16180                     SparseArray<ArrayMap<String, Association>> sourceUids
16181                             = targetComponents.valueAt(i2);
16182                     ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid);
16183                     if (sourceProcesses != null) {
16184                         for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
16185                             Association ass = sourceProcesses.valueAt(i4);
16186                             if (ass.mNesting >= 1) {
16187                                 // currently associated
16188                                 long uptime = SystemClock.uptimeMillis();
16189                                 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16190                                         += uptime - ass.mLastStateUptime;
16191                                 ass.mLastState = state;
16192                                 ass.mLastStateUptime = uptime;
16193                             }
16194                         }
16195                     }
16196                 }
16197             }
16198         }
16199     }
16200 
16201     /**
16202      * Returns true if things are idle enough to perform GCs.
16203      */
16204     @GuardedBy("this")
canGcNowLocked()16205     final boolean canGcNowLocked() {
16206         for (BroadcastQueue q : mBroadcastQueues) {
16207             if (!q.isIdleLocked()) {
16208                 return false;
16209             }
16210         }
16211         return mAtmInternal.canGcNow();
16212     }
16213 
checkExcessivePowerUsage()16214     private void checkExcessivePowerUsage() {
16215         updateCpuStatsNow();
16216 
16217         final boolean monitorPhantomProcs = mSystemReady && FeatureFlagUtils.isEnabled(mContext,
16218                 SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS);
16219         synchronized (mProcLock) {
16220             final boolean doCpuKills = mLastPowerCheckUptime != 0;
16221             final long curUptime = SystemClock.uptimeMillis();
16222             final long uptimeSince = curUptime - mLastPowerCheckUptime;
16223             mLastPowerCheckUptime = curUptime;
16224             mProcessList.forEachLruProcessesLOSP(false, app -> {
16225                 if (app.getThread() == null) {
16226                     return;
16227                 }
16228                 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) {
16229                     int cpuLimit;
16230                     long checkDur = curUptime - app.mState.getWhenUnimportant();
16231                     if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
16232                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
16233                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2)
16234                             || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) {
16235                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
16236                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) {
16237                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
16238                     } else {
16239                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
16240                     }
16241 
16242                     updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app);
16243 
16244                     if (monitorPhantomProcs) {
16245                         // Also check the phantom processes if there is any
16246                         updatePhantomProcessCpuTimeLPr(
16247                                 uptimeSince, doCpuKills, checkDur, cpuLimit, app);
16248                     }
16249                 }
16250             });
16251         }
16252     }
16253 
16254     @GuardedBy("mProcLock")
updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)16255     private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills,
16256             final long checkDur, final int cpuLimit, final ProcessRecord app) {
16257         synchronized (mAppProfiler.mProfilerLock) {
16258             final ProcessProfileRecord profile = app.mProfile;
16259             final long curCpuTime = profile.mCurCpuTime.get();
16260             final long lastCpuTime = profile.mLastCpuTime.get();
16261             if (lastCpuTime > 0) {
16262                 final long cpuTimeUsed = curCpuTime - lastCpuTime;
16263                 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed,
16264                             app.processName, app.toShortString(), cpuLimit, app)) {
16265                     mHandler.post(() -> {
16266                         synchronized (ActivityManagerService.this) {
16267                             if (app.getThread() == null
16268                                || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) {
16269                                    return;
16270                             }
16271                             app.killLocked("excessive cpu " + cpuTimeUsed + " during "
16272                                     + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit,
16273                                     ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
16274                                     ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
16275                                     true);
16276                         }
16277                     });
16278                     profile.reportExcessiveCpu();
16279                 }
16280             }
16281 
16282             profile.mLastCpuTime.set(curCpuTime);
16283         }
16284     }
16285 
16286     @GuardedBy("mProcLock")
updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)16287     private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills,
16288             final long checkDur, final int cpuLimit, final ProcessRecord app) {
16289         mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> {
16290             if (r.mLastCputime > 0) {
16291                 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime;
16292                 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed,
16293                             app.processName, r.toString(), cpuLimit, app)) {
16294                     mHandler.post(() -> {
16295                         synchronized (ActivityManagerService.this) {
16296                             if (app.getThread() == null
16297                                || app.mState.getSetProcState() < ActivityManager.PROCESS_STATE_HOME) {
16298                                    return;
16299                             }
16300                             mPhantomProcessList.killPhantomProcessGroupLocked(app, r,
16301                                     ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
16302                                     ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
16303                                     "excessive cpu " + cpuTimeUsed + " during "
16304                                     + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit);
16305                         }
16306                     });
16307                     return false;
16308                 }
16309             }
16310             r.mLastCputime = r.mCurrentCputime;
16311             return true;
16312         });
16313     }
16314 
16315     @GuardedBy("mProcLock")
checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)16316     private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills,
16317             final long cputimeUsed, final String processName, final String description,
16318             final int cpuLimit, final ProcessRecord app) {
16319         if (DEBUG_POWER && (uptimeSince > 0)) {
16320             StringBuilder sb = new StringBuilder(128);
16321             sb.append("CPU for ");
16322             sb.append(description);
16323             sb.append(": over ");
16324             TimeUtils.formatDuration(uptimeSince, sb);
16325             sb.append(" used ");
16326             TimeUtils.formatDuration(cputimeUsed, sb);
16327             sb.append(" (");
16328             sb.append((cputimeUsed * 100.0) / uptimeSince);
16329             sb.append("%)");
16330             Slog.i(TAG_POWER, sb.toString());
16331         }
16332         // If the process has used too much CPU over the last duration, the
16333         // user probably doesn't want this, so kill!
16334         if (doCpuKills && uptimeSince > 0) {
16335             if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) {
16336                 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName,
16337                         uptimeSince, cputimeUsed);
16338                 app.getPkgList().forEachPackageProcessStats(holder -> {
16339                     final ProcessState state = holder.state;
16340                     FrameworkStatsLog.write(
16341                             FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED,
16342                             app.info.uid,
16343                             processName,
16344                             state != null ? state.getPackage() : app.info.packageName,
16345                             holder.appVersion);
16346                 });
16347                 return true;
16348             }
16349         }
16350         return false;
16351     }
16352 
isEphemeralLocked(int uid)16353     private boolean isEphemeralLocked(int uid) {
16354         final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
16355         if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid
16356             return false;
16357         }
16358         return getPackageManagerInternal().isPackageEphemeral(
16359                 UserHandle.getUserId(uid), packages[0]);
16360     }
16361 
16362     @GuardedBy("this")
enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)16363     void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) {
16364         uid = uidRec != null ? uidRec.getUid() : uid;
16365         if (uid < 0) {
16366             throw new IllegalArgumentException("No UidRecord or uid");
16367         }
16368 
16369         final int procState = uidRec != null
16370                 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT;
16371         final int procAdj = uidRec != null
16372                 ? uidRec.getMinProcAdj() : ProcessList.INVALID_ADJ;
16373         final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0;
16374         final int capability = uidRec != null ? uidRec.getSetCapability() : 0;
16375         final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid);
16376 
16377         if (uidRec != null && uidRec.isIdle() && (change & UidRecord.CHANGE_IDLE) != 0) {
16378             mProcessList.killAppIfBgRestrictedAndCachedIdleLocked(uidRec);
16379         }
16380 
16381         if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) {
16382             // If this uid is going away, and we haven't yet reported it is gone,
16383             // then do so now.
16384             change |= UidRecord.CHANGE_IDLE;
16385         }
16386         final int enqueuedChange = mUidObserverController.enqueueUidChange(
16387                 uidRec == null ? null : uidRec.pendingChange,
16388                 uid, change, procState, procAdj, procStateSeq, capability, ephemeral);
16389         if (uidRec != null) {
16390             uidRec.setLastReportedChange(enqueuedChange);
16391         }
16392 
16393         // Directly update the power manager, since we sit on top of it and it is critical
16394         // it be kept in sync (so wake locks will be held as soon as appropriate).
16395         if (mLocalPowerManager != null) {
16396             // TODO: dispatch cached/uncached changes here, so we don't need to report
16397             // all proc state changes.
16398             if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) {
16399                 mLocalPowerManager.uidActive(uid);
16400             }
16401             if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) {
16402                 mLocalPowerManager.uidIdle(uid);
16403             }
16404             if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) {
16405                 mLocalPowerManager.uidGone(uid);
16406             } else if ((enqueuedChange & UidRecord.CHANGE_PROCSTATE) != 0) {
16407                 mLocalPowerManager.updateUidProcState(uid, procState);
16408             }
16409         }
16410     }
16411 
16412     @GuardedBy(anyOf = {"this", "mProcLock"})
setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor)16413     final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor) {
16414         if (proc.getThread() != null) {
16415             proc.mProfile.setProcessTrackerState(
16416                     proc.mState.getReportedProcState(), memFactor);
16417         }
16418     }
16419 
16420     @GuardedBy("this")
clearProcessForegroundLocked(ProcessRecord proc)16421     final void clearProcessForegroundLocked(ProcessRecord proc) {
16422         updateProcessForegroundLocked(proc, /* isForeground =*/ false,
16423                 /* fgsTypes =*/0, /* hasTypeNoneFgs =*/false, /* oomAdj= */ false);
16424     }
16425 
16426     @GuardedBy("this")
updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj)16427     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
16428             int fgServiceTypes, boolean hasTypeNoneFgs, boolean oomAdj) {
16429         final ProcessServiceRecord psr = proc.mServices;
16430         final boolean foregroundStateChanged = isForeground != psr.hasForegroundServices();
16431         if (foregroundStateChanged
16432                 || !psr.areForegroundServiceTypesSame(fgServiceTypes, hasTypeNoneFgs)) {
16433             if (foregroundStateChanged) {
16434                 // Notify internal listeners.
16435                 for (int i = mForegroundServiceStateListeners.size() - 1; i >= 0; i--) {
16436                     mForegroundServiceStateListeners.get(i).onForegroundServiceStateChanged(
16437                             proc.info.packageName, proc.info.uid, proc.getPid(), isForeground);
16438                 }
16439             }
16440             psr.setHasForegroundServices(isForeground, fgServiceTypes, hasTypeNoneFgs);
16441             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
16442                     proc.info.uid);
16443             if (isForeground) {
16444                 if (curProcs == null) {
16445                     curProcs = new ArrayList<ProcessRecord>();
16446                     mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
16447                 }
16448                 if (!curProcs.contains(proc)) {
16449                     curProcs.add(proc);
16450                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
16451                             proc.info.packageName, proc.info.uid);
16452                 }
16453             } else {
16454                 if (curProcs != null) {
16455                     if (curProcs.remove(proc)) {
16456                         mBatteryStatsService.noteEvent(
16457                                 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
16458                                 proc.info.packageName, proc.info.uid);
16459                         if (curProcs.size() <= 0) {
16460                             mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
16461                         }
16462                     }
16463                 }
16464             }
16465 
16466             psr.setReportedForegroundServiceTypes(fgServiceTypes);
16467             ProcessChangeItem item = mProcessList.enqueueProcessChangeItemLocked(
16468                     proc.getPid(), proc.info.uid);
16469             item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES;
16470             item.foregroundServiceTypes = fgServiceTypes;
16471         }
16472         if (oomAdj) {
16473             updateOomAdjLocked(proc, OOM_ADJ_REASON_UI_VISIBILITY);
16474         }
16475     }
16476 
16477     // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update
16478     // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities
16479     @Nullable
getTopApp()16480     ProcessRecord getTopApp() {
16481         final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null;
16482         final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null;
16483         String pkg;
16484         int uid;
16485         if (r != null) {
16486             pkg = r.processName;
16487             uid = r.info.uid;
16488         } else {
16489             pkg = null;
16490             uid = -1;
16491         }
16492         // Has the UID or resumed package name changed?
16493         synchronized (mCurResumedAppLock) {
16494             if (uid != mCurResumedUid || (pkg != mCurResumedPackage
16495                         && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
16496 
16497                 final long identity = Binder.clearCallingIdentity();
16498                 try {
16499                     if (mCurResumedPackage != null) {
16500                         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
16501                                 mCurResumedPackage, mCurResumedUid);
16502                     }
16503                     mCurResumedPackage = pkg;
16504                     mCurResumedUid = uid;
16505                     if (mCurResumedPackage != null) {
16506                         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
16507                                 mCurResumedPackage, mCurResumedUid);
16508                     }
16509                 } finally {
16510                     Binder.restoreCallingIdentity(identity);
16511                 }
16512             }
16513         }
16514         return r;
16515     }
16516 
16517     /**
16518      * Enqueue the given process into a todo list, and the caller should
16519      * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update.
16520      */
16521     @GuardedBy("this")
enqueueOomAdjTargetLocked(ProcessRecord app)16522     void enqueueOomAdjTargetLocked(ProcessRecord app) {
16523         mOomAdjuster.enqueueOomAdjTargetLocked(app);
16524     }
16525 
16526     /**
16527      * Remove the given process into a todo list.
16528      */
16529     @GuardedBy("this")
removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)16530     void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) {
16531         mOomAdjuster.removeOomAdjTargetLocked(app, procDied);
16532     }
16533 
16534     /**
16535      * Kick off an oom adj update pass for the pending targets which are enqueued via
16536      * {@link #enqueueOomAdjTargetLocked}.
16537      */
16538     @GuardedBy("this")
updateOomAdjPendingTargetsLocked(@omAdjReason int oomAdjReason)16539     void updateOomAdjPendingTargetsLocked(@OomAdjReason int oomAdjReason) {
16540         mOomAdjuster.updateOomAdjPendingTargetsLocked(oomAdjReason);
16541     }
16542 
16543     static final class ProcStatsRunnable implements Runnable {
16544         private final ActivityManagerService mService;
16545         private final ProcessStatsService mProcessStats;
16546 
ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)16547         ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) {
16548             this.mService = service;
16549             this.mProcessStats = mProcessStats;
16550         }
16551 
run()16552         @Override public void run() {
16553             mProcessStats.writeStateAsync();
16554         }
16555     }
16556 
16557     @GuardedBy("this")
updateOomAdjLocked(@omAdjReason int oomAdjReason)16558     final void updateOomAdjLocked(@OomAdjReason int oomAdjReason) {
16559         mOomAdjuster.updateOomAdjLocked(oomAdjReason);
16560     }
16561 
16562     /**
16563      * Update OomAdj for a specific process and its reachable processes.
16564      *
16565      * @param app The process to update
16566      * @param oomAdjReason
16567      * @return whether updateOomAdjLocked(app) was successful.
16568      */
16569     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason)16570     final boolean updateOomAdjLocked(ProcessRecord app, @OomAdjReason int oomAdjReason) {
16571         return mOomAdjuster.updateOomAdjLocked(app, oomAdjReason);
16572     }
16573 
16574     @Override
makePackageIdle(String packageName, int userId)16575     public void makePackageIdle(String packageName, int userId) {
16576         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
16577                 != PackageManager.PERMISSION_GRANTED) {
16578             String msg = "Permission Denial: makePackageIdle() from pid="
16579                     + Binder.getCallingPid()
16580                     + ", uid=" + Binder.getCallingUid()
16581                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
16582             Slog.w(TAG, msg);
16583             throw new SecurityException(msg);
16584         }
16585         final int callingPid = Binder.getCallingPid();
16586         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
16587                 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null);
16588         final long callingId = Binder.clearCallingIdentity();
16589         try {
16590             IPackageManager pm = AppGlobals.getPackageManager();
16591             int pkgUid = -1;
16592             try {
16593                 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES
16594                         | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM);
16595             } catch (RemoteException e) {
16596             }
16597             if (pkgUid == -1) {
16598                 throw new IllegalArgumentException("Unknown package name " + packageName);
16599             }
16600 
16601             synchronized (this) {
16602                 try {
16603                     if (mLocalPowerManager != null) {
16604                         mLocalPowerManager.startUidChanges();
16605                     }
16606                     final int appId = UserHandle.getAppId(pkgUid);
16607                     for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) {
16608                         final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
16609                         final long bgTime = uidRec.getLastBackgroundTime();
16610                         if (bgTime > 0 && !uidRec.isIdle()) {
16611                             final int uid = uidRec.getUid();
16612                             if (UserHandle.getAppId(uid) == appId) {
16613                                 if (userId == UserHandle.USER_ALL
16614                                         || userId == UserHandle.getUserId(uid)) {
16615                                     EventLogTags.writeAmUidIdle(uid);
16616                                     synchronized (mProcLock) {
16617                                         uidRec.setIdle(true);
16618                                         uidRec.setSetIdle(true);
16619                                     }
16620                                     Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid)
16621                                             + " from package " + packageName + " user " + userId);
16622                                     doStopUidLocked(uid, uidRec);
16623                                 }
16624                             }
16625                         }
16626                     }
16627                 } finally {
16628                     if (mLocalPowerManager != null) {
16629                         mLocalPowerManager.finishUidChanges();
16630                     }
16631                 }
16632             }
16633         } finally {
16634             Binder.restoreCallingIdentity(callingId);
16635         }
16636     }
16637 
16638     @Override
setDeterministicUidIdle(boolean deterministic)16639     public void setDeterministicUidIdle(boolean deterministic) {
16640         mDeterministicUidIdle = deterministic;
16641     }
16642 
16643     /** Make the currently active UIDs idle after a certain grace period. */
idleUids()16644     final void idleUids() {
16645         synchronized (this) {
16646             mOomAdjuster.idleUidsLocked();
16647         }
16648     }
16649 
runInBackgroundDisabled(int uid)16650     final void runInBackgroundDisabled(int uid) {
16651         synchronized (this) {
16652             UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
16653             if (uidRec != null) {
16654                 // This uid is actually running...  should it be considered background now?
16655                 if (uidRec.isIdle()) {
16656                     doStopUidLocked(uidRec.getUid(), uidRec);
16657                 }
16658             } else {
16659                 // This uid isn't actually running...  still send a report about it being "stopped".
16660                 doStopUidLocked(uid, null);
16661             }
16662         }
16663     }
16664 
cameraActiveChanged(@serIdInt int uid, boolean active)16665     final void cameraActiveChanged(@UserIdInt int uid, boolean active) {
16666         synchronized (mActiveCameraUids) {
16667             final int curIndex = mActiveCameraUids.indexOf(uid);
16668             if (active) {
16669                 if (curIndex < 0) {
16670                     mActiveCameraUids.add(uid);
16671                 }
16672             } else {
16673                 if (curIndex >= 0) {
16674                     mActiveCameraUids.remove(curIndex);
16675                 }
16676             }
16677         }
16678     }
16679 
isCameraActiveForUid(@serIdInt int uid)16680     final boolean isCameraActiveForUid(@UserIdInt int uid) {
16681         synchronized (mActiveCameraUids) {
16682             return mActiveCameraUids.indexOf(uid) >= 0;
16683         }
16684     }
16685 
16686     @GuardedBy("this")
doStopUidLocked(int uid, final UidRecord uidRec)16687     final void doStopUidLocked(int uid, final UidRecord uidRec) {
16688         mServices.stopInBackgroundLocked(uid);
16689         enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE | UidRecord.CHANGE_PROCSTATE);
16690     }
16691 
16692     /**
16693      * Allowlists {@code targetUid} to temporarily bypass Power Save mode.
16694      */
16695     @GuardedBy("this")
tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)16696     void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid,
16697             long duration, int type, @ReasonCode int reasonCode, String reason) {
16698         if (DEBUG_ALLOWLISTS) {
16699             Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", "
16700                     + targetUid + ", " + duration + ", " + type + ")");
16701         }
16702 
16703         synchronized (mPidsSelfLocked) {
16704             final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
16705             if (pr == null) {
16706                 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid "
16707                         + callerPid);
16708                 return;
16709             }
16710             if (!pr.mServices.mAllowlistManager) {
16711                 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid)
16712                         != PackageManager.PERMISSION_GRANTED
16713                         && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid)
16714                         != PackageManager.PERMISSION_GRANTED
16715                         && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid,
16716                         callerUid) != PackageManager.PERMISSION_GRANTED) {
16717                     if (DEBUG_ALLOWLISTS) {
16718                         Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid
16719                                 + ": pid " + callerPid + " is not allowed");
16720                     }
16721                     return;
16722                 }
16723             }
16724         }
16725 
16726         tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid);
16727     }
16728 
16729     /**
16730      * Allowlists {@code targetUid} to temporarily bypass Power Save mode.
16731      */
16732     @GuardedBy("this")
tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)16733     void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode,
16734             String reason, @TempAllowListType int type, int callingUid) {
16735         synchronized (mProcLock) {
16736             // The temp allowlist type could change according to the reasonCode.
16737             if (mLocalDeviceIdleController != null) {
16738                 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type);
16739             }
16740             if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) {
16741                 return;
16742             }
16743             mPendingTempAllowlist.put(targetUid,
16744                     new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type,
16745                             callingUid));
16746             setUidTempAllowlistStateLSP(targetUid, true);
16747             mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget();
16748 
16749             if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) {
16750                 mFgsStartTempAllowList.add(targetUid, duration,
16751                         new FgsTempAllowListItem(duration, reasonCode, reason, callingUid));
16752             }
16753         }
16754     }
16755 
pushTempAllowlist()16756     void pushTempAllowlist() {
16757         final int N;
16758         final PendingTempAllowlist[] list;
16759 
16760         // First copy out the pending changes...  we need to leave them in the map for now,
16761         // in case someone needs to check what is coming up while we don't have the lock held.
16762         synchronized (this) {
16763             synchronized (mProcLock) {
16764                 N = mPendingTempAllowlist.size();
16765                 list = new PendingTempAllowlist[N];
16766                 for (int i = 0; i < N; i++) {
16767                     list[i] = mPendingTempAllowlist.valueAt(i);
16768                 }
16769             }
16770         }
16771 
16772         // Now safely dispatch changes to device idle controller.  Skip this if we're early
16773         // in boot and the controller hasn't yet been brought online:  we do not apply
16774         // device idle policy anyway at this phase.
16775         if (mLocalDeviceIdleController != null) {
16776             for (int i = 0; i < N; i++) {
16777                 PendingTempAllowlist ptw = list[i];
16778                 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid,
16779                         ptw.duration, ptw.type, false, ptw.reasonCode, ptw.tag,
16780                         ptw.callingUid);
16781             }
16782         }
16783 
16784         // And now we can safely remove them from the map.
16785         synchronized (this) {
16786             synchronized (mProcLock) {
16787                 for (int i = 0; i < N; i++) {
16788                     PendingTempAllowlist ptw = list[i];
16789                     int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid);
16790                     if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) {
16791                         mPendingTempAllowlist.removeAt(index);
16792                     }
16793                 }
16794             }
16795         }
16796     }
16797 
16798     @GuardedBy({"this", "mProcLock"})
setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist)16799     final void setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist) {
16800         mOomAdjuster.setAppIdTempAllowlistStateLSP(uid, onAllowlist);
16801     }
16802 
16803     @GuardedBy({"this", "mProcLock"})
setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)16804     final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) {
16805         mOomAdjuster.setUidTempAllowlistStateLSP(uid, onAllowlist);
16806     }
16807 
trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)16808     private void trimApplications(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) {
16809         synchronized (this) {
16810             trimApplicationsLocked(forceFullOomAdj, oomAdjReason);
16811         }
16812     }
16813 
16814     @GuardedBy("this")
trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason)16815     private void trimApplicationsLocked(boolean forceFullOomAdj, @OomAdjReason int oomAdjReason) {
16816         // First remove any unused application processes whose package
16817         // has been removed.
16818         boolean didSomething = false;
16819         for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) {
16820             final ProcessRecord app = mProcessList.mRemovedProcesses.get(i);
16821             if (!app.hasActivitiesOrRecentTasks()
16822                     && app.mReceivers.numberOfCurReceivers() == 0
16823                     && app.mServices.numberOfRunningServices() == 0) {
16824                 final IApplicationThread thread = app.getThread();
16825                 Slog.i(TAG, "Exiting empty application process "
16826                         + app.toShortString() + " ("
16827                         + (thread != null ? thread.asBinder() : null)
16828                         + ")\n");
16829                 final int pid = app.getPid();
16830                 if (pid > 0 && pid != MY_PID) {
16831                     app.killLocked("empty",
16832                             ApplicationExitInfo.REASON_OTHER,
16833                             ApplicationExitInfo.SUBREASON_TRIM_EMPTY,
16834                             false);
16835                 } else if (thread != null) {
16836                     try {
16837                         thread.scheduleExit();
16838                     } catch (Exception e) {
16839                         // Ignore exceptions.
16840                     }
16841                 }
16842                 didSomething = true;
16843                 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/,
16844                         false /* fromBinderDied */);
16845                 mProcessList.mRemovedProcesses.remove(i);
16846 
16847                 if (app.isPersistent()) {
16848                     addAppLocked(app.info, null, false, null /* ABI override */,
16849                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
16850                     app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_PERSISTENT);
16851                 }
16852             }
16853         }
16854 
16855         // Now update the oom adj for all processes. Don't skip this, since other callers
16856         // might be depending on it.
16857         if (didSomething || forceFullOomAdj) {
16858             updateOomAdjLocked(oomAdjReason);
16859         } else {
16860             // Process any pending oomAdj targets, it'll be a no-op if nothing is pending.
16861             updateOomAdjPendingTargetsLocked(oomAdjReason);
16862         }
16863     }
16864 
16865     /** This method sends the specified signal to each of the persistent apps */
signalPersistentProcesses(final int sig)16866     public void signalPersistentProcesses(final int sig) throws RemoteException {
16867         if (sig != SIGNAL_USR1) {
16868             throw new SecurityException("Only SIGNAL_USR1 is allowed");
16869         }
16870 
16871         if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
16872                 != PackageManager.PERMISSION_GRANTED) {
16873             throw new SecurityException("Requires permission "
16874                     + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
16875         }
16876 
16877         synchronized (mProcLock) {
16878             mProcessList.forEachLruProcessesLOSP(false, app -> {
16879                 if (app.getThread() != null && app.isPersistent()) {
16880                     sendSignal(app.getPid(), sig);
16881                 }
16882             });
16883         }
16884     }
16885 
profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)16886     public boolean profileControl(String process, int userId, boolean start,
16887             ProfilerInfo profilerInfo, int profileType) throws RemoteException {
16888         // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
16889         // its own permission.
16890         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
16891                 != PackageManager.PERMISSION_GRANTED) {
16892             throw new SecurityException("Requires permission "
16893                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
16894         }
16895 
16896         if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
16897             throw new IllegalArgumentException("null profile info or fd");
16898         }
16899 
16900         ProcessRecord proc = null;
16901         synchronized (mProcLock) {
16902             if (process != null) {
16903                 proc = findProcessLOSP(process, userId, "profileControl");
16904             }
16905 
16906             if (start && (proc == null || proc.getThread() == null)) {
16907                 throw new IllegalArgumentException("Unknown process: " + process);
16908             }
16909         }
16910 
16911         synchronized (mAppProfiler.mProfilerLock) {
16912             return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType);
16913         }
16914     }
16915 
16916     @GuardedBy(anyOf = {"this", "mProcLock"})
findProcessLOSP(String process, int userId, String callName)16917     private ProcessRecord findProcessLOSP(String process, int userId, String callName) {
16918         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
16919                 userId, true, ALLOW_FULL_ONLY, callName, null);
16920         ProcessRecord proc = null;
16921         try {
16922             int pid = Integer.parseInt(process);
16923             synchronized (mPidsSelfLocked) {
16924                 proc = mPidsSelfLocked.get(pid);
16925             }
16926         } catch (NumberFormatException e) {
16927         }
16928 
16929         if (proc == null) {
16930             ArrayMap<String, SparseArray<ProcessRecord>> all =
16931                     mProcessList.getProcessNamesLOSP().getMap();
16932             SparseArray<ProcessRecord> procs = all.get(process);
16933             if (procs != null && procs.size() > 0) {
16934                 proc = procs.valueAt(0);
16935                 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
16936                     for (int i=1; i<procs.size(); i++) {
16937                         ProcessRecord thisProc = procs.valueAt(i);
16938                         if (thisProc.userId == userId) {
16939                             proc = thisProc;
16940                             break;
16941                         }
16942                     }
16943                 }
16944             }
16945         }
16946 
16947         return proc;
16948     }
16949 
16950     @Override
dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)16951     public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo,
16952             boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) {
16953         try {
16954             // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
16955             // its own permission (same as profileControl).
16956             if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
16957                     != PackageManager.PERMISSION_GRANTED) {
16958                 throw new SecurityException("Requires permission "
16959                         + android.Manifest.permission.SET_ACTIVITY_WATCHER);
16960             }
16961 
16962             if (fd == null) {
16963                 throw new IllegalArgumentException("null fd");
16964             }
16965 
16966             synchronized (this) {
16967                 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap");
16968                 IApplicationThread thread;
16969                 if (proc == null || (thread = proc.getThread()) == null) {
16970                     throw new IllegalArgumentException("Unknown process: " + process);
16971                 }
16972 
16973                 enforceDebuggable(proc);
16974 
16975                 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
16976 
16977                 final RemoteCallback intermediateCallback = new RemoteCallback(
16978                         new RemoteCallback.OnResultListener() {
16979                         @Override
16980                         public void onResult(Bundle result) {
16981                             finishCallback.sendResult(result);
16982                             mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
16983                         }
16984                     }, null);
16985 
16986                 thread.dumpHeap(managed, mallocInfo, runGc, path, fd, intermediateCallback);
16987                 fd = null;
16988                 return true;
16989             }
16990         } catch (RemoteException e) {
16991             throw new IllegalStateException("Process disappeared");
16992         } finally {
16993             if (fd != null) {
16994                 try {
16995                     fd.close();
16996                 } catch (IOException e) {
16997                 }
16998             }
16999         }
17000     }
17001 
17002     /**
17003      * Dump the resources structure for the given process
17004      *
17005      * @param process The process to dump resource info for
17006      * @param fd The FileDescriptor to dump it into
17007      * @throws RemoteException
17008      */
dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)17009     public boolean dumpResources(String process, ParcelFileDescriptor fd, RemoteCallback callback)
17010             throws RemoteException {
17011         synchronized (this) {
17012             ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_CURRENT, "dumpResources");
17013             IApplicationThread thread;
17014             if (proc == null || (thread = proc.getThread()) == null) {
17015                 throw new IllegalArgumentException("Unknown process: " + process);
17016             }
17017             thread.dumpResources(fd, callback);
17018             return true;
17019         }
17020     }
17021 
17022     /**
17023      * Dump the resources structure for all processes
17024      *
17025      * @param fd The FileDescriptor to dump it into
17026      * @throws RemoteException
17027      */
dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw)17028     public void dumpAllResources(ParcelFileDescriptor fd, PrintWriter pw) throws RemoteException {
17029         final ArrayList<ProcessRecord> processes = new ArrayList<>();
17030         synchronized (this) {
17031             processes.addAll(mProcessList.getLruProcessesLOSP());
17032         }
17033         for (int i = 0, size = processes.size(); i < size; i++) {
17034             ProcessRecord app = processes.get(i);
17035             pw.println(String.format("Resources History for %s (%s)",
17036                     app.processName,
17037                     app.info.packageName));
17038             if (app.mOptRecord.isFrozen()) {
17039                 pw.println("  Skipping frozen process");
17040                 pw.flush();
17041                 continue;
17042             }
17043             pw.flush();
17044             try {
17045                 TransferPipe tp = new TransferPipe("  ");
17046                 try {
17047                     IApplicationThread thread = app.getThread();
17048                     if (thread != null) {
17049                         app.getThread().dumpResources(tp.getWriteFd(), null);
17050                         tp.go(fd.getFileDescriptor(), 2000);
17051                     } else {
17052                         pw.println(String.format(
17053                                 "  Resources history for %s (%s) failed, no thread",
17054                                 app.processName,
17055                                 app.info.packageName));
17056                     }
17057                 } finally {
17058                     tp.kill();
17059                 }
17060             } catch (IOException e) {
17061                 pw.println("  " + e.getMessage());
17062                 pw.flush();
17063             }
17064 
17065         }
17066     }
17067 
17068     @Override
setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)17069     public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize,
17070             String reportPackage) {
17071         if (processName != null) {
17072             enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
17073                     "setDumpHeapDebugLimit()");
17074         } else {
17075             synchronized (mPidsSelfLocked) {
17076                 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid());
17077                 if (proc == null) {
17078                     throw new SecurityException("No process found for calling pid "
17079                             + Binder.getCallingPid());
17080                 }
17081                 enforceDebuggable(proc);
17082                 processName = proc.processName;
17083                 uid = proc.uid;
17084                 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) {
17085                     throw new SecurityException("Package " + reportPackage + " is not running in "
17086                             + proc);
17087                 }
17088             }
17089         }
17090         mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage);
17091     }
17092 
17093     @Override
dumpHeapFinished(String path)17094     public void dumpHeapFinished(String path) {
17095         mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid());
17096     }
17097 
17098     /** In this method we try to acquire our lock to make sure that we have not deadlocked */
monitor()17099     public void monitor() {
17100         synchronized (this) { }
17101     }
17102 
onCoreSettingsChange(Bundle settings)17103     void onCoreSettingsChange(Bundle settings) {
17104         synchronized (mProcLock) {
17105             mProcessList.updateCoreSettingsLOSP(settings);
17106         }
17107     }
17108 
17109     // Multi-user methods
17110 
17111     /**
17112      * Start user, if its not already running, but don't bring it to foreground.
17113      */
17114     @Override
startUserInBackground(final int userId)17115     public boolean startUserInBackground(final int userId) {
17116         return startUserInBackgroundWithListener(userId, null);
17117     }
17118 
17119     @Override
startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17120     public boolean startUserInBackgroundWithListener(final int userId,
17121                 @Nullable IProgressListener unlockListener) {
17122         return mUserController.startUser(userId, USER_START_MODE_BACKGROUND, unlockListener);
17123     }
17124 
17125     @Override
startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17126     public boolean startUserInForegroundWithListener(final int userId,
17127             @Nullable IProgressListener unlockListener) {
17128         // Permission check done inside UserController.
17129         return mUserController.startUser(userId, USER_START_MODE_FOREGROUND, unlockListener);
17130     }
17131 
17132     @Override
startUserInBackgroundVisibleOnDisplay(int userId, int displayId, @Nullable IProgressListener unlockListener)17133     public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId,
17134             @Nullable IProgressListener unlockListener) {
17135         int[] displayIds = getDisplayIdsForStartingVisibleBackgroundUsers();
17136         boolean validDisplay = false;
17137         if (displayIds != null) {
17138             for (int i = 0; i < displayIds.length; i++) {
17139                 if (displayId == displayIds[i]) {
17140                     validDisplay = true;
17141                     break;
17142                 }
17143             }
17144         }
17145         if (!validDisplay) {
17146             throw new IllegalArgumentException("Invalid display (" + displayId + ") to start user. "
17147                     + "Valid options are: " + Arrays.toString(displayIds));
17148         }
17149 
17150         if (DEBUG_MU) {
17151             Slogf.d(TAG_MU, "Calling startUserOnSecondaryDisplay(%d, %d, %s) using injector %s",
17152                     userId, displayId, unlockListener, mInjector);
17153         }
17154         // Permission check done inside UserController.
17155         return mInjector.startUserInBackgroundVisibleOnDisplay(userId, displayId, unlockListener);
17156     }
17157 
17158     @Override
getDisplayIdsForStartingVisibleBackgroundUsers()17159     public int[] getDisplayIdsForStartingVisibleBackgroundUsers() {
17160         enforceCallingHasAtLeastOnePermission("getDisplayIdsForStartingVisibleBackgroundUsers()",
17161                 MANAGE_USERS, INTERACT_ACROSS_USERS);
17162         return mInjector.getDisplayIdsForStartingVisibleBackgroundUsers();
17163     }
17164 
17165     /** @deprecated see the AIDL documentation {@inheritDoc} */
17166     @Override
17167     @Deprecated
unlockUser(@serIdInt int userId, @Nullable byte[] token, @Nullable byte[] secret, @Nullable IProgressListener listener)17168     public boolean unlockUser(@UserIdInt int userId, @Nullable byte[] token,
17169             @Nullable byte[] secret, @Nullable IProgressListener listener) {
17170         return mUserController.unlockUser(userId, listener);
17171     }
17172 
17173     @Override
unlockUser2(@serIdInt int userId, @Nullable IProgressListener listener)17174     public boolean unlockUser2(@UserIdInt int userId, @Nullable IProgressListener listener) {
17175         return mUserController.unlockUser(userId, listener);
17176     }
17177 
17178     @Override
switchUser(final int targetUserId)17179     public boolean switchUser(final int targetUserId) {
17180         return mUserController.switchUser(targetUserId);
17181     }
17182 
17183     @Override
getSwitchingFromUserMessage()17184     public String getSwitchingFromUserMessage() {
17185         return mUserController.getSwitchingFromSystemUserMessage();
17186     }
17187 
17188     @Override
getSwitchingToUserMessage()17189     public String getSwitchingToUserMessage() {
17190         return mUserController.getSwitchingToSystemUserMessage();
17191     }
17192 
17193     @Override
setStopUserOnSwitch(@topUserOnSwitch int value)17194     public void setStopUserOnSwitch(@StopUserOnSwitch int value) {
17195         mUserController.setStopUserOnSwitch(value);
17196     }
17197 
17198     @Override
stopUser(final int userId, boolean force, final IStopUserCallback callback)17199     public int stopUser(final int userId, boolean force, final IStopUserCallback callback) {
17200         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ false,
17201                 /* callback= */ callback, /* keyEvictedCallback= */ null);
17202     }
17203 
17204     /**
17205      * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after
17206      * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true.
17207      *
17208      * <p>When delayed locking is not enabled through the overlay, this call becomes the same
17209      * with {@link #stopUser(int, boolean, IStopUserCallback)} call.
17210      *
17211      * @param userId User id to stop.
17212      * @param force Force stop the user even if the user is related with system user or current
17213      *              user.
17214      * @param callback Callback called when user has stopped.
17215      *
17216      * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns
17217      *         other {@code ActivityManager#USER_OP_*} codes for failure.
17218      *
17219      */
17220     @Override
stopUserWithDelayedLocking(final int userId, boolean force, final IStopUserCallback callback)17221     public int stopUserWithDelayedLocking(final int userId, boolean force,
17222             final IStopUserCallback callback) {
17223         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ true,
17224                 /* callback= */ callback, /* keyEvictedCallback= */ null);
17225     }
17226 
17227     @Override
startProfile(@serIdInt int userId)17228     public boolean startProfile(@UserIdInt int userId) {
17229         return mUserController.startProfile(userId, /* evenWhenDisabled= */ false,
17230                 /* unlockListener= */ null);
17231     }
17232 
17233     @Override
startProfileWithListener(@serIdInt int userId, @Nullable IProgressListener unlockListener)17234     public boolean startProfileWithListener(@UserIdInt int userId,
17235             @Nullable IProgressListener unlockListener) {
17236         return mUserController.startProfile(userId, /* evenWhenDisabled= */ false, unlockListener);
17237     }
17238 
17239     @Override
stopProfile(@serIdInt int userId)17240     public boolean stopProfile(@UserIdInt int userId) {
17241         return mUserController.stopProfile(userId);
17242     }
17243 
17244     @Override
getCurrentUser()17245     public UserInfo getCurrentUser() {
17246         return mUserController.getCurrentUser();
17247     }
17248 
17249     @Override
getCurrentUserId()17250     public @UserIdInt int getCurrentUserId() {
17251         return mUserController.getCurrentUserIdChecked();
17252     }
17253 
getStartedUserState(int userId)17254     String getStartedUserState(int userId) {
17255         final UserState userState = mUserController.getStartedUserState(userId);
17256         return UserState.stateToString(userState.state);
17257     }
17258 
17259     @Override
isUserRunning(int userId, int flags)17260     public boolean isUserRunning(int userId, int flags) {
17261         if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId())
17262                 && checkCallingPermission(INTERACT_ACROSS_USERS)
17263                     != PackageManager.PERMISSION_GRANTED) {
17264             String msg = "Permission Denial: isUserRunning() from pid="
17265                     + Binder.getCallingPid()
17266                     + ", uid=" + Binder.getCallingUid()
17267                     + " requires " + INTERACT_ACROSS_USERS;
17268             Slog.w(TAG, msg);
17269             throw new SecurityException(msg);
17270         }
17271         return mUserController.isUserRunning(userId, flags);
17272     }
17273 
17274     @Override
getRunningUserIds()17275     public int[] getRunningUserIds() {
17276         if (checkCallingPermission(INTERACT_ACROSS_USERS)
17277                 != PackageManager.PERMISSION_GRANTED) {
17278             String msg = "Permission Denial: isUserRunning() from pid="
17279                     + Binder.getCallingPid()
17280                     + ", uid=" + Binder.getCallingUid()
17281                     + " requires " + INTERACT_ACROSS_USERS;
17282             Slog.w(TAG, msg);
17283             throw new SecurityException(msg);
17284         }
17285         return mUserController.getStartedUserArray();
17286     }
17287 
17288     @Override
registerUserSwitchObserver(IUserSwitchObserver observer, String name)17289     public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
17290         mUserController.registerUserSwitchObserver(observer, name);
17291     }
17292 
17293     @Override
unregisterUserSwitchObserver(IUserSwitchObserver observer)17294     public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
17295         mUserController.unregisterUserSwitchObserver(observer);
17296     }
17297 
getAppInfoForUser(ApplicationInfo info, int userId)17298     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
17299         if (info == null) return null;
17300         ApplicationInfo newInfo = new ApplicationInfo(info);
17301         newInfo.initForUser(userId);
17302         return newInfo;
17303     }
17304 
isUserStopped(int userId)17305     public boolean isUserStopped(int userId) {
17306         return mUserController.getStartedUserState(userId) == null;
17307     }
17308 
getActivityInfoForUser(ActivityInfo aInfo, int userId)17309     ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
17310         if (aInfo == null
17311                 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
17312             return aInfo;
17313         }
17314 
17315         ActivityInfo info = new ActivityInfo(aInfo);
17316         info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
17317         return info;
17318     }
17319 
17320     @GuardedBy("mProcLock")
processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)17321     private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) {
17322         if (process == null || thread == null) {
17323             return false;
17324         }
17325 
17326         return Build.IS_DEBUGGABLE || process.isDebuggable();
17327     }
17328 
startBinderTracking()17329     public boolean startBinderTracking() throws RemoteException {
17330         // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17331         // permission (same as profileControl).
17332         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17333                 != PackageManager.PERMISSION_GRANTED) {
17334             throw new SecurityException("Requires permission "
17335                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17336         }
17337 
17338         synchronized (mProcLock) {
17339             mBinderTransactionTrackingEnabled = true;
17340             mProcessList.forEachLruProcessesLOSP(true, process -> {
17341                 final IApplicationThread thread = process.getThread();
17342                 if (!processSanityChecksLPr(process, thread)) {
17343                     return;
17344                 }
17345                 try {
17346                     thread.startBinderTracking();
17347                 } catch (RemoteException e) {
17348                     Log.v(TAG, "Process disappared");
17349                 }
17350             });
17351         }
17352         return true;
17353     }
17354 
17355     @Override
stopBinderTrackingAndDump(final ParcelFileDescriptor fd)17356     public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException {
17357         // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17358         // permission (same as profileControl).
17359         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17360                 != PackageManager.PERMISSION_GRANTED) {
17361             throw new SecurityException("Requires permission "
17362                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17363         }
17364 
17365         boolean closeFd = true;
17366         try {
17367             synchronized (mProcLock) {
17368                 if (fd == null) {
17369                     throw new IllegalArgumentException("null fd");
17370                 }
17371                 mBinderTransactionTrackingEnabled = false;
17372 
17373                 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor()));
17374                 pw.println("Binder transaction traces for all processes.\n");
17375                 mProcessList.forEachLruProcessesLOSP(true, process -> {
17376                     final IApplicationThread thread = process.getThread();
17377                     if (!processSanityChecksLPr(process, thread)) {
17378                         return;
17379                     }
17380 
17381                     pw.println("Traces for process: " + process.processName);
17382                     pw.flush();
17383                     try {
17384                         TransferPipe tp = new TransferPipe();
17385                         try {
17386                             thread.stopBinderTrackingAndDump(tp.getWriteFd());
17387                             tp.go(fd.getFileDescriptor());
17388                         } finally {
17389                             tp.kill();
17390                         }
17391                     } catch (IOException e) {
17392                         pw.println("Failure while dumping IPC traces from " + process +
17393                                 ".  Exception: " + e);
17394                         pw.flush();
17395                     } catch (RemoteException e) {
17396                         pw.println("Got a RemoteException while dumping IPC traces from " +
17397                                 process + ".  Exception: " + e);
17398                         pw.flush();
17399                     }
17400                 });
17401                 closeFd = false;
17402                 return true;
17403             }
17404         } finally {
17405             if (fd != null && closeFd) {
17406                 try {
17407                     fd.close();
17408                 } catch (IOException e) {
17409                 }
17410             }
17411         }
17412     }
17413 
onProcessFreezableChangedLocked(ProcessRecord app)17414     void onProcessFreezableChangedLocked(ProcessRecord app) {
17415         if (mEnableModernQueue) {
17416             mBroadcastQueues[0].onProcessFreezableChangedLocked(app);
17417         }
17418     }
17419 
17420     @VisibleForTesting
17421     public final class LocalService extends ActivityManagerInternal
17422             implements ActivityManagerLocal {
17423 
17424         @Override
getPendingIntentStats()17425         public List<PendingIntentStats> getPendingIntentStats() {
17426             return mPendingIntentController.dumpPendingIntentStatsForStatsd();
17427         }
17428 
17429         @Override
getAppProfileStatsForDebugging(long time, int lines)17430         public Pair<String, String> getAppProfileStatsForDebugging(long time, int lines) {
17431             return mAppProfiler.getAppProfileStatsForDebugging(time, lines);
17432         }
17433 
17434         @Override
checkContentProviderAccess(String authority, int userId)17435         public String checkContentProviderAccess(String authority, int userId) {
17436             return mCpHelper.checkContentProviderAccess(authority, userId);
17437         }
17438 
17439         @Override
checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)17440         public int checkContentProviderUriPermission(Uri uri, int userId,
17441                 int callingUid, int modeFlags) {
17442             return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags);
17443         }
17444 
17445         @Override
onWakefulnessChanged(int wakefulness)17446         public void onWakefulnessChanged(int wakefulness) {
17447             ActivityManagerService.this.onWakefulnessChanged(wakefulness);
17448         }
17449 
17450         @Override
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)17451         public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
17452                 String processName, String abiOverride, int uid, Runnable crashHandler) {
17453             return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
17454                     processName, abiOverride, uid, crashHandler);
17455         }
17456 
17457         @Override
startSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)17458         public ComponentName startSdkSandboxService(Intent service, int clientAppUid,
17459                 String clientAppPackage, String processName) throws RemoteException {
17460             validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName);
17461             if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) != MODE_ALLOWED) {
17462                 throw new IllegalArgumentException("uid does not belong to provided package");
17463             }
17464             // TODO(b/269598719): Is passing the application thread of the system_server alright?
17465             // e.g. the sandbox getting privileged access due to this.
17466             ComponentName cn = ActivityManagerService.this.startService(
17467                     mContext.getIApplicationThread(), service,
17468                     service.resolveTypeIfNeeded(mContext.getContentResolver()), false,
17469                     mContext.getOpPackageName(), mContext.getAttributionTag(),
17470                     UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage,
17471                     processName);
17472             if (cn != null) {
17473                 if (cn.getPackageName().equals("!")) {
17474                     throw new SecurityException(
17475                             "Not allowed to start service " + service
17476                                     + " without permission " + cn.getClassName());
17477                 } else if (cn.getPackageName().equals("!!")) {
17478                     throw new SecurityException(
17479                             "Unable to start service " + service
17480                                     + ": " + cn.getClassName());
17481                 } else if (cn.getPackageName().equals("?")) {
17482                     throw ServiceStartNotAllowedException.newInstance(false,
17483                             "Not allowed to start service " + service + ": "
17484                                     + cn.getClassName());
17485                 }
17486             }
17487 
17488             return cn;
17489         }
17490 
17491         @Override
stopSdkSandboxService(Intent service, int clientAppUid, String clientAppPackage, String processName)17492         public boolean stopSdkSandboxService(Intent service, int clientAppUid,
17493                 String clientAppPackage, String processName) {
17494             validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName);
17495             int res = ActivityManagerService.this.stopService(
17496                     mContext.getIApplicationThread(), service,
17497                     service.resolveTypeIfNeeded(mContext.getContentResolver()),
17498                     UserHandle.getUserId(clientAppUid), true, clientAppUid, clientAppPackage,
17499                     processName);
17500             if (res < 0) {
17501                 throw new SecurityException(
17502                         "Not allowed to stop service " + service);
17503             }
17504             return res != 0;
17505         }
17506 
17507         @Override
bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, int flags)17508         public boolean bindSdkSandboxService(Intent service, ServiceConnection conn,
17509                 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage,
17510                 String processName, int flags)
17511                 throws RemoteException {
17512             return bindSdkSandboxServiceInternal(service, conn, clientAppUid,
17513                     clientApplicationThread, clientAppPackage, processName,
17514                     Integer.toUnsignedLong(flags));
17515         }
17516 
17517         @Override
bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, BindServiceFlags flags)17518         public boolean bindSdkSandboxService(Intent service, ServiceConnection conn,
17519                 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage,
17520                 String processName, BindServiceFlags flags) throws RemoteException {
17521             return bindSdkSandboxServiceInternal(service, conn, clientAppUid,
17522                     clientApplicationThread, clientAppPackage, processName, flags.getValue());
17523         }
17524 
bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn, int clientAppUid, IBinder clientApplicationThread, String clientAppPackage, String processName, long flags)17525         private boolean bindSdkSandboxServiceInternal(Intent service, ServiceConnection conn,
17526                 int clientAppUid, IBinder clientApplicationThread, String clientAppPackage,
17527                 String processName, long flags)
17528                 throws RemoteException {
17529             validateSdkSandboxParams(service, clientAppUid, clientAppPackage, processName);
17530             if (mAppOpsService.checkPackage(clientAppUid, clientAppPackage) != MODE_ALLOWED) {
17531                 throw new IllegalArgumentException("uid does not belong to provided package");
17532             }
17533             if (conn == null) {
17534                 throw new IllegalArgumentException("connection is null");
17535             }
17536 
17537             Handler handler = mContext.getMainThreadHandler();
17538             IApplicationThread clientApplicationThreadVerified = null;
17539             if (clientApplicationThread != null) {
17540                 // Make sure this is a valid application process
17541                 synchronized (this) {
17542                     final ProcessRecord rec = getRecordForAppLOSP(clientApplicationThread);
17543                     if (rec == null) {
17544                         // This could happen if the calling process has disappeared; no need for the
17545                         // sandbox to be even started in this case.
17546                         Slog.i(TAG, "clientApplicationThread process not found.");
17547                         return false;
17548                     }
17549                     if (rec.info.uid != clientAppUid) {
17550                         throw new IllegalArgumentException("clientApplicationThread does not match "
17551                                 + " client uid");
17552                     }
17553                     clientApplicationThreadVerified = rec.getThread();
17554                 }
17555             }
17556             final IServiceConnection sd = mContext.getServiceDispatcher(conn, handler,
17557                     flags);
17558             service.prepareToLeaveProcess(mContext);
17559             return ActivityManagerService.this.bindServiceInstance(
17560                     mContext.getIApplicationThread(), mContext.getActivityToken(), service,
17561                     service.resolveTypeIfNeeded(mContext.getContentResolver()), sd,
17562                     flags,
17563                     processName, /*isSdkSandboxService*/ true, clientAppUid, clientAppPackage,
17564                     clientApplicationThreadVerified, mContext.getOpPackageName(),
17565                     UserHandle.getUserId(clientAppUid)) != 0;
17566         }
17567 
validateSdkSandboxParams(Intent service, int clientAppUid, String clientAppPackage, String processName)17568         private void validateSdkSandboxParams(Intent service, int clientAppUid,
17569                 String clientAppPackage, String processName) {
17570             if (service == null) {
17571                 throw new IllegalArgumentException("intent is null");
17572             }
17573             if (clientAppPackage == null) {
17574                 throw new IllegalArgumentException("clientAppPackage is null");
17575             }
17576             if (processName == null) {
17577                 throw new IllegalArgumentException("processName is null");
17578             }
17579             if (service.getComponent() == null) {
17580                 throw new IllegalArgumentException("service must specify explicit component");
17581             }
17582             if (!UserHandle.isApp(clientAppUid)) {
17583                 throw new IllegalArgumentException("uid is not within application range");
17584             }
17585         }
17586 
17587         @Override
bindSdkSandboxService(Intent service, ServiceConnection conn, int clientAppUid, String clientAppPackage, String processName, int flags)17588         public boolean bindSdkSandboxService(Intent service, ServiceConnection conn,
17589                 int clientAppUid, String clientAppPackage, String processName, int flags)
17590                 throws RemoteException {
17591             return bindSdkSandboxService(service, conn, clientAppUid,
17592                     null /* clientApplicationThread */, clientAppPackage, processName, flags);
17593         }
17594 
17595         @Override
killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder)17596         public void killSdkSandboxClientAppProcess(IBinder clientApplicationThreadBinder) {
17597             synchronized (ActivityManagerService.this) {
17598                 ProcessRecord r = getRecordForAppLOSP(clientApplicationThreadBinder);
17599                 if (r != null) {
17600                     r.killLocked(
17601                             "sdk sandbox died",
17602                             ApplicationExitInfo.REASON_DEPENDENCY_DIED,
17603                             ApplicationExitInfo.SUBREASON_SDK_SANDBOX_DIED,
17604                             true);
17605                 }
17606             }
17607         }
17608 
17609         @Override
onUserRemoved(@serIdInt int userId)17610         public void onUserRemoved(@UserIdInt int userId) {
17611             // Clean up any ActivityTaskManager state (by telling it the user is stopped)
17612             mAtmInternal.onUserStopped(userId);
17613             // Clean up various services by removing the user
17614             mBatteryStatsService.onUserRemoved(userId);
17615         }
17616 
17617         @Override
killForegroundAppsForUser(@serIdInt int userId)17618         public void killForegroundAppsForUser(@UserIdInt int userId) {
17619             final ArrayList<ProcessRecord> procs = new ArrayList<>();
17620             synchronized (mProcLock) {
17621                 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size();
17622                 for (int ip = 0; ip < numOfProcs; ip++) {
17623                     final SparseArray<ProcessRecord> apps =
17624                             mProcessList.getProcessNamesLOSP().getMap().valueAt(ip);
17625                     final int NA = apps.size();
17626                     for (int ia = 0; ia < NA; ia++) {
17627                         final ProcessRecord app = apps.valueAt(ia);
17628                         if (app.isPersistent()) {
17629                             // We don't kill persistent processes.
17630                             continue;
17631                         }
17632                         if (app.isRemoved()
17633                                 || (app.userId == userId && app.mState.hasForegroundActivities())) {
17634                             procs.add(app);
17635                         }
17636                     }
17637                 }
17638             }
17639 
17640             final int numOfProcs = procs.size();
17641             if (numOfProcs > 0) {
17642                 synchronized (ActivityManagerService.this) {
17643                     for (int i = 0; i < numOfProcs; i++) {
17644                         mProcessList.removeProcessLocked(procs.get(i), false, true,
17645                                 ApplicationExitInfo.REASON_OTHER,
17646                                 ApplicationExitInfo.SUBREASON_KILL_ALL_FG,
17647                                 "kill all fg");
17648                     }
17649                 }
17650             }
17651         }
17652 
17653         @Override
setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)17654         public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken,
17655                 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) {
17656             mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken,
17657                     duration, type, reasonCode, reason);
17658         }
17659 
17660         @Override
getPendingIntentFlags(IIntentSender target)17661         public int getPendingIntentFlags(IIntentSender target) {
17662             return mPendingIntentController.getPendingIntentFlags(target);
17663         }
17664 
17665         @Override
getStartedUserIds()17666         public int[] getStartedUserIds() {
17667             return mUserController.getStartedUserArray();
17668         }
17669 
17670         @Override
setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)17671         public void setPendingIntentAllowBgActivityStarts(IIntentSender target,
17672                 IBinder allowlistToken, int flags) {
17673             if (!(target instanceof PendingIntentRecord)) {
17674                 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():"
17675                         + " not a PendingIntentRecord: " + target);
17676                 return;
17677             }
17678             synchronized (ActivityManagerService.this) {
17679                 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags);
17680             }
17681         }
17682 
17683         @Override
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)17684         public void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
17685                 IBinder allowlistToken) {
17686             if (!(target instanceof PendingIntentRecord)) {
17687                 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():"
17688                         + " not a PendingIntentRecord: " + target);
17689                 return;
17690             }
17691             synchronized (ActivityManagerService.this) {
17692                 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken);
17693             }
17694         }
17695 
17696         @Override
setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)17697         public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) {
17698             synchronized (ActivityManagerService.this) {
17699                 synchronized (mProcLock) {
17700                     mDeviceIdleAllowlist = allAppids;
17701                     mDeviceIdleExceptIdleAllowlist = exceptIdleAppids;
17702                     mAppRestrictionController.setDeviceIdleAllowlist(allAppids, exceptIdleAppids);
17703                 }
17704             }
17705         }
17706 
17707         @Override
updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)17708         public void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid,
17709                 boolean adding, long durationMs, @TempAllowListType int type,
17710                 @ReasonCode int reasonCode, @Nullable String reason, int callingUid) {
17711             synchronized (ActivityManagerService.this) {
17712                 synchronized (mProcLock) {
17713                     if (appids != null) {
17714                         mDeviceIdleTempAllowlist = appids;
17715                     }
17716                     if (adding) {
17717                         if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) {
17718                             // Note, the device idle temp-allowlist are by app-ids, but here
17719                             // mFgsStartTempAllowList contains UIDs.
17720                             mFgsStartTempAllowList.add(changingUid, durationMs,
17721                                     new FgsTempAllowListItem(durationMs, reasonCode, reason,
17722                                     callingUid));
17723                         }
17724                     } else {
17725                         mFgsStartTempAllowList.removeUid(changingUid);
17726                     }
17727                     setAppIdTempAllowlistStateLSP(changingUid, adding);
17728                 }
17729             }
17730         }
17731 
17732         @Override
getUidProcessState(int uid)17733         public int getUidProcessState(int uid) {
17734             return getUidState(uid);
17735         }
17736 
17737         @Override
getProcessesWithPendingBindMounts(int userId)17738         public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) {
17739             return mProcessList.getProcessesWithPendingBindMounts(userId);
17740         }
17741 
17742         @Override
isSystemReady()17743         public boolean isSystemReady() {
17744             // no need to synchronize(this) just to read & return the value
17745             return mSystemReady;
17746         }
17747 
17748         @Override
isModernQueueEnabled()17749         public boolean isModernQueueEnabled() {
17750             return mEnableModernQueue;
17751         }
17752 
17753         @Override
enforceBroadcastOptionsPermissions(Bundle options, int callingUid)17754         public void enforceBroadcastOptionsPermissions(Bundle options, int callingUid) {
17755             enforceBroadcastOptionPermissionsInternal(options, callingUid);
17756         }
17757 
17758         /**
17759          * Returns package name by pid.
17760          */
17761         @Override
17762         @Nullable
getPackageNameByPid(int pid)17763         public String getPackageNameByPid(int pid) {
17764             synchronized (mPidsSelfLocked) {
17765                 final ProcessRecord app = mPidsSelfLocked.get(pid);
17766 
17767                 if (app != null && app.info != null) {
17768                     return app.info.packageName;
17769                 }
17770 
17771                 return null;
17772             }
17773         }
17774 
17775         /**
17776          * Sets if the given pid has an overlay UI or not.
17777          *
17778          * @param pid The pid we are setting overlay UI for.
17779          * @param hasOverlayUi True if the process has overlay UI.
17780          * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
17781          */
17782         @Override
setHasOverlayUi(int pid, boolean hasOverlayUi)17783         public void setHasOverlayUi(int pid, boolean hasOverlayUi) {
17784             synchronized (ActivityManagerService.this) {
17785                 final ProcessRecord pr;
17786                 synchronized (mPidsSelfLocked) {
17787                     pr = mPidsSelfLocked.get(pid);
17788                     if (pr == null) {
17789                         Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid);
17790                         return;
17791                     }
17792                 }
17793                 if (pr.mState.hasOverlayUi() == hasOverlayUi) {
17794                     return;
17795                 }
17796                 pr.mState.setHasOverlayUi(hasOverlayUi);
17797                 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid);
17798                 updateOomAdjLocked(pr, OOM_ADJ_REASON_UI_VISIBILITY);
17799             }
17800         }
17801 
17802         /**
17803          * Called after the network policy rules are updated by
17804          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
17805          * and {@param procStateSeq}.
17806          */
17807         @Override
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)17808         public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
17809             if (DEBUG_NETWORK) {
17810                 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: "
17811                         + uid + " seq: " + procStateSeq);
17812             }
17813             UidRecord record;
17814             synchronized (mProcLock) {
17815                 record = mProcessList.getUidRecordLOSP(uid);
17816                 if (record == null) {
17817                     if (DEBUG_NETWORK) {
17818                         Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
17819                                 + " procStateSeq: " + procStateSeq);
17820                     }
17821                     return;
17822                 }
17823             }
17824             synchronized (record.networkStateLock) {
17825                 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
17826                     if (DEBUG_NETWORK) {
17827                         Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already"
17828                                 + " been handled for uid: " + uid);
17829                     }
17830                     return;
17831                 }
17832                 record.lastNetworkUpdatedProcStateSeq = procStateSeq;
17833                 if (record.procStateSeqWaitingForNetwork != 0
17834                         && procStateSeq >= record.procStateSeqWaitingForNetwork) {
17835                     if (DEBUG_NETWORK) {
17836                         Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid
17837                                 + ", procStateSeq: " + procStateSeq
17838                                 + ", procStateSeqWaitingForNetwork: "
17839                                 + record.procStateSeqWaitingForNetwork);
17840                     }
17841                     record.networkStateLock.notifyAll();
17842                 }
17843             }
17844         }
17845 
17846         @Override
onUidBlockedReasonsChanged(int uid, int blockedReasons)17847         public void onUidBlockedReasonsChanged(int uid, int blockedReasons) {
17848             synchronized (mUidNetworkBlockedReasons) {
17849                 if (blockedReasons == BLOCKED_REASON_NONE) {
17850                     mUidNetworkBlockedReasons.delete(uid);
17851                 } else {
17852                     mUidNetworkBlockedReasons.put(uid, blockedReasons);
17853                 }
17854             }
17855         }
17856 
17857         @Override
isRuntimeRestarted()17858         public boolean isRuntimeRestarted() {
17859             return mSystemServiceManager.isRuntimeRestarted();
17860         }
17861 
17862         @Override
canStartMoreUsers()17863         public boolean canStartMoreUsers() {
17864             return mUserController.canStartMoreUsers();
17865         }
17866 
17867         @Override
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)17868         public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
17869             mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage);
17870         }
17871 
17872         @Override
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)17873         public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
17874             mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage);
17875         }
17876 
17877         @Override
getMaxRunningUsers()17878         public int getMaxRunningUsers() {
17879             return mUserController.getMaxRunningUsers();
17880         }
17881 
17882         @Override
isUidActive(int uid)17883         public boolean isUidActive(int uid) {
17884             synchronized (mProcLock) {
17885                 return isUidActiveLOSP(uid);
17886             }
17887         }
17888 
17889         @Override
getMemoryStateForProcesses()17890         public List<ProcessMemoryState> getMemoryStateForProcesses() {
17891             List<ProcessMemoryState> processMemoryStates = new ArrayList<>();
17892             synchronized (mPidsSelfLocked) {
17893                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
17894                     final ProcessRecord r = mPidsSelfLocked.valueAt(i);
17895                     processMemoryStates.add(new ProcessMemoryState(
17896                             r.uid, r.getPid(), r.processName, r.mState.getCurAdj(),
17897                             r.mServices.hasForegroundServices(),
17898                             r.mProfile.getCurrentHostingComponentTypes(),
17899                             r.mProfile.getHistoricalHostingComponentTypes()));
17900                 }
17901             }
17902             return processMemoryStates;
17903         }
17904 
17905         @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)17906         public int handleIncomingUser(int callingPid, int callingUid, int userId,
17907                 boolean allowAll, int allowMode, String name, String callerPackage) {
17908             return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
17909                     allowMode, name, callerPackage);
17910         }
17911 
17912         @Override
enforceCallingPermission(String permission, String func)17913         public void enforceCallingPermission(String permission, String func) {
17914             ActivityManagerService.this.enforceCallingPermission(permission, func);
17915         }
17916 
17917         @Override
getCurrentAndTargetUserIds()17918         public Pair<Integer, Integer> getCurrentAndTargetUserIds() {
17919             return mUserController.getCurrentAndTargetUserIds();
17920         }
17921 
17922         @Override
getCurrentUserId()17923         public int getCurrentUserId() {
17924             return mUserController.getCurrentUserId();
17925         }
17926 
17927         @Override
isUserRunning(int userId, int flags)17928         public boolean isUserRunning(int userId, int flags) {
17929             // Holding am lock isn't required to call into user controller.
17930             return mUserController.isUserRunning(userId, flags);
17931         }
17932 
17933         @Override
trimApplications()17934         public void trimApplications() {
17935             ActivityManagerService.this.trimApplications(true, OOM_ADJ_REASON_ACTIVITY);
17936         }
17937 
killProcessesForRemovedTask(ArrayList<Object> procsToKill)17938         public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) {
17939             synchronized (ActivityManagerService.this) {
17940                 for (int i = 0; i < procsToKill.size(); i++) {
17941                     final WindowProcessController wpc =
17942                             (WindowProcessController) procsToKill.get(i);
17943                     final ProcessRecord pr = (ProcessRecord) wpc.mOwner;
17944                     if (ActivityManager.isProcStateBackground(pr.mState.getSetProcState())
17945                             && pr.mReceivers.numberOfCurReceivers() == 0) {
17946                         pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED,
17947                                 ApplicationExitInfo.SUBREASON_REMOVE_TASK, true);
17948                     } else {
17949                         // We delay killing processes that are not in the background or running a
17950                         // receiver.
17951                         pr.setWaitingToKill("remove task");
17952                     }
17953                 }
17954             }
17955         }
17956 
17957         @Override
killProcess(String processName, int uid, String reason)17958         public void killProcess(String processName, int uid, String reason) {
17959             synchronized (ActivityManagerService.this) {
17960                 final ProcessRecord proc = getProcessRecordLocked(processName, uid);
17961                 if (proc != null) {
17962                     mProcessList.removeProcessLocked(proc, false /* callerWillRestart */,
17963                             true /* allowRestart */,  ApplicationExitInfo.REASON_OTHER, reason);
17964                 }
17965             }
17966         }
17967 
17968         @Override
hasRunningActivity(int uid, @Nullable String packageName)17969         public boolean hasRunningActivity(int uid, @Nullable String packageName) {
17970             if (packageName == null) return false;
17971 
17972             synchronized (mProcLock) {
17973                 return mProcessList.searchEachLruProcessesLOSP(true, app -> {
17974                     if (app.uid == uid
17975                             && app.getWindowProcessController().hasRunningActivity(packageName)) {
17976                         return Boolean.TRUE;
17977                     }
17978                     return null;
17979                 }) != null;
17980             }
17981         }
17982 
17983         @Override
updateOomAdj(@omAdjReason int oomAdjReason)17984         public void updateOomAdj(@OomAdjReason int oomAdjReason) {
17985             synchronized (ActivityManagerService.this) {
17986                 ActivityManagerService.this.updateOomAdjLocked(oomAdjReason);
17987             }
17988         }
17989 
17990         @Override
updateCpuStats()17991         public void updateCpuStats() {
17992             ActivityManagerService.this.updateCpuStats();
17993         }
17994 
17995         @Override
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)17996         public void updateBatteryStats(ComponentName activity, int uid, int userId,
17997                 boolean resumed) {
17998             ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed);
17999         }
18000 
18001         @Override
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot, ActivityId activityId)18002         public void updateActivityUsageStats(ComponentName activity, int userId, int event,
18003                 IBinder appToken, ComponentName taskRoot, ActivityId activityId) {
18004             ActivityManagerService.this.updateActivityUsageStats(activity, userId, event,
18005                     appToken, taskRoot, activityId);
18006         }
18007 
18008         @Override
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)18009         public void updateForegroundTimeIfOnBattery(
18010                 String packageName, int uid, long cpuTimeDiff) {
18011             mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff);
18012         }
18013 
18014         @Override
sendForegroundProfileChanged(int userId)18015         public void sendForegroundProfileChanged(int userId) {
18016             mUserController.sendForegroundProfileChanged(userId);
18017         }
18018 
18019         @Override
shouldConfirmCredentials(int userId)18020         public boolean shouldConfirmCredentials(int userId) {
18021             return mUserController.shouldConfirmCredentials(userId);
18022         }
18023 
18024         @Override
noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)18025         public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid,
18026                 String tag) {
18027             ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null,
18028                     workSource, sourceUid, tag);
18029         }
18030 
18031         @Override
noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)18032         public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid,
18033                 String tag) {
18034             ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null,
18035                     workSource, sourceUid, tag);
18036         }
18037 
18038         @Override
noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)18039         public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid,
18040                 String sourcePkg, String tag) {
18041             ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
18042                     workSource, sourceUid, sourcePkg, tag);
18043         }
18044 
18045         @Override
isAppStartModeDisabled(int uid, String packageName)18046         public boolean isAppStartModeDisabled(int uid, String packageName) {
18047             return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName);
18048         }
18049 
18050         @Override
getCurrentProfileIds()18051         public int[] getCurrentProfileIds() {
18052             return mUserController.getCurrentProfileIds();
18053         }
18054 
18055         @Override
getCurrentUser()18056         public UserInfo getCurrentUser() {
18057             return mUserController.getCurrentUser();
18058         }
18059 
18060         @Override
ensureNotSpecialUser(int userId)18061         public void ensureNotSpecialUser(int userId) {
18062             mUserController.ensureNotSpecialUser(userId);
18063         }
18064 
18065         @Override
isCurrentProfile(int userId)18066         public boolean isCurrentProfile(int userId) {
18067             return mUserController.isCurrentProfile(userId);
18068         }
18069 
18070         @Override
hasStartedUserState(int userId)18071         public boolean hasStartedUserState(int userId) {
18072             return mUserController.hasStartedUserState(userId);
18073         }
18074 
18075         @Override
finishUserSwitch(Object uss)18076         public void finishUserSwitch(Object uss) {
18077             mUserController.finishUserSwitch((UserState) uss);
18078         }
18079 
18080         @Override
scheduleAppGcs()18081         public void scheduleAppGcs() {
18082             synchronized (mAppProfiler.mProfilerLock) {
18083                 mAppProfiler.scheduleAppGcsLPf();
18084             }
18085         }
18086 
18087         @Override
getTaskIdForActivity(IBinder token, boolean onlyRoot)18088         public int getTaskIdForActivity(IBinder token, boolean onlyRoot) {
18089             return ActivityManagerService.this.getTaskForActivity(token, onlyRoot);
18090         }
18091 
18092         @Override
getActivityPresentationInfo(IBinder token)18093         public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
18094             final ActivityClient ac = ActivityClient.getInstance();
18095             return new ActivityPresentationInfo(ac.getTaskForActivity(token,
18096                     /*onlyRoot=*/ false), ac.getDisplayId(token),
18097                     mAtmInternal.getActivityName(token));
18098         }
18099 
18100         @Override
setBooting(boolean booting)18101         public void setBooting(boolean booting) {
18102             mBooting = booting;
18103         }
18104 
18105         @Override
isBooting()18106         public boolean isBooting() {
18107             return mBooting;
18108         }
18109 
18110         @Override
setBooted(boolean booted)18111         public void setBooted(boolean booted) {
18112             mBooted = booted;
18113         }
18114 
18115         @Override
isBooted()18116         public boolean isBooted() {
18117             return mBooted;
18118         }
18119 
18120         @Override
finishBooting()18121         public void finishBooting() {
18122             ActivityManagerService.this.finishBooting();
18123         }
18124 
18125         @Override
tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)18126         public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid,
18127                 long duration, int type, @ReasonCode int reasonCode, String reason) {
18128             synchronized (ActivityManagerService.this) {
18129                 ActivityManagerService.this.tempAllowlistForPendingIntentLocked(
18130                         callerPid, callerUid, targetUid, duration, type, reasonCode, reason);
18131             }
18132         }
18133 
18134         @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)18135         public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
18136                 int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
18137                 IApplicationThread resultToThread, IIntentReceiver resultTo, int resultCode,
18138                 String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions,
18139                 boolean serialized, boolean sticky, int userId,
18140                 BackgroundStartPrivileges backgroundStartPrivileges,
18141                 @Nullable int[] broadcastAllowList) {
18142             synchronized (ActivityManagerService.this) {
18143                 final ProcessRecord resultToApp = getRecordForAppLOSP(resultToThread);
18144                 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId,
18145                         uid, realCallingUid, realCallingPid, intent, resolvedType, resultToApp,
18146                         resultTo, resultCode, resultData, resultExtras, requiredPermission,
18147                         bOptions, serialized, sticky, userId,
18148                         backgroundStartPrivileges,
18149                         broadcastAllowList);
18150             }
18151         }
18152 
18153         @Override
broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)18154         public int broadcastIntent(Intent intent,
18155                 IIntentReceiver resultTo,
18156                 String[] requiredPermissions,
18157                 boolean serialized, int userId, int[] appIdAllowList,
18158                 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
18159                 @Nullable Bundle bOptions) {
18160             synchronized (ActivityManagerService.this) {
18161                 intent = verifyBroadcastLocked(intent);
18162 
18163                 final int callingPid = Binder.getCallingPid();
18164                 final int callingUid = Binder.getCallingUid();
18165                 final long origId = Binder.clearCallingIdentity();
18166                 try {
18167                     return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/,
18168                             null /*callerPackage*/, null /*callingFeatureId*/, intent,
18169                             null /* resolvedType */, null /* resultToApp */, resultTo,
18170                             0 /* resultCode */, null /* resultData */,
18171                             null /* resultExtras */, requiredPermissions,
18172                             null /*excludedPermissions*/, null /*excludedPackages*/,
18173                             AppOpsManager.OP_NONE, bOptions /*options*/, serialized,
18174                             false /*sticky*/, callingPid, callingUid, callingUid, callingPid,
18175                             userId, BackgroundStartPrivileges.NONE,
18176                             appIdAllowList, filterExtrasForReceiver);
18177                 } finally {
18178                     Binder.restoreCallingIdentity(origId);
18179                 }
18180             }
18181 
18182         }
18183 
18184         @Override
broadcastIntentWithCallback(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, int userId, int[] appIdAllowList, @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver, @Nullable Bundle bOptions)18185         public int broadcastIntentWithCallback(Intent intent,
18186                 IIntentReceiver resultTo,
18187                 String[] requiredPermissions,
18188                 int userId, int[] appIdAllowList,
18189                 @Nullable BiFunction<Integer, Bundle, Bundle> filterExtrasForReceiver,
18190                 @Nullable Bundle bOptions) {
18191             // Sending broadcasts with a finish callback without the need for the broadcasts
18192             // delivery to be serialized is only supported by modern queue. So, when modern
18193             // queue is disabled, we continue to send broadcasts in a serialized fashion.
18194             final boolean serialized = !isModernQueueEnabled();
18195             return broadcastIntent(intent, resultTo, requiredPermissions, serialized, userId,
18196                     appIdAllowList, filterExtrasForReceiver, bOptions);
18197         }
18198 
18199         @Override
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, BackgroundStartPrivileges backgroundStartPrivileges)18200         public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType,
18201                 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId,
18202                 int userId, BackgroundStartPrivileges backgroundStartPrivileges)
18203                 throws TransactionTooLargeException {
18204             if (DEBUG_SERVICE) {
18205                 Slog.v(TAG_SERVICE,
18206                         "startServiceInPackage: " + service + " type=" + resolvedType);
18207             }
18208             final long origId = Binder.clearCallingIdentity();
18209             ComponentName res;
18210             try {
18211                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18212                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startServiceInPackage: "
18213                             + "intent=" + service + ", caller=" + callingPackage
18214                             + ", fgRequired=" + fgRequired);
18215                 }
18216                 synchronized (ActivityManagerService.this) {
18217                     res = mServices.startServiceLocked(null, service,
18218                             resolvedType, -1, uid, fgRequired, callingPackage,
18219                             callingFeatureId, userId,
18220                             backgroundStartPrivileges);
18221                 }
18222             } finally {
18223                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18224                 Binder.restoreCallingIdentity(origId);
18225             }
18226             return res;
18227         }
18228 
18229         // The arguments here are untyped because the base ActivityManagerInternal class
18230         // doesn't have compile-time visibility into ActivityServiceConnectionHolder or
18231         // ConnectionRecord.
18232         @Override
disconnectActivityFromServices(Object connectionHolder)18233         public void disconnectActivityFromServices(Object connectionHolder) {
18234             // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder
18235             final ActivityServiceConnectionsHolder holder =
18236                     (ActivityServiceConnectionsHolder) connectionHolder;
18237             synchronized (ActivityManagerService.this) {
18238                 synchronized (mProcLock) {
18239                     holder.forEachConnection(cr -> mServices.removeConnectionLocked(
18240                             (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */,
18241                             false /* enqueueOomAdj */));
18242                 }
18243             }
18244         }
18245 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)18246         public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
18247             synchronized(ActivityManagerService.this) {
18248                 mServices.cleanUpServices(userId, component, baseIntent);
18249             }
18250         }
18251 
getActivityInfoForUser(ActivityInfo aInfo, int userId)18252         public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
18253             // Locked intentionally not held as it isn't needed for this case.
18254             return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId);
18255         }
18256 
ensureBootCompleted()18257         public void ensureBootCompleted() {
18258             // Locked intentionally not held as it isn't needed for this case.
18259             ActivityManagerService.this.ensureBootCompleted();
18260         }
18261 
updateOomLevelsForDisplay(int displayId)18262         public void updateOomLevelsForDisplay(int displayId) {
18263             synchronized(ActivityManagerService.this) {
18264                 if (mWindowManager != null) {
18265                     mProcessList.applyDisplaySize(mWindowManager);
18266                 }
18267             }
18268         }
18269 
isActivityStartsLoggingEnabled()18270         public boolean isActivityStartsLoggingEnabled() {
18271             return mConstants.mFlagActivityStartsLoggingEnabled;
18272         }
18273 
isBackgroundActivityStartsEnabled()18274         public boolean isBackgroundActivityStartsEnabled() {
18275             return mConstants.mFlagBackgroundActivityStartsEnabled;
18276         }
18277 
18278         @Override
getBackgroundStartPrivileges(int uid)18279         public BackgroundStartPrivileges getBackgroundStartPrivileges(int uid) {
18280             return ActivityManagerService.this.getBackgroundStartPrivileges(uid);
18281         }
18282 
18283         @Override
canScheduleUserInitiatedJobs(int uid, int pid, String pkgName)18284         public boolean canScheduleUserInitiatedJobs(int uid, int pid, String pkgName) {
18285             return ActivityManagerService.this.canScheduleUserInitiatedJobs(uid, pid, pkgName);
18286         }
18287 
reportCurKeyguardUsageEvent(boolean keyguardShowing)18288         public void reportCurKeyguardUsageEvent(boolean keyguardShowing) {
18289             ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing
18290                     ? UsageEvents.Event.KEYGUARD_SHOWN
18291                     : UsageEvents.Event.KEYGUARD_HIDDEN);
18292         }
18293 
18294         @Override
monitor()18295         public void monitor() {
18296             ActivityManagerService.this.monitor();
18297         }
18298 
18299         @Override
inputDispatchingTimedOut(int pid, boolean aboveSystem, TimeoutRecord timeoutRecord)18300         public long inputDispatchingTimedOut(int pid, boolean aboveSystem,
18301                 TimeoutRecord timeoutRecord) {
18302             return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem,
18303                     timeoutRecord);
18304         }
18305 
18306         @Override
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, TimeoutRecord timeoutRecord)18307         public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
18308                 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
18309                 boolean aboveSystem, TimeoutRecord timeoutRecord) {
18310             return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc,
18311                     activityShortComponentName, aInfo, parentShortComponentName,
18312                     (WindowProcessController) parentProc, aboveSystem, timeoutRecord);
18313         }
18314 
18315         @Override
inputDispatchingResumed(int pid)18316         public void inputDispatchingResumed(int pid) {
18317             final ProcessRecord proc;
18318             synchronized (mPidsSelfLocked) {
18319                 proc = mPidsSelfLocked.get(pid);
18320             }
18321             if (proc != null) {
18322                 mAppErrors.handleDismissAnrDialogs(proc);
18323             }
18324         }
18325 
18326         @Override
rescheduleAnrDialog(Object data)18327         public void rescheduleAnrDialog(Object data) {
18328             Message msg = Message.obtain();
18329             msg.what = SHOW_NOT_RESPONDING_UI_MSG;
18330             msg.obj = (AppNotRespondingDialog.Data) data;
18331 
18332             mUiHandler.sendMessageDelayed(msg, InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
18333         }
18334 
18335         @Override
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)18336         public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) {
18337             synchronized (ActivityManagerService.this) {
18338                 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
18339                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18340                         | Intent.FLAG_RECEIVER_REPLACE_PENDING
18341                         | Intent.FLAG_RECEIVER_FOREGROUND
18342                         | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18343                 final Bundle configChangedOptions = new BroadcastOptions()
18344                         .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
18345                         .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
18346                         .toBundle();
18347                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
18348                         null, null, OP_NONE, configChangedOptions, false, false, MY_PID, SYSTEM_UID,
18349                         Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
18350                 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
18351                     intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
18352                     intent.addFlags(Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND
18353                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
18354                             | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18355                     if (initLocale || !mProcessesReady) {
18356                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
18357                     }
18358                     final BroadcastOptions bOptions = BroadcastOptions.makeBasic();
18359                     bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(),
18360                             TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
18361                             PowerExemptionManager.REASON_LOCALE_CHANGED, "");
18362                     bOptions.setDeliveryGroupPolicy(
18363                             BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT);
18364                     bOptions.setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE);
18365                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
18366                             null, null, OP_NONE, bOptions.toBundle(), false, false, MY_PID,
18367                             SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(),
18368                             UserHandle.USER_ALL);
18369                 }
18370 
18371                 // Send a broadcast to PackageInstallers if the configuration change is interesting
18372                 // for the purposes of installing additional splits.
18373                 if (!initLocale && isSplitConfigurationChange(changes)) {
18374                     intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
18375                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
18376                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
18377 
18378                     // Typically only app stores will have this permission.
18379                     String[] permissions =
18380                             new String[] { android.Manifest.permission.INSTALL_PACKAGES };
18381                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null,
18382                             permissions, null, null, OP_NONE, null, false, false, MY_PID,
18383                             SYSTEM_UID, Binder.getCallingUid(), Binder.getCallingPid(),
18384                             UserHandle.USER_ALL);
18385                 }
18386             }
18387         }
18388 
18389         /**
18390          * Returns true if this configuration change is interesting enough to send an
18391          * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
18392          */
isSplitConfigurationChange(int configDiff)18393         private boolean isSplitConfigurationChange(int configDiff) {
18394             return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
18395         }
18396 
18397         @Override
broadcastCloseSystemDialogs(String reason)18398         public void broadcastCloseSystemDialogs(String reason) {
18399             synchronized (ActivityManagerService.this) {
18400                 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
18401                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18402                         | Intent.FLAG_RECEIVER_FOREGROUND);
18403                 if (reason != null) {
18404                     intent.putExtra("reason", reason);
18405                 }
18406 
18407                 final BroadcastOptions options = new BroadcastOptions()
18408                         .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
18409                         .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE);
18410                 if (reason != null) {
18411                     options.setDeliveryGroupMatchingKey(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, reason);
18412                 }
18413                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
18414                         null, null, OP_NONE, options.toBundle(), false, false, -1, SYSTEM_UID,
18415                         Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
18416             }
18417         }
18418 
18419         @Override
appNotResponding(@onNull String processName, int uid, @NonNull TimeoutRecord timeoutRecord)18420         public void appNotResponding(@NonNull String processName, int uid,
18421                 @NonNull TimeoutRecord timeoutRecord) {
18422             ActivityManagerService.this.appNotResponding(processName, uid, timeoutRecord);
18423         }
18424 
18425         @Override
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)18426         public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
18427             synchronized (ActivityManagerService.this) {
18428                 ActivityManagerService.this.killAllBackgroundProcessesExcept(
18429                         minTargetSdk, maxProcState);
18430             }
18431         }
18432 
18433         @Override
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)18434         public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
18435                 boolean isTop, String hostingType, ComponentName hostingName) {
18436             try {
18437                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18438                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
18439                             + processName);
18440                 }
18441                 synchronized (ActivityManagerService.this) {
18442                     // If the process is known as top app, set a hint so when the process is
18443                     // started, the top priority can be applied immediately to avoid cpu being
18444                     // preempted by other processes before attaching the process of top app.
18445                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
18446                             new HostingRecord(hostingType, hostingName, isTop),
18447                             ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
18448                             false /* isolated */);
18449                 }
18450             } finally {
18451                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18452             }
18453         }
18454 
18455         @Override
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)18456         public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
18457                 ProfilerInfo profilerInfo, Object wmLock) {
18458             synchronized (ActivityManagerService.this) {
18459                 /**
18460                  * This function is called from the window manager context and needs to be executed
18461                  * synchronously.  To avoid deadlock, we pass a message to AMS to execute the
18462                  * function and notify the passed in lock when it has been completed.
18463                  */
18464                 synchronized (wmLock) {
18465                     if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
18466                         boolean suspend =
18467                                 (startFlags & ActivityManager.START_FLAG_DEBUG_SUSPEND) != 0;
18468                         setDebugApp(aInfo.processName, true, false, suspend);
18469                     }
18470 
18471                     if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
18472                         setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
18473                     }
18474 
18475                     if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
18476                         setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
18477                     }
18478 
18479                     if (profilerInfo != null) {
18480                         setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo, null);
18481                     }
18482                     wmLock.notify();
18483                 }
18484             }
18485         }
18486 
18487         @Override
getStorageMountMode(int pid, int uid)18488         public int getStorageMountMode(int pid, int uid) {
18489             if (uid == SHELL_UID || uid == ROOT_UID) {
18490                 return Zygote.MOUNT_EXTERNAL_DEFAULT;
18491             }
18492             synchronized (mPidsSelfLocked) {
18493                 final ProcessRecord pr = mPidsSelfLocked.get(pid);
18494                 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode();
18495             }
18496         }
18497 
18498         @Override
isAppForeground(int uid)18499         public boolean isAppForeground(int uid) {
18500             return ActivityManagerService.this.isAppForeground(uid);
18501         }
18502 
18503         @Override
isAppBad(final String processName, final int uid)18504         public boolean isAppBad(final String processName, final int uid) {
18505             return ActivityManagerService.this.isAppBad(processName, uid);
18506         }
18507 
18508         @Override
clearPendingBackup(int userId)18509         public void clearPendingBackup(int userId) {
18510             ActivityManagerService.this.clearPendingBackup(userId);
18511         }
18512 
18513         /**
18514          * When power button is very long pressed, call this interface to do some pre-shutdown work
18515          * like persisting database etc.
18516          */
18517         @Override
prepareForPossibleShutdown()18518         public void prepareForPossibleShutdown() {
18519             ActivityManagerService.this.prepareForPossibleShutdown();
18520         }
18521 
18522         @Override
hasRunningForegroundService(int uid, int foregroundServicetype)18523         public boolean hasRunningForegroundService(int uid, int foregroundServicetype) {
18524             synchronized (ActivityManagerService.this) {
18525                 final UidRecord uidRec = mProcessList.mActiveUids.get(uid);
18526                 if (uidRec == null) {
18527                     return false;
18528                 }
18529                 for (int i = uidRec.getNumOfProcs() - 1; i >= 0; i--) {
18530                     final ProcessRecord app = uidRec.getProcessRecordByIndex(i);
18531                     if ((app.mServices.containsAnyForegroundServiceTypes(foregroundServicetype))) {
18532                         return true;
18533                     }
18534                 }
18535                 return false;
18536             }
18537         }
18538 
18539         @Override
hasForegroundServiceNotification(String pkg, int userId, String channelId)18540         public boolean hasForegroundServiceNotification(String pkg, int userId,
18541                 String channelId) {
18542             synchronized (ActivityManagerService.this) {
18543                 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId);
18544             }
18545         }
18546 
18547         @Override
applyForegroundServiceNotification( Notification notification, String tag, int id, String pkg, int userId)18548         public ServiceNotificationPolicy applyForegroundServiceNotification(
18549                 Notification notification, String tag, int id, String pkg, int userId) {
18550             synchronized (ActivityManagerService.this) {
18551                 return mServices.applyForegroundServiceNotificationLocked(notification,
18552                         tag, id, pkg, userId);
18553             }
18554         }
18555 
18556         @Override
onForegroundServiceNotificationUpdate(boolean shown, Notification notification, int id, String pkg, @UserIdInt int userId)18557         public void onForegroundServiceNotificationUpdate(boolean shown,
18558                 Notification notification, int id, String pkg, @UserIdInt int userId) {
18559             synchronized (ActivityManagerService.this) {
18560                 mServices.onForegroundServiceNotificationUpdateLocked(shown,
18561                         notification, id, pkg, userId);
18562             }
18563         }
18564 
18565         @Override
stopAppForUser(String pkg, @UserIdInt int userId)18566         public void stopAppForUser(String pkg, @UserIdInt int userId) {
18567             ActivityManagerService.this.stopAppForUserInternal(pkg, userId);
18568         }
18569 
18570         @Override
registerProcessObserver(IProcessObserver processObserver)18571         public void registerProcessObserver(IProcessObserver processObserver) {
18572             ActivityManagerService.this.registerProcessObserver(processObserver);
18573         }
18574 
18575         @Override
unregisterProcessObserver(IProcessObserver processObserver)18576         public void unregisterProcessObserver(IProcessObserver processObserver) {
18577             ActivityManagerService.this.unregisterProcessObserver(processObserver);
18578         }
18579 
18580         @Override
getInstrumentationSourceUid(int uid)18581         public int getInstrumentationSourceUid(int uid) {
18582             synchronized (mProcLock) {
18583                 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) {
18584                     ActiveInstrumentation activeInst = mActiveInstrumentation.get(i);
18585                     if (!activeInst.mFinished && activeInst.mTargetInfo != null
18586                             && activeInst.mTargetInfo.uid == uid) {
18587                         return activeInst.mSourceUid;
18588                     }
18589                 }
18590             }
18591             return INVALID_UID;
18592         }
18593 
18594         @Override
setDeviceOwnerUid(int uid)18595         public void setDeviceOwnerUid(int uid) {
18596             mDeviceOwnerUid = uid;
18597         }
18598 
18599         @Override
isDeviceOwner(int uid)18600         public boolean isDeviceOwner(int uid) {
18601             int cachedUid = mDeviceOwnerUid;
18602             return uid >= 0 && cachedUid == uid;
18603         }
18604 
18605 
18606         @Override
setProfileOwnerUid(ArraySet<Integer> profileOwnerUids)18607         public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) {
18608             synchronized (ActivityManagerService.this) {
18609                 mProfileOwnerUids = profileOwnerUids;
18610             }
18611         }
18612 
18613         @Override
isProfileOwner(int uid)18614         public boolean isProfileOwner(int uid) {
18615             synchronized (ActivityManagerService.this) {
18616                 return mProfileOwnerUids != null && mProfileOwnerUids.indexOf(uid) >= 0;
18617             }
18618         }
18619 
18620         @Override
setCompanionAppUids(int userId, Set<Integer> companionAppUids)18621         public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) {
18622             synchronized (ActivityManagerService.this) {
18623                 mCompanionAppUidsMap.put(userId, companionAppUids);
18624             }
18625         }
18626 
18627         @Override
isAssociatedCompanionApp(int userId, int uid)18628         public boolean isAssociatedCompanionApp(int userId, int uid) {
18629             final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
18630             if (allUids == null) {
18631                 return false;
18632             }
18633             return allUids.contains(uid);
18634         }
18635 
18636         @Override
addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread)18637         public void addPendingTopUid(int uid, int pid, @Nullable IApplicationThread thread) {
18638             final boolean isNewPending = mPendingStartActivityUids.add(uid, pid);
18639             // If the next top activity is in cached and frozen mode, WM should raise its priority
18640             // to unfreeze it. This is done by calling AMS.updateOomAdj that will lower its oom adj.
18641             // However, WM cannot hold the AMS clock here so the updateOomAdj operation is performed
18642             // in a separate thread asynchronously. Therefore WM can't guarantee AMS will unfreeze
18643             // next top activity on time. This race will fail the following binder transactions WM
18644             // sends to the activity. After this race issue between WM/ATMS and AMS is solved, this
18645             // workaround can be removed. (b/213288355)
18646             if (isNewPending) {
18647                 mOomAdjuster.mCachedAppOptimizer.unfreezeProcess(pid, OOM_ADJ_REASON_ACTIVITY);
18648             }
18649             // We need to update the network rules for the app coming to the top state so that
18650             // it can access network when the device or the app is in a restricted state
18651             // (e.g. battery/data saver) but since waiting for updateOomAdj to complete and then
18652             // informing NetworkPolicyManager might get delayed, informing the state change as soon
18653             // as we know app is going to come to the top state.
18654             if (isNewPending && mNetworkPolicyUidObserver != null) {
18655                 try {
18656                     final long procStateSeq = mProcessList.getNextProcStateSeq();
18657                     mNetworkPolicyUidObserver.onUidStateChanged(uid, PROCESS_STATE_TOP,
18658                             procStateSeq, PROCESS_CAPABILITY_ALL);
18659                     if (thread != null && shouldWaitForNetworkRulesUpdate(uid)) {
18660                         thread.setNetworkBlockSeq(procStateSeq);
18661                     }
18662                 } catch (RemoteException e) {
18663                     Slog.d(TAG, "Error calling setNetworkBlockSeq", e);
18664                 }
18665             }
18666         }
18667 
shouldWaitForNetworkRulesUpdate(int uid)18668         private boolean shouldWaitForNetworkRulesUpdate(int uid) {
18669             synchronized (mUidNetworkBlockedReasons) {
18670                 // TODO: We can reuse this data in
18671                 // ProcessList#incrementProcStateSeqAndNotifyAppsLOSP instead of calling into
18672                 // NetworkManagementService.
18673                 final int uidBlockedReasons = mUidNetworkBlockedReasons.get(
18674                         uid, BLOCKED_REASON_NONE);
18675                 // We should only inform the uid to block if it is currently blocked but will be
18676                 // unblocked once it comes to the TOP state.
18677                 return uidBlockedReasons != BLOCKED_REASON_NONE
18678                         && updateBlockedReasonsWithProcState(uidBlockedReasons, PROCESS_STATE_TOP)
18679                         == BLOCKED_REASON_NONE;
18680             }
18681         }
18682 
18683         @Override
deletePendingTopUid(int uid, long nowElapsed)18684         public void deletePendingTopUid(int uid, long nowElapsed) {
18685             mPendingStartActivityUids.delete(uid, nowElapsed);
18686         }
18687 
18688         @Override
isPendingTopUid(int uid)18689         public boolean isPendingTopUid(int uid) {
18690             return mPendingStartActivityUids.isPendingTopUid(uid);
18691         }
18692 
18693         @Override
getIntentForIntentSender(IIntentSender sender)18694         public Intent getIntentForIntentSender(IIntentSender sender) {
18695             return ActivityManagerService.this.getIntentForIntentSender(sender);
18696         }
18697 
18698         @Override
getPendingIntentActivityAsApp( int requestCode, @NonNull Intent intent, int flags, Bundle options, String ownerPkg, int ownerUid)18699         public PendingIntent getPendingIntentActivityAsApp(
18700                 int requestCode, @NonNull Intent intent, int flags, Bundle options,
18701                 String ownerPkg, int ownerUid) {
18702             return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags,
18703                     options, ownerPkg, ownerUid);
18704         }
18705 
18706         @Override
getPendingIntentActivityAsApp( int requestCode, @NonNull Intent[] intents, int flags, Bundle options, String ownerPkg, int ownerUid)18707         public PendingIntent getPendingIntentActivityAsApp(
18708                 int requestCode, @NonNull Intent[] intents, int flags, Bundle options,
18709                 String ownerPkg, int ownerUid) {
18710             // system callers must explicitly set mutability state
18711             final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0;
18712             final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0;
18713             if (flagImmutableSet == flagMutableSet) {
18714                 throw new IllegalArgumentException(
18715                         "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE");
18716             }
18717 
18718             final Context context = ActivityManagerService.this.mContext;
18719             final ContentResolver resolver = context.getContentResolver();
18720             final int len = intents.length;
18721             final String[] resolvedTypes = new String[len];
18722             for (int i = 0; i < len; i++) {
18723                 final Intent intent = intents[i];
18724                 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver);
18725                 intent.migrateExtraStreamToClipData(context);
18726                 intent.prepareToLeaveProcess(context);
18727             }
18728             IIntentSender target =
18729                     ActivityManagerService.this.getIntentSenderWithFeatureAsApp(
18730                             INTENT_SENDER_ACTIVITY, ownerPkg,
18731                             context.getAttributionTag(), null, null, requestCode,
18732                             intents,
18733                             resolvedTypes,
18734                             flags, options, UserHandle.getUserId(ownerUid), ownerUid);
18735             return target != null ? new PendingIntent(target) : null;
18736         }
18737 
18738         @Override
getBootTimeTempAllowListDuration()18739         public long getBootTimeTempAllowListDuration() {
18740             // Do not lock ActivityManagerService.this here, this API is called by
18741             // PackageManagerService.
18742             return mConstants.mBootTimeTempAllowlistDuration;
18743         }
18744 
18745         @Override
registerAnrController(AnrController controller)18746         public void registerAnrController(AnrController controller) {
18747             mActivityTaskManager.registerAnrController(controller);
18748         }
18749 
18750         @Override
unregisterAnrController(AnrController controller)18751         public void unregisterAnrController(AnrController controller) {
18752             mActivityTaskManager.unregisterAnrController(controller);
18753         }
18754 
18755         @Override
canStartForegroundService(int pid, int uid, @NonNull String packageName)18756         public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) {
18757             synchronized (ActivityManagerService.this) {
18758                 return mServices.canStartForegroundServiceLocked(pid, uid, packageName);
18759             }
18760         }
18761 
18762         @Override
tempAllowWhileInUsePermissionInFgs(int uid, long durationMs)18763         public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) {
18764             mFgsWhileInUseTempAllowList.add(uid, durationMs, "");
18765         }
18766 
18767         @Override
isTempAllowlistedForFgsWhileInUse(int uid)18768         public boolean isTempAllowlistedForFgsWhileInUse(int uid) {
18769             return mFgsWhileInUseTempAllowList.isAllowed(uid);
18770         }
18771 
18772         @Override
canAllowWhileInUsePermissionInFgs(int pid, int uid, @NonNull String packageName)18773         public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid,
18774                 @NonNull String packageName) {
18775             synchronized (ActivityManagerService.this) {
18776                 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName);
18777             }
18778         }
18779 
18780         @Override
getPushMessagingOverQuotaBehavior()18781         public @TempAllowListType int getPushMessagingOverQuotaBehavior() {
18782             synchronized (ActivityManagerService.this) {
18783                 return mConstants.mPushMessagingOverQuotaBehavior;
18784             }
18785         }
18786 
18787         @Override
getServiceStartForegroundTimeout()18788         public int getServiceStartForegroundTimeout() {
18789             return mConstants.mServiceStartForegroundTimeoutMs;
18790         }
18791 
18792         @Override
getUidCapability(int uid)18793         public int getUidCapability(int uid) {
18794             synchronized (ActivityManagerService.this) {
18795                 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
18796                 if (uidRecord == null) {
18797                     throw new IllegalArgumentException("uid record for " + uid + " not found");
18798                 }
18799                 return uidRecord.getCurCapability();
18800             }
18801         }
18802 
18803         /**
18804          * @return The PID list of the isolated process with packages matching the given uid.
18805          */
18806         @Nullable
getIsolatedProcesses(int uid)18807         public List<Integer> getIsolatedProcesses(int uid) {
18808             synchronized (ActivityManagerService.this) {
18809                 return mProcessList.getIsolatedProcessesLocked(uid);
18810             }
18811         }
18812 
18813         /** @see ActivityManagerService#sendIntentSender */
18814         @Override
sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)18815         public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code,
18816                 Intent intent, String resolvedType,
18817                 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
18818             return ActivityManagerService.this.sendIntentSender(null, target, allowlistToken, code,
18819                     intent, resolvedType, finishedReceiver, requiredPermission, options);
18820         }
18821 
18822         @Override
setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)18823         public void setVoiceInteractionManagerProvider(
18824                 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) {
18825             ActivityManagerService.this.setVoiceInteractionManagerProvider(provider);
18826         }
18827 
18828         @Override
setStopUserOnSwitch(int value)18829         public void setStopUserOnSwitch(int value) {
18830             ActivityManagerService.this.setStopUserOnSwitch(value);
18831         }
18832 
18833         @Override
getRestrictionLevel(int uid)18834         public @RestrictionLevel int getRestrictionLevel(int uid) {
18835             return mAppRestrictionController.getRestrictionLevel(uid);
18836         }
18837 
18838         @Override
getRestrictionLevel(String pkg, @UserIdInt int userId)18839         public @RestrictionLevel int getRestrictionLevel(String pkg, @UserIdInt int userId) {
18840             return mAppRestrictionController.getRestrictionLevel(pkg, userId);
18841         }
18842 
18843         @Override
isBgAutoRestrictedBucketFeatureFlagEnabled()18844         public boolean isBgAutoRestrictedBucketFeatureFlagEnabled() {
18845             return mAppRestrictionController.isBgAutoRestrictedBucketFeatureFlagEnabled();
18846         }
18847 
18848         @Override
addAppBackgroundRestrictionListener( @onNull ActivityManagerInternal.AppBackgroundRestrictionListener listener)18849         public void addAppBackgroundRestrictionListener(
18850                 @NonNull ActivityManagerInternal.AppBackgroundRestrictionListener listener) {
18851             mAppRestrictionController.addAppBackgroundRestrictionListener(listener);
18852         }
18853 
18854         @Override
addForegroundServiceStateListener( @onNull ForegroundServiceStateListener listener)18855         public void addForegroundServiceStateListener(
18856                 @NonNull ForegroundServiceStateListener listener) {
18857             synchronized (ActivityManagerService.this) {
18858                 mForegroundServiceStateListeners.add(listener);
18859             }
18860         }
18861 
18862         @Override
addBroadcastEventListener(@onNull BroadcastEventListener listener)18863         public void addBroadcastEventListener(@NonNull BroadcastEventListener listener) {
18864             // It's a CopyOnWriteArrayList, so no lock is needed.
18865             mBroadcastEventListeners.add(listener);
18866         }
18867 
18868         @Override
addBindServiceEventListener(@onNull BindServiceEventListener listener)18869         public void addBindServiceEventListener(@NonNull BindServiceEventListener listener) {
18870             // It's a CopyOnWriteArrayList, so no lock is needed.
18871             mBindServiceEventListeners.add(listener);
18872         }
18873 
18874         @Override
restart()18875         public void restart() {
18876             ActivityManagerService.this.restart();
18877         }
18878 
18879         @Override
registerNetworkPolicyUidObserver(@onNull IUidObserver observer, int which, int cutpoint, @NonNull String callingPackage)18880         public void registerNetworkPolicyUidObserver(@NonNull IUidObserver observer,
18881                 int which, int cutpoint, @NonNull String callingPackage) {
18882             mNetworkPolicyUidObserver = observer;
18883             mUidObserverController.register(observer, which, cutpoint, callingPackage,
18884                     Binder.getCallingUid(), /*uids*/null);
18885         }
18886 
18887         @Override
startForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)18888         public boolean startForegroundServiceDelegate(
18889                 @NonNull ForegroundServiceDelegationOptions options,
18890                 @Nullable ServiceConnection connection) {
18891             synchronized (ActivityManagerService.this) {
18892                 return mServices.startForegroundServiceDelegateLocked(options, connection);
18893             }
18894         }
18895 
18896         @Override
stopForegroundServiceDelegate( @onNull ForegroundServiceDelegationOptions options)18897         public void stopForegroundServiceDelegate(
18898                 @NonNull ForegroundServiceDelegationOptions options) {
18899             synchronized (ActivityManagerService.this) {
18900                 mServices.stopForegroundServiceDelegateLocked(options);
18901             }
18902         }
18903 
18904         @Override
stopForegroundServiceDelegate(@onNull ServiceConnection connection)18905         public void stopForegroundServiceDelegate(@NonNull ServiceConnection connection) {
18906             synchronized (ActivityManagerService.this) {
18907                 mServices.stopForegroundServiceDelegateLocked(connection);
18908             }
18909         }
18910 
18911         @Override
getClientPackages(String servicePackageName)18912         public ArraySet<String> getClientPackages(String servicePackageName) {
18913             synchronized (ActivityManagerService.this) {
18914                 return mServices.getClientPackagesLocked(servicePackageName);
18915             }
18916         }
18917 
18918         @Override
getRegisteredStrictModeCallback(int callingPid)18919         public IUnsafeIntentStrictModeCallback getRegisteredStrictModeCallback(int callingPid) {
18920             return mStrictModeCallbacks.get(callingPid);
18921         }
18922 
18923         @Override
unregisterStrictModeCallback(int callingPid)18924         public void unregisterStrictModeCallback(int callingPid) {
18925             mStrictModeCallbacks.remove(callingPid);
18926         }
18927 
18928         @Override
startProfileEvenWhenDisabled(@serIdInt int userId)18929         public boolean startProfileEvenWhenDisabled(@UserIdInt int userId) {
18930             return mUserController.startProfile(userId, /* evenWhenDisabled= */ true,
18931                     /* unlockListener= */ null);
18932         }
18933 
18934         @Override
logFgsApiBegin(@oregroundServiceApiType int apiType, int uid, int pid)18935         public void logFgsApiBegin(@ForegroundServiceApiType int apiType,
18936                 int uid, int pid) {
18937             synchronized (this) {
18938                 mServices.logFgsApiBeginLocked(apiType, uid, pid);
18939             }
18940         }
18941 
18942         @Override
logFgsApiEnd(@oregroundServiceApiType int apiType, int uid, int pid)18943         public void logFgsApiEnd(@ForegroundServiceApiType int apiType,
18944                 int uid, int pid) {
18945             synchronized (this) {
18946                 mServices.logFgsApiEndLocked(apiType, uid, pid);
18947             }
18948         }
18949 
18950         @Override
notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken, @MediaProjectionTokenEvent int event)18951         public void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken,
18952                 @MediaProjectionTokenEvent int event) {
18953             ActivityManagerService.this.notifyMediaProjectionEvent(uid, projectionToken, event);
18954         }
18955 
18956         @Override
18957         @NonNull
getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull)18958         public StatsEvent getCachedAppsHighWatermarkStats(int atomTag, boolean resetAfterPull) {
18959             return mAppProfiler.mCachedAppsWatermarkData.getCachedAppsHighWatermarkStats(
18960                     atomTag, resetAfterPull);
18961         }
18962 
18963         @Override
clearApplicationUserData(final String packageName, boolean keepState, boolean isRestore, final IPackageDataObserver observer, int userId)18964         public boolean clearApplicationUserData(final String packageName, boolean keepState,
18965                 boolean isRestore, final IPackageDataObserver observer, int userId) {
18966             return ActivityManagerService.this.clearApplicationUserData(packageName, keepState,
18967                     isRestore, observer, userId);
18968         }
18969     }
18970 
18971     long inputDispatchingTimedOut(int pid, final boolean aboveSystem, TimeoutRecord timeoutRecord) {
18972         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
18973             throw new SecurityException("Requires permission " + FILTER_EVENTS);
18974         }
18975         ProcessRecord proc;
18976         timeoutRecord.mLatencyTracker.waitingOnPidLockStarted();
18977         synchronized (mPidsSelfLocked) {
18978             timeoutRecord.mLatencyTracker.waitingOnPidLockEnded();
18979             proc = mPidsSelfLocked.get(pid);
18980         }
18981         final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() :
18982                 DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
18983 
18984         if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, timeoutRecord)) {
18985             return 0;
18986         }
18987 
18988         return timeoutMillis;
18989     }
18990 
18991     /**
18992      * Handle input dispatching timeouts.
18993      * @return whether input dispatching should be aborted or not.
18994      */
18995     boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName,
18996             ApplicationInfo aInfo, String parentShortComponentName,
18997             WindowProcessController parentProcess, boolean aboveSystem,
18998             TimeoutRecord timeoutRecord) {
18999         try {
19000             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "inputDispatchingTimedOut()");
19001             if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
19002                 throw new SecurityException("Requires permission " + FILTER_EVENTS);
19003             }
19004 
19005             if (proc != null) {
19006                 timeoutRecord.mLatencyTracker.waitingOnAMSLockStarted();
19007                 synchronized (this) {
19008                     timeoutRecord.mLatencyTracker.waitingOnAMSLockEnded();
19009                     if (proc.isDebugging()) {
19010                         return false;
19011                     }
19012 
19013                     if (proc.getActiveInstrumentation() != null) {
19014                         Bundle info = new Bundle();
19015                         info.putString("shortMsg", "keyDispatchingTimedOut");
19016                         info.putString("longMsg", timeoutRecord.mReason);
19017                         finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
19018                         return true;
19019                     }
19020                 }
19021                 mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo,
19022                         parentShortComponentName, parentProcess, aboveSystem, timeoutRecord,
19023                         /*isContinuousAnr*/ true);
19024             }
19025 
19026             return true;
19027         } finally {
19028             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
19029         }
19030     }
19031 
19032     /**
19033      * Called by app main thread to wait for the network policy rules to get updated.
19034      *
19035      * @param procStateSeq The sequence number indicating the process state change that the main
19036      *                     thread is interested in.
19037      */
19038     @Override
19039     public void waitForNetworkStateUpdate(long procStateSeq) {
19040         final int callingUid = Binder.getCallingUid();
19041         if (DEBUG_NETWORK) {
19042             Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq);
19043         }
19044         UidRecord record;
19045         synchronized (mProcLock) {
19046             record = mProcessList.getUidRecordLOSP(callingUid);
19047             if (record == null) {
19048                 return;
19049             }
19050         }
19051         synchronized (record.networkStateLock) {
19052             if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
19053                 if (DEBUG_NETWORK) {
19054                     Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. "
19055                             + procStateSeq + ", so no need to wait. Uid: "
19056                             + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: "
19057                             + record.lastNetworkUpdatedProcStateSeq);
19058                 }
19059                 return;
19060             }
19061             try {
19062                 if (DEBUG_NETWORK) {
19063                     Slog.d(TAG_NETWORK, "Starting to wait for the network rules update."
19064                         + " Uid: " + callingUid + " procStateSeq: " + procStateSeq);
19065                 }
19066                 final long startTime = SystemClock.uptimeMillis();
19067                 record.procStateSeqWaitingForNetwork = procStateSeq;
19068                 record.networkStateLock.wait(mConstants.mNetworkAccessTimeoutMs);
19069                 record.procStateSeqWaitingForNetwork = 0;
19070                 final long totalTime = SystemClock.uptimeMillis() - startTime;
19071                 if (totalTime >= mConstants.mNetworkAccessTimeoutMs || DEBUG_NETWORK) {
19072                     Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: "
19073                             + totalTime + ". Uid: " + callingUid + " procStateSeq: "
19074                             + procStateSeq + " UidRec: " + record
19075                             + " validateUidRec: "
19076                             + mUidObserverController.getValidateUidRecord(callingUid));
19077                 }
19078             } catch (InterruptedException e) {
19079                 Thread.currentThread().interrupt();
19080             }
19081         }
19082     }
19083 
19084     @Override
19085     public void waitForBroadcastIdle() {
19086         waitForBroadcastIdle(LOG_WRITER_INFO, false);
19087     }
19088 
19089     void waitForBroadcastIdle(@NonNull PrintWriter pw, boolean flushBroadcastLoopers) {
19090         enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()");
19091         if (flushBroadcastLoopers) {
19092             BroadcastLoopers.waitForIdle(pw);
19093         }
19094         for (BroadcastQueue queue : mBroadcastQueues) {
19095             queue.waitForIdle(pw);
19096         }
19097         pw.println("All broadcast queues are idle!");
19098         pw.flush();
19099     }
19100 
19101     @Override
19102     public void waitForBroadcastBarrier() {
19103         waitForBroadcastBarrier(LOG_WRITER_INFO, false, false);
19104     }
19105 
19106     void waitForBroadcastBarrier(@NonNull PrintWriter pw,
19107             boolean flushBroadcastLoopers, boolean flushApplicationThreads) {
19108         enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()");
19109         if (flushBroadcastLoopers) {
19110             BroadcastLoopers.waitForBarrier(pw);
19111         }
19112         for (BroadcastQueue queue : mBroadcastQueues) {
19113             queue.waitForBarrier(pw);
19114         }
19115         if (flushApplicationThreads) {
19116             waitForApplicationBarrier(pw);
19117         }
19118     }
19119 
19120     /**
19121      * Wait for all pending {@link IApplicationThread} events to be processed in
19122      * all currently running apps.
19123      */
19124     void waitForApplicationBarrier(@NonNull PrintWriter pw) {
19125         final CountDownLatch finishedLatch = new CountDownLatch(1);
19126         final AtomicInteger pingCount = new AtomicInteger(0);
19127         final AtomicInteger pongCount = new AtomicInteger(0);
19128         final RemoteCallback pongCallback = new RemoteCallback((result) -> {
19129             if (pongCount.incrementAndGet() == pingCount.get()) {
19130                 finishedLatch.countDown();
19131             }
19132         });
19133 
19134         // Insert an extra "ping" as a sentinel value to guard us from finishing
19135         // too quickly in parallel below
19136         pingCount.incrementAndGet();
19137 
19138         synchronized (ActivityManagerService.this) {
19139             synchronized (mProcLock) {
19140                 final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
19141                         mProcessList.getProcessNamesLOSP().getMap();
19142                 final int numProc = pmap.size();
19143                 for (int iProc = 0; iProc < numProc; iProc++) {
19144                     final SparseArray<ProcessRecord> apps = pmap.valueAt(iProc);
19145                     for (int iApp = 0, numApps = apps.size(); iApp < numApps; iApp++) {
19146                         final ProcessRecord app = apps.valueAt(iApp);
19147                         final IApplicationThread thread = app.getOnewayThread();
19148                         if (thread != null) {
19149                             mOomAdjuster.mCachedAppOptimizer.unfreezeTemporarily(app,
19150                                     CachedAppOptimizer.UNFREEZE_REASON_PING);
19151                             pingCount.incrementAndGet();
19152                             try {
19153                                 thread.schedulePing(pongCallback);
19154                             } catch (RemoteException ignored) {
19155                                 // When we failed to ping remote process, pretend as
19156                                 // if we received the expected pong
19157                                 pongCallback.sendResult(null);
19158                             }
19159                         }
19160                     }
19161                 }
19162             }
19163         }
19164 
19165         // Now that we've dispatched all "ping" events above, we can send our
19166         // "pong" sentinel value
19167         pongCallback.sendResult(null);
19168 
19169         // Wait for any remaining "pong" events to trickle in
19170         for (int i = 0; i < 30; i++) {
19171             try {
19172                 if (finishedLatch.await(1, TimeUnit.SECONDS)) {
19173                     pw.println("Finished application barriers!");
19174                     pw.flush();
19175                     return;
19176                 } else {
19177                     pw.println("Waiting for application barriers, at " + pongCount.get() + " of "
19178                             + pingCount.get() + "...");
19179                     pw.flush();
19180                 }
19181             } catch (InterruptedException ignored) {
19182             }
19183         }
19184         pw.println("Gave up waiting for application barriers!");
19185         pw.flush();
19186     }
19187 
19188     void waitForBroadcastDispatch(@NonNull PrintWriter pw, @NonNull Intent intent) {
19189         enforceCallingPermission(permission.DUMP, "waitForBroadcastDispatch");
19190         for (BroadcastQueue queue : mBroadcastQueues) {
19191             queue.waitForDispatched(intent, pw);
19192         }
19193     }
19194 
19195     void setIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) {
19196         Objects.requireNonNull(broadcastAction);
19197         enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()");
19198         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19199             mDeliveryGroupPolicyIgnoredActions.add(broadcastAction);
19200         }
19201     }
19202 
19203     void clearIgnoreDeliveryGroupPolicy(@NonNull String broadcastAction) {
19204         Objects.requireNonNull(broadcastAction);
19205         enforceCallingPermission(permission.DUMP, "waitForBroadcastBarrier()");
19206         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19207             mDeliveryGroupPolicyIgnoredActions.remove(broadcastAction);
19208         }
19209     }
19210 
19211     boolean shouldIgnoreDeliveryGroupPolicy(@Nullable String broadcastAction) {
19212         if (broadcastAction == null) {
19213             return false;
19214         }
19215         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19216             return mDeliveryGroupPolicyIgnoredActions.contains(broadcastAction);
19217         }
19218     }
19219 
19220     void dumpDeliveryGroupPolicyIgnoredActions(IndentingPrintWriter ipw) {
19221         synchronized (mDeliveryGroupPolicyIgnoredActions) {
19222             ipw.println(mDeliveryGroupPolicyIgnoredActions);
19223         }
19224     }
19225 
19226     @Override
19227     public void forceDelayBroadcastDelivery(@NonNull String targetPackage,
19228             long delayedDurationMs) {
19229         Objects.requireNonNull(targetPackage);
19230         Preconditions.checkArgumentNonnegative(delayedDurationMs);
19231         enforceCallingPermission(permission.DUMP, "forceDelayBroadcastDelivery()");
19232         // Ignore request if modern queue is not enabled
19233         if (!mEnableModernQueue) {
19234             return;
19235         }
19236 
19237         for (BroadcastQueue queue : mBroadcastQueues) {
19238             queue.forceDelayBroadcastDelivery(targetPackage, delayedDurationMs);
19239         }
19240     }
19241 
19242     @Override
19243     public boolean isModernBroadcastQueueEnabled() {
19244         enforceCallingPermission(permission.DUMP, "isModernBroadcastQueueEnabled()");
19245         return mEnableModernQueue;
19246     }
19247 
19248     @Override
19249     public boolean isProcessFrozen(int pid) {
19250         enforceCallingPermission(permission.DUMP, "isProcessFrozen()");
19251         return mOomAdjuster.mCachedAppOptimizer.isProcessFrozen(pid);
19252     }
19253 
19254     @Override
19255     @ReasonCode
19256     public int getBackgroundRestrictionExemptionReason(int uid) {
19257         enforceCallingPermission(android.Manifest.permission.DEVICE_POWER,
19258                 "getBackgroundRestrictionExemptionReason()");
19259         return mAppRestrictionController.getBackgroundRestrictionExemptionReason(uid);
19260     }
19261 
19262     /**
19263      * Set an app's background restriction level.
19264      * This interface is intended for the shell command to use.
19265      */
19266     void setBackgroundRestrictionLevel(String packageName, int uid, int userId,
19267             @RestrictionLevel int level, int reason, int subReason) {
19268         final int callingUid = Binder.getCallingUid();
19269         if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) {
19270             throw new SecurityException(
19271                     "No permission to change app restriction level");
19272         }
19273         final long callingId = Binder.clearCallingIdentity();
19274         try {
19275             final int curBucket = mUsageStatsService.getAppStandbyBucket(packageName, userId,
19276                     SystemClock.elapsedRealtime());
19277             mAppRestrictionController.applyRestrictionLevel(packageName, uid, level,
19278                     null /* trackerInfo */, curBucket, true /* allowUpdateBucket */,
19279                     reason, subReason);
19280         } finally {
19281             Binder.restoreCallingIdentity(callingId);
19282         }
19283     }
19284 
19285     /**
19286      * Get an app's background restriction level.
19287      * This interface is intended for the shell command to use.
19288      */
19289     @RestrictionLevel int getBackgroundRestrictionLevel(String packageName, int userId) {
19290         final int callingUid = Binder.getCallingUid();
19291         if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) {
19292             throw new SecurityException(
19293                     "Don't have permission to query app background restriction level");
19294         }
19295         final long callingId = Binder.clearCallingIdentity();
19296         try {
19297             return mInternal.getRestrictionLevel(packageName, userId);
19298         } finally {
19299             Binder.restoreCallingIdentity(callingId);
19300         }
19301     }
19302 
19303     /**
19304      * Start/stop foreground service delegate on a app's process.
19305      * This interface is intended for the shell command to use.
19306      */
19307     void setForegroundServiceDelegate(String packageName, int uid, boolean isStart,
19308             @ForegroundServiceDelegationOptions.DelegationService int delegateService,
19309             String clientInstanceName) {
19310         final int callingUid = Binder.getCallingUid();
19311         if (callingUid != SYSTEM_UID && callingUid != ROOT_UID && callingUid != SHELL_UID) {
19312             throw new SecurityException(
19313                     "No permission to start/stop foreground service delegate");
19314         }
19315         final long callingId = Binder.clearCallingIdentity();
19316         try {
19317             boolean foundPid = false;
19318             synchronized (this) {
19319                 ArrayList<ForegroundServiceDelegationOptions> delegates = new ArrayList<>();
19320                 synchronized (mPidsSelfLocked) {
19321                     for (int i = 0; i < mPidsSelfLocked.size(); i++) {
19322                         final ProcessRecord p = mPidsSelfLocked.valueAt(i);
19323                         final IApplicationThread thread = p.getThread();
19324                         if (p.uid == uid && thread != null) {
19325                             foundPid = true;
19326                             int pid = mPidsSelfLocked.keyAt(i);
19327                             ForegroundServiceDelegationOptions options =
19328                                     new ForegroundServiceDelegationOptions(pid, uid, packageName,
19329                                             null /* clientAppThread */,
19330                                             false /* isSticky */,
19331                                             clientInstanceName, 0 /* foregroundServiceType */,
19332                                             delegateService);
19333                             delegates.add(options);
19334                         }
19335                     }
19336                 }
19337                 for (int i = delegates.size() - 1; i >= 0; i--) {
19338                     final ForegroundServiceDelegationOptions options = delegates.get(i);
19339                     if (isStart) {
19340                         mInternal.startForegroundServiceDelegate(options,
19341                                 null /* connection */);
19342                     } else {
19343                         mInternal.stopForegroundServiceDelegate(options);
19344                     }
19345                 }
19346             }
19347             if (!foundPid) {
19348                 Slog.e(TAG, "setForegroundServiceDelegate can not find process for packageName:"
19349                         + packageName + " uid:" + uid);
19350             }
19351         } finally {
19352             Binder.restoreCallingIdentity(callingId);
19353         }
19354     }
19355 
19356     /**
19357      * Force the settings cache to be loaded
19358      */
19359     void refreshSettingsCache() {
19360         mCoreSettingsObserver.onChange(true);
19361     }
19362 
19363     /**
19364      * Reset the dropbox rate limiter here and in BootReceiver
19365      */
19366     void resetDropboxRateLimiter() {
19367         mDropboxRateLimiter.reset();
19368         BootReceiver.resetDropboxRateLimiter();
19369     }
19370 
19371     /**
19372      * Kill processes for the user with id userId and that depend on the package named packageName
19373      */
19374     @Override
19375     public void killPackageDependents(String packageName, int userId) {
19376         enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()");
19377         if (packageName == null) {
19378             throw new NullPointerException(
19379                     "Cannot kill the dependents of a package without its name.");
19380         }
19381 
19382         final long callingId = Binder.clearCallingIdentity();
19383         IPackageManager pm = AppGlobals.getPackageManager();
19384         int pkgUid = -1;
19385         try {
19386             pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
19387         } catch (RemoteException e) {
19388         }
19389         if (userId != UserHandle.USER_ALL && pkgUid == -1) {
19390             throw new IllegalArgumentException(
19391                     "Cannot kill dependents of non-existing package " + packageName);
19392         }
19393         try {
19394             synchronized(this) {
19395                 synchronized (mProcLock) {
19396                     mProcessList.killPackageProcessesLSP(packageName, UserHandle.getAppId(pkgUid),
19397                             userId, ProcessList.FOREGROUND_APP_ADJ,
19398                             ApplicationExitInfo.REASON_DEPENDENCY_DIED,
19399                             ApplicationExitInfo.SUBREASON_UNKNOWN,
19400                             "dep: " + packageName);
19401                 }
19402             }
19403         } finally {
19404             Binder.restoreCallingIdentity(callingId);
19405         }
19406     }
19407 
19408     @Override
19409     public int restartUserInBackground(int userId, int userStartMode) {
19410         return mUserController.restartUser(userId, userStartMode);
19411     }
19412 
19413     @Override
19414     public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) {
19415         enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
19416                 "scheduleApplicationInfoChanged()");
19417 
19418         final long origId = Binder.clearCallingIdentity();
19419         try {
19420             final boolean updateFrameworkRes = packageNames.contains("android");
19421             synchronized (mProcLock) {
19422                 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId);
19423             }
19424 
19425             AppWidgetManagerInternal widgets = LocalServices.getService(
19426                     AppWidgetManagerInternal.class);
19427             if (widgets != null) {
19428                 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId,
19429                         updateFrameworkRes);
19430             }
19431         } finally {
19432             Binder.restoreCallingIdentity(origId);
19433         }
19434     }
19435 
19436     /**
19437      * Synchronously update the system ActivityThread, bypassing any deferred threading so any
19438      * resources and overlaid values are available immediately.
19439      */
19440     public void updateSystemUiContext() {
19441         final PackageManagerInternal packageManagerInternal = getPackageManagerInternal();
19442 
19443         ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android",
19444                 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM);
19445         ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai);
19446     }
19447 
19448     @GuardedBy(anyOf = {"this", "mProcLock"})
19449     private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate,
19450             boolean updateFrameworkRes, int userId) {
19451         if (updateFrameworkRes) {
19452             ParsingPackageUtils.readConfigUseRoundIcon(null);
19453         }
19454 
19455         mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes);
19456 
19457         if (updateFrameworkRes) {
19458             // Update system server components that need to know about changed overlays. Because the
19459             // overlay is applied in ActivityThread, we need to serialize through its thread too.
19460             final Executor executor = ActivityThread.currentActivityThread().getExecutor();
19461             final DisplayManagerInternal display =
19462                     LocalServices.getService(DisplayManagerInternal.class);
19463             if (display != null) {
19464                 executor.execute(display::onOverlayChanged);
19465             }
19466             if (mWindowManager != null) {
19467                 executor.execute(mWindowManager::onOverlayChanged);
19468             }
19469         }
19470     }
19471 
19472     /**
19473      * Update the binder call heavy hitter watcher per the new configuration
19474      */
19475     void scheduleUpdateBinderHeavyHitterWatcherConfig() {
19476         // There are two sets of configs: the default watcher and the auto sampler,
19477         // the default one takes precedence. System would kick off auto sampler when there is
19478         // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while.
19479         mHandler.post(() -> {
19480             final boolean enabled;
19481             final int batchSize;
19482             final float threshold;
19483             final BinderCallHeavyHitterListener listener;
19484             synchronized (mProcLock) {
19485                 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
19486                     // Default watcher takes precedence, ignore the auto sampler.
19487                     mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG);
19488                     // Set the watcher with the default watcher's config
19489                     enabled = true;
19490                     batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE;
19491                     threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD;
19492                     listener = (a, b, c, d) -> mHandler.post(
19493                             () -> handleBinderHeavyHitters(a, b, c, d));
19494                 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) {
19495                     // There is an ongoing auto sampler session, update it
19496                     enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED;
19497                     batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
19498                     threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
19499                     listener = (a, b, c, d) -> mHandler.post(
19500                             () -> handleBinderHeavyHitters(a, b, c, d));
19501                 } else {
19502                     // Stop it
19503                     enabled = false;
19504                     batchSize = 0;
19505                     threshold = 0.0f;
19506                     listener = null;
19507                 }
19508             }
19509             Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener);
19510         });
19511     }
19512 
19513     /**
19514      * Kick off the watcher to run for given timeout, it could be throttled however.
19515      */
19516     void scheduleBinderHeavyHitterAutoSampler() {
19517         mHandler.post(() -> {
19518             final int batchSize;
19519             final float threshold;
19520             final long now;
19521             synchronized (mProcLock) {
19522                 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) {
19523                     // It's configured OFF
19524                     return;
19525                 }
19526                 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
19527                     // If the default watcher is active already, don't start the auto sampler
19528                     return;
19529                 }
19530                 now = SystemClock.uptimeMillis();
19531                 if (mLastBinderHeavyHitterAutoSamplerStart
19532                         + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) {
19533                     // Too frequent, throttle it
19534                     return;
19535                 }
19536                 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
19537                 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
19538             }
19539             // No lock is needed because we are accessing these variables in handle thread only.
19540             mLastBinderHeavyHitterAutoSamplerStart = now;
19541             // Start the watcher with the auto sampler's config.
19542             Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold,
19543                     (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d)));
19544             // Schedule to stop it after given timeout.
19545             mHandler.sendMessageDelayed(mHandler.obtainMessage(
19546                     BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG),
19547                     BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS);
19548         });
19549     }
19550 
19551     /**
19552      * Stop the binder heavy hitter auto sampler after given timeout.
19553      */
19554     private void handleBinderHeavyHitterAutoSamplerTimeOut() {
19555         synchronized (mProcLock) {
19556             if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
19557                 // The default watcher is ON, don't bother to stop it.
19558                 return;
19559             }
19560         }
19561         Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null);
19562     }
19563 
19564     /**
19565      * Handle the heavy hitters
19566      */
19567     private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters,
19568             final int totalBinderCalls, final float threshold, final long timeSpan) {
19569         final int size = hitters.size();
19570         if (size == 0) {
19571             return;
19572         }
19573         // Simply log it for now
19574         final String pfmt = "%.1f%%";
19575         final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver();
19576         final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>")
19577                 .append(String.format(pfmt, threshold * 100))
19578                 .append(',').append(totalBinderCalls)
19579                 .append(',').append(timeSpan)
19580                 .append("ms): ");
19581         for (int i = 0; i < size; i++) {
19582             if (i > 0) {
19583                 sb.append(", ");
19584             }
19585             final HeavyHitterContainer container = hitters.get(i);
19586             sb.append('[').append(container.mUid)
19587                     .append(',').append(container.mClass.getName())
19588                     .append(',').append(resolver.getMethodName(container.mClass, container.mCode))
19589                     .append(',').append(container.mCode)
19590                     .append(',').append(String.format(pfmt, container.mFrequency * 100))
19591                     .append(']');
19592         }
19593         Slog.w(TAG, sb.toString());
19594     }
19595 
19596     /**
19597      * Attach an agent to the specified process (proces name or PID)
19598      */
19599     public void attachAgent(String process, String path) {
19600         try {
19601             synchronized (mProcLock) {
19602                 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM,
19603                         "attachAgent");
19604                 IApplicationThread thread;
19605                 if (proc == null || (thread = proc.getThread()) == null) {
19606                     throw new IllegalArgumentException("Unknown process: " + process);
19607                 }
19608 
19609                 enforceDebuggable(proc);
19610 
19611                 thread.attachAgent(path);
19612             }
19613         } catch (RemoteException e) {
19614             throw new IllegalStateException("Process disappeared");
19615         }
19616     }
19617 
19618     /**
19619      * When power button is very long pressed, call this interface to do some pre-shutdown work
19620      * like persisting database etc.
19621      */
19622     public void prepareForPossibleShutdown() {
19623         if (mUsageStatsService != null) {
19624             mUsageStatsService.prepareForPossibleShutdown();
19625         }
19626     }
19627 
19628     @VisibleForTesting
19629     public static class Injector {
19630         private final Context mContext;
19631         private NetworkManagementInternal mNmi;
19632 
19633         private UserController mUserController;
19634 
19635         public Injector(Context context) {
19636             mContext = context;
19637         }
19638 
19639         public Context getContext() {
19640             return mContext;
19641         }
19642 
19643         public AppOpsService getAppOpsService(File recentAccessesFile, File storageFile,
19644                 Handler handler) {
19645             return new AppOpsService(recentAccessesFile, storageFile, handler, getContext());
19646         }
19647 
19648         public Handler getUiHandler(ActivityManagerService service) {
19649             return service.new UiHandler();
19650         }
19651 
19652         public boolean isNetworkRestrictedForUid(int uid) {
19653             if (ensureHasNetworkManagementInternal()) {
19654                 return mNmi.isNetworkRestrictedForUid(uid);
19655             }
19656             return false;
19657         }
19658 
19659         /**
19660          * Called by {@code AMS.getDisplayIdsForStartingVisibleBackgroundUsers()}.
19661          */
19662         // NOTE: ideally Injector should have no complex logic, but if this logic was moved to AMS,
19663         // it could not be tested with the existing ActivityManagerServiceTest (as DisplayManager,
19664         // DisplayInfo, etc... are final and UserManager.isUsersOnSecondaryDisplaysEnabled is
19665         // static).
19666         // So, the logic was added here, and tested on ActivityManagerServiceInjectorTest (which
19667         // was added on FrameworksMockingServicesTests and hence uses Extended Mockito to mock
19668         // final and static stuff)
19669         @Nullable
19670         public int[] getDisplayIdsForStartingVisibleBackgroundUsers() {
19671             if (!UserManager.isVisibleBackgroundUsersEnabled()) {
19672                 Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): not supported");
19673                 return null;
19674             }
19675 
19676             // NOTE: DisplayManagerInternal doesn't have a method to list all displays
19677             DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
19678 
19679             Display[] allDisplays = displayManager.getDisplays();
19680 
19681             // allDisplays should contain at least Display.DEFAULT_DISPLAY, but it's better to
19682             // double check, just in case...
19683             if (allDisplays == null || allDisplays.length == 0) {
19684                 Slogf.wtf(TAG, "displayManager (%s) returned no displays", displayManager);
19685                 return null;
19686             }
19687             boolean hasDefaultDisplay = false;
19688             for (Display display : allDisplays) {
19689                 if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
19690                     hasDefaultDisplay = true;
19691                     break;
19692                 }
19693             }
19694             if (!hasDefaultDisplay) {
19695                 Slogf.wtf(TAG, "displayManager (%s) has %d displays (%s), but none has id "
19696                         + "DEFAULT_DISPLAY (%d)", displayManager, allDisplays.length,
19697                         Arrays.toString(allDisplays), Display.DEFAULT_DISPLAY);
19698                 return null;
19699             }
19700 
19701             boolean allowOnDefaultDisplay = UserManager
19702                     .isVisibleBackgroundUsersOnDefaultDisplayEnabled();
19703             int displaysSize = allDisplays.length;
19704             if (!allowOnDefaultDisplay) {
19705                 displaysSize--;
19706             }
19707             int[] displayIds = new int[displaysSize];
19708 
19709             int numberValidDisplays = 0;
19710             for (Display display : allDisplays) {
19711                 int displayId = display.getDisplayId();
19712                 // TODO(b/247592632): check other properties like isSecure or proper display type
19713                 if (display.isValid() && ((display.getFlags() & Display.FLAG_PRIVATE) == 0)
19714                         && (allowOnDefaultDisplay || displayId != Display.DEFAULT_DISPLAY)) {
19715                     displayIds[numberValidDisplays++] = displayId;
19716                 }
19717             }
19718 
19719             if (numberValidDisplays == 0) {
19720                 // TODO(b/247580038): remove this workaround once a virtual display on Car's
19721                 // KitchenSink (or other app) can be used while running CTS tests on devices that
19722                 // don't have a real display.
19723                 // STOPSHIP: if not removed, it should at least be unit tested
19724                 String testingProp = "fw.display_ids_for_starting_users_for_testing_purposes";
19725                 int displayId = SystemProperties.getInt(testingProp, Display.DEFAULT_DISPLAY);
19726                 if (allowOnDefaultDisplay && displayId == Display.DEFAULT_DISPLAY
19727                         || displayId > 0) {
19728                     Slogf.w(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid "
19729                             + "display found, but returning %d as set by property %s", displayId,
19730                             testingProp);
19731                     return new int[] { displayId };
19732                 }
19733                 Slogf.e(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): no valid display"
19734                         + " on %s", Arrays.toString(allDisplays));
19735                 return null;
19736             }
19737 
19738             if (numberValidDisplays != displayIds.length) {
19739                 int[] validDisplayIds = new int[numberValidDisplays];
19740                 System.arraycopy(displayIds, 0, validDisplayIds, 0, numberValidDisplays);
19741                 if (DEBUG_MU) {
19742                     Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning "
19743                             + "only valid displays (%d instead of %d): %s", numberValidDisplays,
19744                             displayIds.length, Arrays.toString(validDisplayIds));
19745                 }
19746                 return validDisplayIds;
19747             }
19748 
19749             if (DEBUG_MU) {
19750                 Slogf.d(TAG, "getDisplayIdsForStartingVisibleBackgroundUsers(): returning all (but "
19751                         + "DEFAULT_DISPLAY) displays : %s", Arrays.toString(displayIds));
19752             }
19753             return displayIds;
19754         }
19755 
19756         /**
19757          * Called by {@code AMS.startUserInBackgroundVisibleOnDisplay()}.
19758          */
19759         public boolean startUserInBackgroundVisibleOnDisplay(int userId, int displayId,
19760                 @Nullable IProgressListener unlockProgressListener) {
19761             return mUserController.startUserVisibleOnDisplay(userId, displayId,
19762                     unlockProgressListener);
19763         }
19764 
19765         /**
19766          * Return the process list instance
19767          */
19768         public ProcessList getProcessList(ActivityManagerService service) {
19769             return new ProcessList();
19770         }
19771 
19772         /**
19773          * Returns the {@link BatteryStatsService} instance
19774          */
19775         public BatteryStatsService getBatteryStatsService() {
19776             return new BatteryStatsService(mContext, SystemServiceManager.ensureSystemDir(),
19777                 BackgroundThread.get().getHandler());
19778         }
19779 
19780         /**
19781          * Returns the {@link ActiveServices} instance
19782          */
19783         public ActiveServices getActiveServices(ActivityManagerService service) {
19784             return new ActiveServices(service);
19785         }
19786 
19787         private boolean ensureHasNetworkManagementInternal() {
19788             if (mNmi == null) {
19789                 mNmi = LocalServices.getService(NetworkManagementInternal.class);
19790             }
19791             return mNmi != null;
19792         }
19793     }
19794 
19795     @Override
19796     public void startDelegateShellPermissionIdentity(int delegateUid,
19797             @Nullable String[] permissions) {
19798         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19799                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19800             throw new SecurityException("Only the shell can delegate its permissions");
19801         }
19802 
19803         // We allow delegation only to one instrumentation started from the shell
19804         synchronized (mProcLock) {
19805             // If the delegate is already set up for the target UID, nothing to do.
19806             if (mAppOpsService.getAppOpsServiceDelegate() != null) {
19807                 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) {
19808                     throw new IllegalStateException("Bad shell delegate state");
19809                 }
19810                 final ShellDelegate delegate = (ShellDelegate) mAppOpsService
19811                         .getAppOpsServiceDelegate();
19812                 if (delegate.getDelegateUid() != delegateUid) {
19813                     throw new SecurityException("Shell can delegate permissions only "
19814                             + "to one instrumentation at a time");
19815                 }
19816             }
19817 
19818             final int instrCount = mActiveInstrumentation.size();
19819             for (int i = 0; i < instrCount; i++) {
19820                 final ActiveInstrumentation instr = mActiveInstrumentation.get(i);
19821                 if (instr.mTargetInfo.uid != delegateUid) {
19822                     continue;
19823                 }
19824                 // If instrumentation started from the shell the connection is not null
19825                 if (instr.mUiAutomationConnection == null) {
19826                     throw new SecurityException("Shell can delegate its permissions" +
19827                             " only to an instrumentation started from the shell");
19828                 }
19829 
19830                 // Hook them up...
19831                 final ShellDelegate shellDelegate = new ShellDelegate(delegateUid,
19832                         permissions);
19833                 mAppOpsService.setAppOpsServiceDelegate(shellDelegate);
19834                 final String packageName = instr.mTargetInfo.packageName;
19835                 final List<String> permissionNames = permissions != null ?
19836                         Arrays.asList(permissions) : null;
19837                 getPermissionManagerInternal().startShellPermissionIdentityDelegation(
19838                         delegateUid, packageName, permissionNames);
19839                 return;
19840             }
19841         }
19842     }
19843 
19844     @Override
19845     public void stopDelegateShellPermissionIdentity() {
19846         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19847                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19848             throw new SecurityException("Only the shell can delegate its permissions");
19849         }
19850         synchronized (mProcLock) {
19851             mAppOpsService.setAppOpsServiceDelegate(null);
19852             getPermissionManagerInternal().stopShellPermissionIdentityDelegation();
19853         }
19854     }
19855 
19856     @Override
19857     public List<String> getDelegatedShellPermissions() {
19858         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19859                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19860             throw new SecurityException("Only the shell can get delegated permissions");
19861         }
19862         synchronized (mProcLock) {
19863             return getPermissionManagerInternal().getDelegatedShellPermissions();
19864         }
19865     }
19866 
19867     private class ShellDelegate implements CheckOpsDelegate {
19868         private final int mTargetUid;
19869         @Nullable
19870         private final String[] mPermissions;
19871 
19872         ShellDelegate(int targetUid, @Nullable String[] permissions) {
19873             mTargetUid = targetUid;
19874             mPermissions = permissions;
19875         }
19876 
19877         int getDelegateUid() {
19878             return mTargetUid;
19879         }
19880 
19881         @Override
19882         public int checkOperation(int code, int uid, String packageName,
19883                 String attributionTag, boolean raw,
19884                 QuintFunction<Integer, Integer, String, String, Boolean, Integer> superImpl) {
19885             if (uid == mTargetUid && isTargetOp(code)) {
19886                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19887                         Process.SHELL_UID);
19888                 final long identity = Binder.clearCallingIdentity();
19889                 try {
19890                     return superImpl.apply(code, shellUid, "com.android.shell", null, raw);
19891                 } finally {
19892                     Binder.restoreCallingIdentity(identity);
19893                 }
19894             }
19895             return superImpl.apply(code, uid, packageName, attributionTag, raw);
19896         }
19897 
19898         @Override
19899         public int checkAudioOperation(int code, int usage, int uid, String packageName,
19900                 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) {
19901             if (uid == mTargetUid && isTargetOp(code)) {
19902                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19903                         Process.SHELL_UID);
19904                 final long identity = Binder.clearCallingIdentity();
19905                 try {
19906                     return superImpl.apply(code, usage, shellUid, "com.android.shell");
19907                 } finally {
19908                     Binder.restoreCallingIdentity(identity);
19909                 }
19910             }
19911             return superImpl.apply(code, usage, uid, packageName);
19912         }
19913 
19914         @Override
19915         public SyncNotedAppOp noteOperation(int code, int uid, @Nullable String packageName,
19916                 @Nullable String featureId, boolean shouldCollectAsyncNotedOp,
19917                 @Nullable String message, boolean shouldCollectMessage,
19918                 @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean,
19919                         SyncNotedAppOp> superImpl) {
19920             if (uid == mTargetUid && isTargetOp(code)) {
19921                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19922                         Process.SHELL_UID);
19923                 final long identity = Binder.clearCallingIdentity();
19924                 try {
19925                     return superImpl.apply(code, shellUid, "com.android.shell", featureId,
19926                             shouldCollectAsyncNotedOp, message, shouldCollectMessage);
19927                 } finally {
19928                     Binder.restoreCallingIdentity(identity);
19929                 }
19930             }
19931             return superImpl.apply(code, uid, packageName, featureId, shouldCollectAsyncNotedOp,
19932                     message, shouldCollectMessage);
19933         }
19934 
19935         @Override
19936         public SyncNotedAppOp noteProxyOperation(int code,
19937                 @NonNull AttributionSource attributionSource, boolean shouldCollectAsyncNotedOp,
19938                 @Nullable String message, boolean shouldCollectMessage, boolean skiProxyOperation,
19939                 @NonNull HexFunction<Integer, AttributionSource, Boolean, String, Boolean,
19940                                 Boolean, SyncNotedAppOp> superImpl) {
19941             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
19942                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
19943                         attributionSource.getUid()), Process.SHELL_UID);
19944                 final long identity = Binder.clearCallingIdentity();
19945                 try {
19946                     return superImpl.apply(code, new AttributionSource(shellUid,
19947                             Process.INVALID_PID, "com.android.shell",
19948                             attributionSource.getAttributionTag(), attributionSource.getToken(),
19949                             /*renouncedPermissions*/ null, attributionSource.getNext()),
19950                             shouldCollectAsyncNotedOp, message, shouldCollectMessage,
19951                             skiProxyOperation);
19952                 } finally {
19953                     Binder.restoreCallingIdentity(identity);
19954                 }
19955             }
19956             return superImpl.apply(code, attributionSource, shouldCollectAsyncNotedOp,
19957                     message, shouldCollectMessage, skiProxyOperation);
19958         }
19959 
19960         @Override
19961         public SyncNotedAppOp startOperation(IBinder token, int code, int uid,
19962                 @Nullable String packageName, @Nullable String attributionTag,
19963                 boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp,
19964                 @Nullable String message, boolean shouldCollectMessage,
19965                 @AttributionFlags int attributionFlags, int attributionChainId,
19966                 @NonNull UndecFunction<IBinder, Integer, Integer, String, String, Boolean,
19967                         Boolean, String, Boolean, Integer, Integer, SyncNotedAppOp> superImpl) {
19968             if (uid == mTargetUid && isTargetOp(code)) {
19969                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
19970                         Process.SHELL_UID);
19971                 final long identity = Binder.clearCallingIdentity();
19972                 try {
19973                     return superImpl.apply(token, code, shellUid, "com.android.shell",
19974                             attributionTag, startIfModeDefault, shouldCollectAsyncNotedOp, message,
19975                             shouldCollectMessage, attributionFlags, attributionChainId);
19976                 } finally {
19977                     Binder.restoreCallingIdentity(identity);
19978                 }
19979             }
19980             return superImpl.apply(token, code, uid, packageName, attributionTag,
19981                     startIfModeDefault, shouldCollectAsyncNotedOp, message, shouldCollectMessage,
19982                     attributionFlags, attributionChainId);
19983         }
19984 
19985         @Override
19986         public SyncNotedAppOp startProxyOperation(@NonNull IBinder clientId, int code,
19987                 @NonNull AttributionSource attributionSource, boolean startIfModeDefault,
19988                 boolean shouldCollectAsyncNotedOp, String message, boolean shouldCollectMessage,
19989                 boolean skipProxyOperation, @AttributionFlags int proxyAttributionFlags,
19990                 @AttributionFlags int proxiedAttributionFlags, int attributionChainId,
19991                 @NonNull UndecFunction<IBinder, Integer, AttributionSource,
19992                         Boolean, Boolean, String, Boolean, Boolean, Integer, Integer, Integer,
19993                         SyncNotedAppOp> superImpl) {
19994             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
19995                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
19996                         attributionSource.getUid()), Process.SHELL_UID);
19997                 final long identity = Binder.clearCallingIdentity();
19998                 try {
19999                     return superImpl.apply(clientId, code, new AttributionSource(shellUid,
20000                             Process.INVALID_PID, "com.android.shell",
20001                             attributionSource.getAttributionTag(), attributionSource.getToken(),
20002                             /*renouncedPermissions*/ null, attributionSource.getNext()),
20003                             startIfModeDefault, shouldCollectAsyncNotedOp, message,
20004                             shouldCollectMessage, skipProxyOperation, proxyAttributionFlags,
20005                             proxiedAttributionFlags, attributionChainId);
20006                 } finally {
20007                     Binder.restoreCallingIdentity(identity);
20008                 }
20009             }
20010             return superImpl.apply(clientId, code, attributionSource, startIfModeDefault,
20011                     shouldCollectAsyncNotedOp, message, shouldCollectMessage, skipProxyOperation,
20012                     proxyAttributionFlags, proxiedAttributionFlags, attributionChainId);
20013         }
20014 
20015         @Override
20016         public void finishProxyOperation(@NonNull IBinder clientId, int code,
20017                 @NonNull AttributionSource attributionSource, boolean skipProxyOperation,
20018                 @NonNull QuadFunction<IBinder, Integer, AttributionSource, Boolean,
20019                         Void> superImpl) {
20020             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
20021                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
20022                         attributionSource.getUid()), Process.SHELL_UID);
20023                 final long identity = Binder.clearCallingIdentity();
20024                 try {
20025                     superImpl.apply(clientId, code, new AttributionSource(shellUid,
20026                             Process.INVALID_PID, "com.android.shell",
20027                             attributionSource.getAttributionTag(), attributionSource.getToken(),
20028                             /*renouncedPermissions*/ null, attributionSource.getNext()),
20029                             skipProxyOperation);
20030                 } finally {
20031                     Binder.restoreCallingIdentity(identity);
20032                 }
20033             }
20034             superImpl.apply(clientId, code, attributionSource, skipProxyOperation);
20035         }
20036 
20037         private boolean isTargetOp(int code) {
20038             // null permissions means all ops are targeted
20039             if (mPermissions == null) {
20040                 return true;
20041             }
20042             // no permission for the op means the op is targeted
20043             final String permission = AppOpsManager.opToPermission(code);
20044             if (permission == null) {
20045                 return true;
20046             }
20047             return isTargetPermission(permission);
20048         }
20049 
20050         private boolean isTargetPermission(@NonNull String permission) {
20051             // null permissions means all permissions are targeted
20052             return (mPermissions == null || ArrayUtils.contains(mPermissions, permission));
20053         }
20054     }
20055 
20056     /**
20057      * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would
20058      * cause a watchdog kill.
20059      */
20060     void maybeTriggerWatchdog() {
20061         final String key = "debug.trigger.watchdog";
20062         if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) {
20063             Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!");
20064 
20065             // Clear the property; otherwise the system would hang again after a watchdog restart.
20066             SystemProperties.set(key, "");
20067             synchronized (ActivityManagerService.this) {
20068                 try {
20069                     // Arbitrary long sleep for watchdog to catch.
20070                     Thread.sleep(60 * 60 * 1000);
20071                 } catch (InterruptedException e) {
20072                 }
20073             }
20074         }
20075     }
20076 
20077     private boolean isOnFgOffloadQueue(int flags) {
20078         return ((flags & Intent.FLAG_RECEIVER_OFFLOAD_FOREGROUND) != 0);
20079     }
20080 
20081     private boolean isOnBgOffloadQueue(int flags) {
20082         return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
20083     }
20084 
20085     @Override
20086     public ParcelFileDescriptor getLifeMonitor() {
20087         if (!isCallerShell()) {
20088             throw new SecurityException("Only shell can call it");
20089         }
20090         synchronized (mProcLock) {
20091             try {
20092                 if (mLifeMonitorFds == null) {
20093                     mLifeMonitorFds = ParcelFileDescriptor.createPipe();
20094                 }
20095                 // The returned FD will be closed, but we want to keep our reader open,
20096                 // so return a dup instead.
20097                 return mLifeMonitorFds[0].dup();
20098             } catch (IOException e) {
20099                 Slog.w(TAG, "Unable to create pipe", e);
20100                 return null;
20101             }
20102         }
20103     }
20104 
20105     @Override
20106     public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) {
20107         final int callingUid = Binder.getCallingUid();
20108         final int userId = UserHandle.getCallingUserId();
20109         if (getPackageManagerInternal().getPackageUid(activity.getPackageName(),
20110                 /*flags=*/ 0, userId) != callingUid) {
20111             throw new SecurityException("Calling uid " + callingUid + " cannot set locusId"
20112                     + "for package " + activity.getPackageName());
20113         }
20114         mActivityTaskManager.setLocusId(locusId, appToken);
20115         if (mUsageStatsService != null) {
20116             mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken);
20117         }
20118     }
20119 
20120     @Override
20121     public boolean isAppFreezerSupported() {
20122         final long token = Binder.clearCallingIdentity();
20123 
20124         try {
20125             return CachedAppOptimizer.isFreezerSupported();
20126         } finally {
20127             Binder.restoreCallingIdentity(token);
20128         }
20129     }
20130 
20131     @Override
20132     public boolean isAppFreezerEnabled() {
20133         return mOomAdjuster.mCachedAppOptimizer.useFreezer();
20134     }
20135 
20136     public boolean isAppFreezerExemptInstPkg() {
20137         return mOomAdjuster.mCachedAppOptimizer.freezerExemptInstPkg();
20138     }
20139 
20140     /**
20141      * Resets the state of the {@link com.android.server.am.AppErrors} instance.
20142      * This is intended for testing within the CTS only and is protected by
20143      * android.permission.RESET_APP_ERRORS.
20144      */
20145     @Override
20146     public void resetAppErrors() {
20147         enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors");
20148         mAppErrors.resetState();
20149     }
20150 
20151     @Override
20152     public boolean enableAppFreezer(boolean enable) {
20153         int callerUid = Binder.getCallingUid();
20154 
20155         // Only system can toggle the freezer state
20156         if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) {
20157             return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable);
20158         } else {
20159             throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state ");
20160         }
20161     }
20162 
20163     /**
20164      * Suppress or reenable the rate limit on foreground service notification deferral.
20165      * @param enable false to suppress rate-limit policy; true to reenable it.
20166      */
20167     @Override
20168     public boolean enableFgsNotificationRateLimit(boolean enable) {
20169         enforceCallingPermission(permission.WRITE_DEVICE_CONFIG,
20170                 "enableFgsNotificationRateLimit");
20171         synchronized (this) {
20172             return mServices.enableFgsNotificationRateLimitLocked(enable);
20173         }
20174     }
20175 
20176     /**
20177      * Holds the AM lock for the specified amount of milliseconds.
20178      * Intended for use by the tests that need to imitate lock contention.
20179      * The token should be obtained by
20180      * {@link android.content.pm.PackageManager#getHoldLockToken()}.
20181      */
20182     @Override
20183     public void holdLock(IBinder token, int durationMs) {
20184         getTestUtilityServiceLocked().verifyHoldLockToken(token);
20185 
20186         synchronized (this) {
20187             SystemClock.sleep(durationMs);
20188         }
20189     }
20190 
20191     static void traceBegin(long traceTag, String methodName, String subInfo) {
20192         if (Trace.isTagEnabled(traceTag)) {
20193             Trace.traceBegin(traceTag, methodName + subInfo);
20194         }
20195     }
20196 
20197     /**
20198      * Gets an {@code int} argument from the given {@code index} on {@code args}, logging an error
20199      * message on {@code pw} when it cannot be parsed.
20200      *
20201      * Returns {@code int} argument or {@code invalidValue} if it could not be parsed.
20202      */
20203     private static int getIntArg(PrintWriter pw, String[] args, int index, int invalidValue) {
20204         if (index > args.length) {
20205             pw.println("Missing argument");
20206             return invalidValue;
20207         }
20208         String arg = args[index];
20209         try {
20210             return Integer.parseInt(arg);
20211         } catch (Exception e) {
20212             pw.printf("Non-numeric argument at index %d: %s\n", index, arg);
20213             return invalidValue;
20214         }
20215     }
20216 
20217     private void notifyMediaProjectionEvent(int uid, @NonNull IBinder projectionToken,
20218             @MediaProjectionTokenEvent int event) {
20219         synchronized (mMediaProjectionTokenMap) {
20220             final int index = mMediaProjectionTokenMap.indexOfKey(uid);
20221             ArraySet<IBinder> tokens;
20222             if (event == MEDIA_PROJECTION_TOKEN_EVENT_CREATED) {
20223                 if (index < 0) {
20224                     tokens = new ArraySet();
20225                     mMediaProjectionTokenMap.put(uid, tokens);
20226                 } else {
20227                     tokens = mMediaProjectionTokenMap.valueAt(index);
20228                 }
20229                 tokens.add(projectionToken);
20230             } else if (event == MEDIA_PROJECTION_TOKEN_EVENT_DESTROYED && index >= 0) {
20231                 tokens = mMediaProjectionTokenMap.valueAt(index);
20232                 tokens.remove(projectionToken);
20233                 if (tokens.isEmpty()) {
20234                     mMediaProjectionTokenMap.removeAt(index);
20235                 }
20236             }
20237         }
20238     }
20239 
20240     /**
20241      * @return {@code true} if the MediaProjectionManagerService has created a media projection
20242      *         for the given {@code uid} because the user has granted the permission;
20243      *         it doesn't necessarily mean it has started the projection.
20244      *
20245      * <p>It doesn't check the {@link AppOpsManager#OP_PROJECT_MEDIA}.</p>
20246      */
20247     boolean isAllowedMediaProjectionNoOpCheck(int uid) {
20248         synchronized (mMediaProjectionTokenMap) {
20249             final int index = mMediaProjectionTokenMap.indexOfKey(uid);
20250             return index >= 0 && !mMediaProjectionTokenMap.valueAt(index).isEmpty();
20251         }
20252     }
20253 
20254     /**
20255      * Deal with binder transactions to frozen apps.
20256      *
20257      * @param debugPid The binder transaction sender
20258      * @param code The binder transaction code
20259      * @param flags The binder transaction flags
20260      * @param err The binder transaction error
20261      */
20262     @Override
20263     public void frozenBinderTransactionDetected(int debugPid, int code, int flags, int err) {
20264         final ProcessRecord app;
20265         synchronized (mPidsSelfLocked) {
20266             app = mPidsSelfLocked.get(debugPid);
20267         }
20268         mOomAdjuster.mCachedAppOptimizer.binderError(debugPid, app, code, flags, err);
20269     }
20270 }
20271