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.START_ACTIVITIES_FROM_BACKGROUND;
25 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND;
26 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS;
27 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_ISOLATED_STORAGE;
28 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_TEST_API_CHECKS;
29 import static android.app.ActivityManager.INSTR_FLAG_NO_RESTART;
30 import static android.app.ActivityManager.INTENT_SENDER_ACTIVITY;
31 import static android.app.ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
32 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
33 import static android.app.ActivityManager.PROCESS_STATE_TOP;
34 import static android.app.ActivityManager.StopUserOnSwitch;
35 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
36 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
37 import static android.app.AppOpsManager.OP_NONE;
38 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
39 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES;
40 import static android.content.pm.PackageManager.MATCH_ALL;
41 import static android.content.pm.PackageManager.MATCH_ANY_USER;
42 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
43 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
44 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
45 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
46 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
47 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
48 import static android.os.FactoryTest.FACTORY_TEST_OFF;
49 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
50 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
51 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
52 import static android.os.IServiceManager.DUMP_FLAG_PROTO;
53 import static android.os.InputConstants.DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
54 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED;
55 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
56 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_NONE;
57 import static android.os.Process.BLUETOOTH_UID;
58 import static android.os.Process.FIRST_APPLICATION_UID;
59 import static android.os.Process.INVALID_UID;
60 import static android.os.Process.NETWORK_STACK_UID;
61 import static android.os.Process.NFC_UID;
62 import static android.os.Process.PHONE_UID;
63 import static android.os.Process.PROC_OUT_LONG;
64 import static android.os.Process.PROC_SPACE_TERM;
65 import static android.os.Process.ROOT_UID;
66 import static android.os.Process.SCHED_FIFO;
67 import static android.os.Process.SCHED_RESET_ON_FORK;
68 import static android.os.Process.SE_UID;
69 import static android.os.Process.SHELL_UID;
70 import static android.os.Process.SIGNAL_USR1;
71 import static android.os.Process.SYSTEM_UID;
72 import static android.os.Process.THREAD_PRIORITY_FOREGROUND;
73 import static android.os.Process.THREAD_PRIORITY_TOP_APP_BOOST;
74 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH;
75 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
76 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
77 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS;
78 import static android.os.Process.ZYGOTE_PROCESS;
79 import static android.os.Process.getTotalMemory;
80 import static android.os.Process.isThreadInProcess;
81 import static android.os.Process.killProcess;
82 import static android.os.Process.killProcessQuiet;
83 import static android.os.Process.myPid;
84 import static android.os.Process.myUid;
85 import static android.os.Process.readProcFile;
86 import static android.os.Process.removeAllProcessGroups;
87 import static android.os.Process.sendSignal;
88 import static android.os.Process.setThreadPriority;
89 import static android.os.Process.setThreadScheduler;
90 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
91 import static android.provider.Settings.Global.DEBUG_APP;
92 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS;
93 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
94 import static android.text.format.DateUtils.DAY_IN_MILLIS;
95 import static android.util.FeatureFlagUtils.SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS;
96 
97 import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONFIGURATION;
98 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
99 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALLOWLISTS;
100 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
101 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP;
103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND;
105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
106 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
107 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
108 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
109 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
110 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
111 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
112 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
113 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
114 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
115 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
120 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
121 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
122 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
123 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
124 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
125 import static com.android.server.am.MemoryStatUtil.hasMemcg;
126 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
127 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
128 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
129 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
130 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
131 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
132 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
133 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
134 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
135 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD;
136 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
137 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD;
138 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
139 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD;
140 import static com.android.server.wm.ActivityTaskManagerService.DUMP_TOP_RESUMED_ACTIVITY;
141 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
142 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString;
143 
144 import android.Manifest;
145 import android.Manifest.permission;
146 import android.annotation.NonNull;
147 import android.annotation.Nullable;
148 import android.annotation.UserIdInt;
149 import android.app.Activity;
150 import android.app.ActivityClient;
151 import android.app.ActivityManager;
152 import android.app.ActivityManager.PendingIntentInfo;
153 import android.app.ActivityManager.ProcessCapability;
154 import android.app.ActivityManager.RunningTaskInfo;
155 import android.app.ActivityManagerInternal;
156 import android.app.ActivityTaskManager.RootTaskInfo;
157 import android.app.ActivityThread;
158 import android.app.AnrController;
159 import android.app.AppGlobals;
160 import android.app.AppOpsManager;
161 import android.app.AppOpsManager.AttributionFlags;
162 import android.app.AppOpsManagerInternal.CheckOpsDelegate;
163 import android.app.ApplicationErrorReport;
164 import android.app.ApplicationExitInfo;
165 import android.app.ApplicationThreadConstants;
166 import android.app.BroadcastOptions;
167 import android.app.ContentProviderHolder;
168 import android.app.IActivityController;
169 import android.app.IActivityManager;
170 import android.app.IApplicationThread;
171 import android.app.IInstrumentationWatcher;
172 import android.app.INotificationManager;
173 import android.app.IProcessObserver;
174 import android.app.IServiceConnection;
175 import android.app.IStopUserCallback;
176 import android.app.ITaskStackListener;
177 import android.app.IUiAutomationConnection;
178 import android.app.IUidObserver;
179 import android.app.IUserSwitchObserver;
180 import android.app.Instrumentation;
181 import android.app.Notification;
182 import android.app.NotificationManager;
183 import android.app.PendingIntent;
184 import android.app.ProcessMemoryState;
185 import android.app.ProfilerInfo;
186 import android.app.PropertyInvalidatedCache;
187 import android.app.SyncNotedAppOp;
188 import android.app.WaitResult;
189 import android.app.backup.BackupManager.OperationType;
190 import android.app.backup.IBackupManager;
191 import android.app.job.JobParameters;
192 import android.app.usage.UsageEvents;
193 import android.app.usage.UsageEvents.Event;
194 import android.app.usage.UsageStatsManager;
195 import android.app.usage.UsageStatsManagerInternal;
196 import android.appwidget.AppWidgetManager;
197 import android.appwidget.AppWidgetManagerInternal;
198 import android.content.AttributionSource;
199 import android.content.AutofillOptions;
200 import android.content.BroadcastReceiver;
201 import android.content.ComponentCallbacks2;
202 import android.content.ComponentName;
203 import android.content.ContentCaptureOptions;
204 import android.content.ContentProvider;
205 import android.content.ContentResolver;
206 import android.content.Context;
207 import android.content.IIntentReceiver;
208 import android.content.IIntentSender;
209 import android.content.Intent;
210 import android.content.IntentFilter;
211 import android.content.LocusId;
212 import android.content.pm.ActivityInfo;
213 import android.content.pm.ActivityPresentationInfo;
214 import android.content.pm.ApplicationInfo;
215 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy;
216 import android.content.pm.IPackageDataObserver;
217 import android.content.pm.IPackageManager;
218 import android.content.pm.IncrementalStatesInfo;
219 import android.content.pm.InstrumentationInfo;
220 import android.content.pm.PackageInfo;
221 import android.content.pm.PackageManager;
222 import android.content.pm.PackageManager.NameNotFoundException;
223 import android.content.pm.PackageManagerInternal;
224 import android.content.pm.ParceledListSlice;
225 import android.content.pm.PermissionInfo;
226 import android.content.pm.ProcessInfo;
227 import android.content.pm.ProviderInfo;
228 import android.content.pm.ProviderInfoList;
229 import android.content.pm.ResolveInfo;
230 import android.content.pm.SELinuxUtil;
231 import android.content.pm.ServiceInfo;
232 import android.content.pm.TestUtilityService;
233 import android.content.pm.UserInfo;
234 import android.content.pm.parsing.ParsingPackageUtils;
235 import android.content.res.CompatibilityInfo;
236 import android.content.res.Configuration;
237 import android.content.res.Resources;
238 import android.database.ContentObserver;
239 import android.graphics.Rect;
240 import android.hardware.display.DisplayManagerInternal;
241 import android.media.audiofx.AudioEffect;
242 import android.net.ConnectivityManager;
243 import android.net.Proxy;
244 import android.net.Uri;
245 import android.os.AppZygote;
246 import android.os.BatteryStats;
247 import android.os.Binder;
248 import android.os.BinderProxy;
249 import android.os.BugreportParams;
250 import android.os.Build;
251 import android.os.Bundle;
252 import android.os.Debug;
253 import android.os.DropBoxManager;
254 import android.os.FactoryTest;
255 import android.os.FileUtils;
256 import android.os.Handler;
257 import android.os.IBinder;
258 import android.os.IDeviceIdentifiersPolicyService;
259 import android.os.IPermissionController;
260 import android.os.IProcessInfoService;
261 import android.os.IProgressListener;
262 import android.os.Looper;
263 import android.os.Message;
264 import android.os.Parcel;
265 import android.os.ParcelFileDescriptor;
266 import android.os.PowerExemptionManager;
267 import android.os.PowerExemptionManager.ReasonCode;
268 import android.os.PowerExemptionManager.TempAllowListType;
269 import android.os.PowerManager;
270 import android.os.PowerManager.ServiceType;
271 import android.os.PowerManagerInternal;
272 import android.os.Process;
273 import android.os.RemoteCallback;
274 import android.os.RemoteException;
275 import android.os.ResultReceiver;
276 import android.os.ServiceManager;
277 import android.os.SharedMemory;
278 import android.os.ShellCallback;
279 import android.os.StrictMode;
280 import android.os.SystemClock;
281 import android.os.SystemProperties;
282 import android.os.Trace;
283 import android.os.TransactionTooLargeException;
284 import android.os.UserHandle;
285 import android.os.UserManager;
286 import android.os.WorkSource;
287 import android.os.incremental.IIncrementalService;
288 import android.os.incremental.IncrementalManager;
289 import android.os.incremental.IncrementalMetrics;
290 import android.os.storage.IStorageManager;
291 import android.os.storage.StorageManager;
292 import android.provider.DeviceConfig;
293 import android.provider.Settings;
294 import android.server.ServerProtoEnums;
295 import android.sysprop.InitProperties;
296 import android.sysprop.VoldProperties;
297 import android.telephony.TelephonyManager;
298 import android.text.TextUtils;
299 import android.text.format.DateUtils;
300 import android.text.style.SuggestionSpan;
301 import android.util.ArrayMap;
302 import android.util.ArraySet;
303 import android.util.EventLog;
304 import android.util.FeatureFlagUtils;
305 import android.util.IntArray;
306 import android.util.Log;
307 import android.util.Pair;
308 import android.util.PrintWriterPrinter;
309 import android.util.Slog;
310 import android.util.SparseArray;
311 import android.util.SparseIntArray;
312 import android.util.TimeUtils;
313 import android.util.proto.ProtoOutputStream;
314 import android.util.proto.ProtoUtils;
315 import android.view.Gravity;
316 import android.view.LayoutInflater;
317 import android.view.View;
318 import android.view.WindowManager;
319 import android.view.autofill.AutofillManagerInternal;
320 
321 import com.android.internal.annotations.CompositeRWLock;
322 import com.android.internal.annotations.GuardedBy;
323 import com.android.internal.annotations.VisibleForTesting;
324 import com.android.internal.app.IAppOpsActiveCallback;
325 import com.android.internal.app.IAppOpsCallback;
326 import com.android.internal.app.IAppOpsService;
327 import com.android.internal.app.ProcessMap;
328 import com.android.internal.app.SystemUserHomeActivity;
329 import com.android.internal.app.procstats.ProcessState;
330 import com.android.internal.app.procstats.ProcessStats;
331 import com.android.internal.content.PackageHelper;
332 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
333 import com.android.internal.notification.SystemNotificationChannels;
334 import com.android.internal.os.BackgroundThread;
335 import com.android.internal.os.BatteryStatsImpl;
336 import com.android.internal.os.BinderCallHeavyHitterWatcher.BinderCallHeavyHitterListener;
337 import com.android.internal.os.BinderCallHeavyHitterWatcher.HeavyHitterContainer;
338 import com.android.internal.os.BinderInternal;
339 import com.android.internal.os.BinderTransactionNameResolver;
340 import com.android.internal.os.ByteTransferPipe;
341 import com.android.internal.os.IResultReceiver;
342 import com.android.internal.os.ProcessCpuTracker;
343 import com.android.internal.os.SomeArgs;
344 import com.android.internal.os.TransferPipe;
345 import com.android.internal.os.Zygote;
346 import com.android.internal.policy.AttributeCache;
347 import com.android.internal.protolog.common.ProtoLog;
348 import com.android.internal.util.ArrayUtils;
349 import com.android.internal.util.DumpUtils;
350 import com.android.internal.util.FastPrintWriter;
351 import com.android.internal.util.FrameworkStatsLog;
352 import com.android.internal.util.MemInfoReader;
353 import com.android.internal.util.Preconditions;
354 import com.android.internal.util.function.DecFunction;
355 import com.android.internal.util.function.HeptFunction;
356 import com.android.internal.util.function.HexFunction;
357 import com.android.internal.util.function.QuadFunction;
358 import com.android.internal.util.function.QuintFunction;
359 import com.android.internal.util.function.TriFunction;
360 import com.android.internal.util.function.UndecFunction;
361 import com.android.server.AlarmManagerInternal;
362 import com.android.server.DeviceIdleInternal;
363 import com.android.server.DisplayThread;
364 import com.android.server.IntentResolver;
365 import com.android.server.IoThread;
366 import com.android.server.LocalManagerRegistry;
367 import com.android.server.LocalServices;
368 import com.android.server.LockGuard;
369 import com.android.server.NetworkManagementInternal;
370 import com.android.server.PackageWatchdog;
371 import com.android.server.ServiceThread;
372 import com.android.server.SystemConfig;
373 import com.android.server.SystemService;
374 import com.android.server.SystemServiceManager;
375 import com.android.server.ThreadPriorityBooster;
376 import com.android.server.UserspaceRebootLogger;
377 import com.android.server.Watchdog;
378 import com.android.server.am.LowMemDetector.MemFactor;
379 import com.android.server.appop.AppOpsService;
380 import com.android.server.compat.PlatformCompat;
381 import com.android.server.contentcapture.ContentCaptureManagerInternal;
382 import com.android.server.firewall.IntentFirewall;
383 import com.android.server.graphics.fonts.FontManagerInternal;
384 import com.android.server.job.JobSchedulerInternal;
385 import com.android.server.os.NativeTombstoneManager;
386 import com.android.server.pm.Installer;
387 import com.android.server.pm.parsing.pkg.AndroidPackage;
388 import com.android.server.pm.permission.PermissionManagerServiceInternal;
389 import com.android.server.uri.GrantUri;
390 import com.android.server.uri.NeededUriGrants;
391 import com.android.server.uri.UriGrantsManagerInternal;
392 import com.android.server.utils.PriorityDump;
393 import com.android.server.utils.TimingsTraceAndSlog;
394 import com.android.server.vr.VrManagerInternal;
395 import com.android.server.wm.ActivityMetricsLaunchObserver;
396 import com.android.server.wm.ActivityServiceConnectionsHolder;
397 import com.android.server.wm.ActivityTaskManagerInternal;
398 import com.android.server.wm.ActivityTaskManagerService;
399 import com.android.server.wm.WindowManagerInternal;
400 import com.android.server.wm.WindowManagerService;
401 import com.android.server.wm.WindowProcessController;
402 
403 import dalvik.system.VMRuntime;
404 
405 import libcore.util.EmptyArray;
406 
407 import java.io.File;
408 import java.io.FileDescriptor;
409 import java.io.FileNotFoundException;
410 import java.io.FileOutputStream;
411 import java.io.IOException;
412 import java.io.InputStreamReader;
413 import java.io.PrintWriter;
414 import java.io.StringWriter;
415 import java.nio.charset.StandardCharsets;
416 import java.text.SimpleDateFormat;
417 import java.util.ArrayList;
418 import java.util.Arrays;
419 import java.util.Collections;
420 import java.util.Comparator;
421 import java.util.Date;
422 import java.util.HashMap;
423 import java.util.HashSet;
424 import java.util.Iterator;
425 import java.util.LinkedList;
426 import java.util.List;
427 import java.util.Locale;
428 import java.util.Map;
429 import java.util.Set;
430 import java.util.UUID;
431 import java.util.concurrent.Executor;
432 import java.util.concurrent.atomic.AtomicInteger;
433 
434 public class ActivityManagerService extends IActivityManager.Stub
435         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
436 
437     private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED =
438             "persist.sys.device_provisioned";
439 
440     static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
441     static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
442     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
443     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
444     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
445     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
446     static final String TAG_LRU = TAG + POSTFIX_LRU;
447     static final String TAG_MU = TAG + POSTFIX_MU;
448     static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
449     static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
450     private static final String TAG_POWER = TAG + POSTFIX_POWER;
451     static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
452     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
453     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
454     static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
455 
456     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
457     // here so that while the job scheduler can depend on AMS, the other way around
458     // need not be the case.
459     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
460 
461     private static final String INTENT_BUGREPORT_REQUESTED =
462             "com.android.internal.intent.action.BUGREPORT_REQUESTED";
463     private static final String SHELL_APP_PACKAGE = "com.android.shell";
464 
465     // The flags that are set for all calls we make to the package manager.
466     public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
467 
468     static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed";
469 
470     public static final String ANR_TRACE_DIR = "/data/anr";
471 
472     // Maximum number of receivers an app can register.
473     private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000;
474 
475     // How long we wait for a launched process to attach to the activity manager
476     // before we decide it's never going to come up for real.
477     static final int PROC_START_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
478     // How long we wait to kill an application zygote, after the last process using
479     // it has gone away.
480     static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000;
481 
482     // How long we wait for a launched process to attach to the activity manager
483     // before we decide it's never going to come up for real, when the process was
484     // started with a wrapper for instrumentation (such as Valgrind) because it
485     // could take much longer than usual.
486     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
487 
488     // How long we allow a receiver to run before giving up on it.
489     static final int BROADCAST_FG_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
490     static final int BROADCAST_BG_TIMEOUT = 60 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
491 
492     public static final int MY_PID = myPid();
493 
494     static final String[] EMPTY_STRING_ARRAY = new String[0];
495 
496     // How many bytes to write into the dropbox log before truncating
497     static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024;
498     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
499     // as one line, but close enough for now.
500     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
501 
502     // Necessary ApplicationInfo flags to mark an app as persistent
503     static final int PERSISTENT_MASK =
504             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
505 
506     // Intent sent when remote bugreport collection has been completed
507     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
508             "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
509 
510     // If set, we will push process association information in to procstats.
511     static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true;
512 
513     /**
514      * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}.
515      */
516     private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec
517 
518     // The minimum memory growth threshold (in KB) for low RAM devices.
519     private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB
520 
521     /**
522      * The number of binder proxies we need to have before we start warning and
523      * dumping debug info.
524      */
525     private static final int BINDER_PROXY_HIGH_WATERMARK = 6000;
526 
527     /**
528      * Low watermark that needs to be met before we consider dumping info again,
529      * after already hitting the high watermark.
530      */
531     private static final int BINDER_PROXY_LOW_WATERMARK = 5500;
532 
533     // Max character limit for a notification title. If the notification title is larger than this
534     // the notification will not be legible to the user.
535     private static final int MAX_BUGREPORT_TITLE_SIZE = 50;
536     private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150;
537 
538     private static final int NATIVE_DUMP_TIMEOUT_MS =
539             2000 * Build.HW_TIMEOUT_MULTIPLIER; // 2 seconds;
540     private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes.
541 
542     OomAdjuster mOomAdjuster;
543 
544     static final String EXTRA_TITLE = "android.intent.extra.TITLE";
545     static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION";
546     static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE";
547 
548     /**
549      * The maximum number of bytes that {@link #setProcessStateSummary} accepts.
550      *
551      * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])}
552      */
553     static final int MAX_STATE_DATA_SIZE = 128;
554 
555     /** All system services */
556     SystemServiceManager mSystemServiceManager;
557 
558     private Installer mInstaller;
559 
560     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
561 
562     @CompositeRWLock({"this", "mProcLock"})
563     final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
564 
565     public final IntentFirewall mIntentFirewall;
566 
567     public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler();
568 
569     /**
570      * The global lock for AMS, it's de-facto the ActivityManagerService object as of now.
571      */
572     final ActivityManagerGlobalLock mGlobalLock = ActivityManagerService.this;
573 
574     /**
575      * Whether or not to enable the {@link #mProcLock}. If {@code false}, the {@link #mProcLock}
576      * will be equivalent to the {@link #mGlobalLock}.
577      */
578     private static final boolean ENABLE_PROC_LOCK = true;
579 
580     /**
581      * The lock for process management.
582      *
583      * <p>
584      * This lock is widely used in conjunction with the {@link #mGlobalLock} at present,
585      * where it'll require any of the locks to read from a data class, and both of the locks
586      * to write into that data class.
587      *
588      * For the naming convention of function suffixes:
589      * <ul>
590      *    <li>-LOSP:    Locked with any Of global am Service or Process lock</li>
591      *    <li>-LSP:     Locked with both of global am Service and Process lock</li>
592      *    <li>-Locked:  Locked with global am service lock alone</li>
593      *    <li>-LPr:     Locked with Process lock alone</li>
594      * </ul>
595      * For the simplicity, the getters/setters of the fields in data classes usually don't end with
596      * the above suffixes even if they're guarded by the locks here.
597      * </p>
598      *
599      * <p>
600      * In terms of locking order, it should be right below to the {@link #mGlobalLock},
601      * and above everything else which used to be underneath the {@link #mGlobalLock}.
602      * As of today, the core components(services/providers/broadcasts) are still guarded by
603      * the {@link #mGlobalLock} alone, so be cautious, avoid from acquiring the {@link #mGlobalLock}
604      * while holding this lock.
605      * </p>
606      *
607      */
608     final ActivityManagerGlobalLock mProcLock = ENABLE_PROC_LOCK
609             ? new ActivityManagerProcLock() : mGlobalLock;
610 
611     // Whether we should use SCHED_FIFO for UI and RenderThreads.
612     final boolean mUseFifoUiScheduling;
613 
614     // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
615     // For simplicity, since we statically declare the size of the array of BroadcastQueues,
616     // we still create this new offload queue, but never ever put anything on it.
617     final boolean mEnableOffloadQueue;
618 
619     final BroadcastQueue mFgBroadcastQueue;
620     final BroadcastQueue mBgBroadcastQueue;
621     final BroadcastQueue mOffloadBroadcastQueue;
622     // Convenient for easy iteration over the queues. Foreground is first
623     // so that dispatch of foreground broadcasts gets precedence.
624     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[3];
625 
626     @GuardedBy("this")
627     BroadcastStats mLastBroadcastStats;
628 
629     @GuardedBy("this")
630     BroadcastStats mCurBroadcastStats;
631 
632     TraceErrorLogger mTraceErrorLogger;
633 
broadcastQueueForIntent(Intent intent)634     BroadcastQueue broadcastQueueForIntent(Intent intent) {
635         if (isOnOffloadQueue(intent.getFlags())) {
636             if (DEBUG_BROADCAST_BACKGROUND) {
637                 Slog.i(TAG_BROADCAST,
638                         "Broadcast intent " + intent + " on offload queue");
639             }
640             return mOffloadBroadcastQueue;
641         }
642 
643         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
644         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
645                 "Broadcast intent " + intent + " on "
646                 + (isFg ? "foreground" : "background") + " queue");
647         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
648     }
649 
650     /**
651      * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
652      * <p>Not actually used</p>
653      */
654     private volatile String mDeviceOwnerName;
655 
656     private volatile int mDeviceOwnerUid = INVALID_UID;
657 
658     /**
659      * Map userId to its companion app uids.
660      */
661     private final Map<Integer, Set<Integer>> mCompanionAppUidsMap = new ArrayMap<>();
662 
663     /**
664      * The profile owner UIDs.
665      */
666     private ArraySet<Integer> mProfileOwnerUids = null;
667 
668     final UserController mUserController;
669     @VisibleForTesting
670     public final PendingIntentController mPendingIntentController;
671 
672     final AppErrors mAppErrors;
673     final PackageWatchdog mPackageWatchdog;
674 
675     /**
676      * Indicates the maximum time spent waiting for the network rules to get updated.
677      */
678     @VisibleForTesting
679     long mWaitForNetworkTimeoutMs;
680 
681     /**
682      * Uids of apps with current active camera sessions.  Access synchronized on
683      * the IntArray instance itself, and no other locks must be acquired while that
684      * one is held.
685      */
686     @GuardedBy("mActiveCameraUids")
687     final IntArray mActiveCameraUids = new IntArray(4);
688 
689     /**
690      * Helper class which strips out priority and proto arguments then calls the dump function with
691      * the appropriate arguments. If priority arguments are omitted, function calls the legacy
692      * dump command.
693      * If priority arguments are omitted all sections are dumped, otherwise sections are dumped
694      * according to their priority.
695      */
696     private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
697         @Override
698         public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
699                 boolean asProto) {
700             if (asProto) return;
701             doDump(fd, pw, new String[]{"activities"}, asProto);
702             doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
703         }
704 
705         @Override
706         public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
707             doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto);
708         }
709 
710         @Override
711         public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
712             doDump(fd, pw, args, asProto);
713         }
714     };
715 
716     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
717             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
718 
boostPriorityForLockedSection()719     static void boostPriorityForLockedSection() {
720         sThreadPriorityBooster.boost();
721     }
722 
resetPriorityAfterLockedSection()723     static void resetPriorityAfterLockedSection() {
724         sThreadPriorityBooster.reset();
725     }
726 
727     private static ThreadPriorityBooster sProcThreadPriorityBooster = new ThreadPriorityBooster(
728             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PROC);
729 
boostPriorityForProcLockedSection()730     static void boostPriorityForProcLockedSection() {
731         if (ENABLE_PROC_LOCK) {
732             sProcThreadPriorityBooster.boost();
733         } else {
734             sThreadPriorityBooster.boost();
735         }
736     }
737 
resetPriorityAfterProcLockedSection()738     static void resetPriorityAfterProcLockedSection() {
739         if (ENABLE_PROC_LOCK) {
740             sProcThreadPriorityBooster.reset();
741         } else {
742             sThreadPriorityBooster.reset();
743         }
744     }
745 
746     /**
747      * Process management.
748      */
749     final ProcessList mProcessList;
750 
751     /**
752      * The list of phantom processes.
753      * @see PhantomProcessRecord
754      */
755     final PhantomProcessList mPhantomProcessList;
756 
757     /**
758      * Tracking long-term execution of processes to look for abuse and other
759      * bad app behavior.
760      */
761     final ProcessStatsService mProcessStats;
762 
763     /**
764      * Non-persistent appId allowlist for background restrictions
765      */
766     @CompositeRWLock({"this", "mProcLock"})
767     private int[] mBackgroundAppIdAllowlist = new int[] {
768             BLUETOOTH_UID
769     };
770 
771     /**
772      * Broadcast actions that will always be deliverable to unlaunched/background apps
773      */
774     @GuardedBy("this")
775     private ArraySet<String> mBackgroundLaunchBroadcasts;
776 
777     /**
778      * When an app has restrictions on the other apps that can have associations with it,
779      * it appears here with a set of the allowed apps and also track debuggability of the app.
780      */
781     @GuardedBy("this")
782     private ArrayMap<String, PackageAssociationInfo> mAllowedAssociations;
783 
784     /**
785      * Tracks association information for a particular package along with debuggability.
786      * <p> Associations for a package A are allowed to package B if B is part of the
787      *     allowed associations for A or if A is debuggable.
788      */
789     private final class PackageAssociationInfo {
790         private final String mSourcePackage;
791         private final ArraySet<String> mAllowedPackageAssociations;
792         private boolean mIsDebuggable;
793 
PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)794         PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages,
795                 boolean isDebuggable) {
796             mSourcePackage = sourcePackage;
797             mAllowedPackageAssociations = allowedPackages;
798             mIsDebuggable = isDebuggable;
799         }
800 
801         /**
802          * Returns true if {@code mSourcePackage} is allowed association with
803          * {@code targetPackage}.
804          */
isPackageAssociationAllowed(String targetPackage)805         boolean isPackageAssociationAllowed(String targetPackage) {
806             return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage);
807         }
808 
isDebuggable()809         boolean isDebuggable() {
810             return mIsDebuggable;
811         }
812 
setDebuggable(boolean isDebuggable)813         void setDebuggable(boolean isDebuggable) {
814             mIsDebuggable = isDebuggable;
815         }
816 
getAllowedPackageAssociations()817         ArraySet<String> getAllowedPackageAssociations() {
818             return mAllowedPackageAssociations;
819         }
820     }
821 
822     /**
823      * These are the currently running processes for which we have a ProcessInfo.
824      * Note: needs to be static since the permission checking call chain is static.  This
825      * all probably should be refactored into a separate permission checking object.
826      */
827     @GuardedBy("sActiveProcessInfoSelfLocked")
828     static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>();
829 
830     /**
831      * All of the processes we currently have running organized by pid.
832      * The keys are the pid running the application.
833      *
834      * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock!
835      */
836     final PidMap mPidsSelfLocked = new PidMap();
837     static final class PidMap {
838         private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>();
839 
get(int pid)840         ProcessRecord get(int pid) {
841             return mPidMap.get(pid);
842         }
843 
size()844         int size() {
845             return mPidMap.size();
846         }
847 
valueAt(int index)848         ProcessRecord valueAt(int index) {
849             return mPidMap.valueAt(index);
850         }
851 
keyAt(int index)852         int keyAt(int index) {
853             return mPidMap.keyAt(index);
854         }
855 
indexOfKey(int key)856         int indexOfKey(int key) {
857             return mPidMap.indexOfKey(key);
858         }
859 
doAddInternal(int pid, ProcessRecord app)860         void doAddInternal(int pid, ProcessRecord app) {
861             mPidMap.put(pid, app);
862         }
863 
doRemoveInternal(int pid, ProcessRecord app)864         boolean doRemoveInternal(int pid, ProcessRecord app) {
865             final ProcessRecord existingApp = mPidMap.get(pid);
866             if (existingApp != null && existingApp.getStartSeq() == app.getStartSeq()) {
867                 mPidMap.remove(pid);
868                 return true;
869             }
870             return false;
871         }
872 
doRemoveIfNoThreadInternal(int pid, ProcessRecord app)873         boolean doRemoveIfNoThreadInternal(int pid, ProcessRecord app) {
874             if (app == null || app.getThread() != null) {
875                 return false;
876             }
877             return doRemoveInternal(pid, app);
878         }
879     }
880 
881     private final PendingStartActivityUids mPendingStartActivityUids;
882 
883     /**
884      * Puts the process record in the map.
885      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
886      * method.
887      */
888     @GuardedBy("this")
addPidLocked(ProcessRecord app)889     void addPidLocked(ProcessRecord app) {
890         final int pid = app.getPid();
891         synchronized (mPidsSelfLocked) {
892             mPidsSelfLocked.doAddInternal(pid, app);
893         }
894         synchronized (sActiveProcessInfoSelfLocked) {
895             if (app.processInfo != null) {
896                 sActiveProcessInfoSelfLocked.put(pid, app.processInfo);
897             } else {
898                 sActiveProcessInfoSelfLocked.remove(pid);
899             }
900         }
901         mAtmInternal.onProcessMapped(pid, app.getWindowProcessController());
902     }
903 
904     /**
905      * Removes the process record from the map.
906      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
907      * method.
908      */
909     @GuardedBy("this")
removePidLocked(int pid, ProcessRecord app)910     void removePidLocked(int pid, ProcessRecord app) {
911         final boolean removed;
912         synchronized (mPidsSelfLocked) {
913             removed = mPidsSelfLocked.doRemoveInternal(pid, app);
914         }
915         if (removed) {
916             synchronized (sActiveProcessInfoSelfLocked) {
917                 sActiveProcessInfoSelfLocked.remove(pid);
918             }
919             mAtmInternal.onProcessUnMapped(pid);
920         }
921     }
922 
923     /**
924      * Removes the process record from the map if it doesn't have a thread.
925      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
926      * method.
927      */
928     @GuardedBy("this")
removePidIfNoThreadLocked(ProcessRecord app)929     private boolean removePidIfNoThreadLocked(ProcessRecord app) {
930         final boolean removed;
931         final int pid = app.getPid();
932         synchronized (mPidsSelfLocked) {
933             removed = mPidsSelfLocked.doRemoveIfNoThreadInternal(pid, app);
934         }
935         if (removed) {
936             synchronized (sActiveProcessInfoSelfLocked) {
937                 sActiveProcessInfoSelfLocked.remove(pid);
938             }
939             mAtmInternal.onProcessUnMapped(pid);
940         }
941         return removed;
942     }
943 
944     /**
945      * All of the processes that have been forced to be important.  The key
946      * is the pid of the caller who requested it (we hold a death
947      * link on it).
948      */
949     abstract class ImportanceToken implements IBinder.DeathRecipient {
950         final int pid;
951         final IBinder token;
952         final String reason;
953 
ImportanceToken(int _pid, IBinder _token, String _reason)954         ImportanceToken(int _pid, IBinder _token, String _reason) {
955             pid = _pid;
956             token = _token;
957             reason = _reason;
958         }
959 
960         @Override
toString()961         public String toString() {
962             return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
963                     + " " + reason + " " + pid + " " + token + " }";
964         }
965 
dumpDebug(ProtoOutputStream proto, long fieldId)966         void dumpDebug(ProtoOutputStream proto, long fieldId) {
967             final long pToken = proto.start(fieldId);
968             proto.write(ImportanceTokenProto.PID, pid);
969             if (token != null) {
970                 proto.write(ImportanceTokenProto.TOKEN, token.toString());
971             }
972             proto.write(ImportanceTokenProto.REASON, reason);
973             proto.end(pToken);
974         }
975     }
976     @GuardedBy("this")
977     final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
978 
979     /**
980      * List of records for processes that someone had tried to start before the
981      * system was ready.  We don't start them at that point, but ensure they
982      * are started by the time booting is complete.
983      */
984     @GuardedBy("this")
985     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
986 
987     /**
988      * List of persistent applications that are in the process
989      * of being started.
990      */
991     @GuardedBy("this")
992     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
993 
994     private final ActivityMetricsLaunchObserver mActivityLaunchObserver =
995             new ActivityMetricsLaunchObserver() {
996         @Override
997         public void onActivityLaunched(byte[] activity, int temperature) {
998             mAppProfiler.onActivityLaunched();
999         }
1000 
1001         // The other observer methods are unused
1002         @Override
1003         public void onIntentStarted(Intent intent, long timestampNs) {
1004         }
1005 
1006         @Override
1007         public void onIntentFailed() {
1008         }
1009 
1010         @Override
1011         public void onActivityLaunchCancelled(byte[] abortingActivity) {
1012         }
1013 
1014         @Override
1015         public void onActivityLaunchFinished(byte[] finalActivity, long timestampNs) {
1016         }
1017 
1018         @Override
1019         public void onReportFullyDrawn(byte[] finalActivity, long timestampNs) {
1020         }
1021     };
1022 
1023     private volatile boolean mBinderTransactionTrackingEnabled = false;
1024 
1025     /**
1026      * Fingerprints (hashCode()) of stack traces that we've
1027      * already logged DropBox entries for.  Guarded by itself.  If
1028      * something (rogue user app) forces this over
1029      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1030      */
1031     @GuardedBy("mAlreadyLoggedViolatedStacks")
1032     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1033     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1034 
1035     /**
1036      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
1037      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
1038      */
1039     @GuardedBy("this")
1040     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
1041 
1042     /**
1043      * Resolver for broadcast intents to registered receivers.
1044      * Holds BroadcastFilter (subclass of IntentFilter).
1045      */
1046     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1047             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1048         @Override
1049         protected boolean allowFilterResult(
1050                 BroadcastFilter filter, List<BroadcastFilter> dest) {
1051             IBinder target = filter.receiverList.receiver.asBinder();
1052             for (int i = dest.size() - 1; i >= 0; i--) {
1053                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1054                     return false;
1055                 }
1056             }
1057             return true;
1058         }
1059 
1060         @Override
1061         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
1062             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
1063                     || userId == filter.owningUserId) {
1064                 return super.newResult(filter, match, userId);
1065             }
1066             return null;
1067         }
1068 
1069         @Override
1070         protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) {
1071             return input;
1072         }
1073 
1074         @Override
1075         protected BroadcastFilter[] newArray(int size) {
1076             return new BroadcastFilter[size];
1077         }
1078 
1079         @Override
1080         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
1081             return packageName.equals(filter.packageName);
1082         }
1083     };
1084 
1085     /**
1086      * State of all active sticky broadcasts per user.  Keys are the action of the
1087      * sticky Intent, values are an ArrayList of all broadcasted intents with
1088      * that action (which should usually be one).  The SparseArray is keyed
1089      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1090      * for stickies that are sent to all users.
1091      */
1092     @GuardedBy("this")
1093     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
1094             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
1095 
1096     final ActiveServices mServices;
1097 
1098     final static class Association {
1099         final int mSourceUid;
1100         final String mSourceProcess;
1101         final int mTargetUid;
1102         final ComponentName mTargetComponent;
1103         final String mTargetProcess;
1104 
1105         int mCount;
1106         long mTime;
1107 
1108         int mNesting;
1109         long mStartTime;
1110 
1111         // states of the source process when the bind occurred.
1112         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1113         long mLastStateUptime;
1114         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1115                 - ActivityManager.MIN_PROCESS_STATE+1];
1116 
Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1117         Association(int sourceUid, String sourceProcess, int targetUid,
1118                 ComponentName targetComponent, String targetProcess) {
1119             mSourceUid = sourceUid;
1120             mSourceProcess = sourceProcess;
1121             mTargetUid = targetUid;
1122             mTargetComponent = targetComponent;
1123             mTargetProcess = targetProcess;
1124         }
1125     }
1126 
1127     /**
1128      * When service association tracking is enabled, this is all of the associations we
1129      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
1130      * -> association data.
1131      */
1132     @GuardedBy("this")
1133     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1134             mAssociations = new SparseArray<>();
1135     boolean mTrackingAssociations;
1136 
1137     /**
1138      * Backup/restore process management
1139      */
1140     @GuardedBy("this")
1141     final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>();
1142 
1143     final ContentProviderHelper mCpHelper;
1144 
1145     CoreSettingsObserver mCoreSettingsObserver;
1146 
1147     /**
1148      * All information we have collected about the runtime performance of
1149      * any user id that can impact battery performance.
1150      */
1151     final BatteryStatsService mBatteryStatsService;
1152 
1153     /**
1154      * Information about component usage
1155      */
1156     volatile UsageStatsManagerInternal mUsageStatsService;
1157 
1158     /**
1159      * Access to DeviceIdleController service.
1160      */
1161     DeviceIdleInternal mLocalDeviceIdleController;
1162 
1163     /**
1164      * Power-save allowlisted app-ids (not including except-idle-allowlisted ones).
1165      */
1166     @CompositeRWLock({"this", "mProcLock"})
1167     int[] mDeviceIdleAllowlist = new int[0];
1168 
1169     /**
1170      * Power-save allowlisted app-ids (including except-idle-allowlisted ones).
1171      */
1172     @CompositeRWLock({"this", "mProcLock"})
1173     int[] mDeviceIdleExceptIdleAllowlist = new int[0];
1174 
1175     /**
1176      * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1177      */
1178     @CompositeRWLock({"this", "mProcLock"})
1179     int[] mDeviceIdleTempAllowlist = new int[0];
1180 
1181     static final class PendingTempAllowlist {
1182         final int targetUid;
1183         final long duration;
1184         final String tag;
1185         final int type;
1186         final @ReasonCode int reasonCode;
1187         final int callingUid;
1188 
PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag, int type, int callingUid)1189         PendingTempAllowlist(int targetUid, long duration, @ReasonCode int reasonCode, String tag,
1190                 int type, int callingUid) {
1191             this.targetUid = targetUid;
1192             this.duration = duration;
1193             this.tag = tag;
1194             this.type = type;
1195             this.reasonCode = reasonCode;
1196             this.callingUid = callingUid;
1197         }
1198 
dumpDebug(ProtoOutputStream proto, long fieldId)1199         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1200             final long token = proto.start(fieldId);
1201             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID,
1202                     targetUid);
1203             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS,
1204                     duration);
1205             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag);
1206             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TYPE, type);
1207             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.REASON_CODE,
1208                     reasonCode);
1209             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.CALLING_UID,
1210                     callingUid);
1211             proto.end(token);
1212         }
1213     }
1214 
1215     @CompositeRWLock({"this", "mProcLock"})
1216     final PendingTempAllowlists mPendingTempAllowlist = new PendingTempAllowlists(this);
1217 
1218     public static final class FgsTempAllowListItem {
1219         final long mDuration;
1220         final @PowerExemptionManager.ReasonCode int mReasonCode;
1221         final String mReason;
1222         final int mCallingUid;
1223 
FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode, String reason, int callingUid)1224         FgsTempAllowListItem(long duration, @PowerExemptionManager.ReasonCode int reasonCode,
1225                 String reason, int callingUid) {
1226             mDuration = duration;
1227             mReasonCode = reasonCode;
1228             mReason = reason;
1229             mCallingUid = callingUid;
1230         }
1231 
dump(PrintWriter pw)1232         void dump(PrintWriter pw) {
1233             pw.print(" duration=" + mDuration +
1234                     " callingUid=" + UserHandle.formatUid(mCallingUid) +
1235                     " reasonCode=" + PowerExemptionManager.reasonCodeToString(mReasonCode) +
1236                     " reason=" + mReason);
1237         }
1238     }
1239 
1240     /**
1241      * The temp-allowlist that is allowed to start FGS from background.
1242      */
1243     @CompositeRWLock({"this", "mProcLock"})
1244     final FgsTempAllowList<FgsTempAllowListItem> mFgsStartTempAllowList =
1245             new FgsTempAllowList();
1246 
1247     static final FgsTempAllowListItem FAKE_TEMP_ALLOW_LIST_ITEM = new FgsTempAllowListItem(
1248             Long.MAX_VALUE, REASON_SYSTEM_ALLOW_LISTED, "", INVALID_UID);
1249 
1250     /*
1251      * List of uids that are allowed to have while-in-use permission when FGS is started from
1252      * background.
1253      */
1254     private final FgsTempAllowList<String> mFgsWhileInUseTempAllowList =
1255             new FgsTempAllowList();
1256 
1257     /**
1258      * Information about and control over application operations
1259      */
1260     final AppOpsService mAppOpsService;
1261     private AppOpsManager mAppOpsManager;
1262 
1263     /**
1264      * List of initialization arguments to pass to all processes when binding applications to them.
1265      * For example, references to the commonly used services.
1266      */
1267     ArrayMap<String, IBinder> mAppBindArgs;
1268     ArrayMap<String, IBinder> mIsolatedAppBindArgs;
1269 
1270     volatile boolean mProcessesReady = false;
1271     volatile boolean mSystemReady = false;
1272     volatile boolean mOnBattery = false;
1273     final int mFactoryTest;
1274     volatile boolean mBooting = false;
1275 
1276     @GuardedBy("this") boolean mCallFinishBooting = false;
1277     @GuardedBy("this") boolean mBootAnimationComplete = false;
1278 
1279     final Context mContext;
1280 
1281     /**
1282      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1283      * change at runtime. Use mContext for non-UI purposes.
1284      */
1285     final Context mUiContext;
1286 
1287     /**
1288      * Last time (in uptime) at which we checked for power usage.
1289      */
1290     @GuardedBy("mProcLock")
1291     long mLastPowerCheckUptime;
1292 
1293     /**
1294      * For some direct access we need to power manager.
1295      */
1296     PowerManagerInternal mLocalPowerManager;
1297 
1298     /**
1299      * State of external calls telling us if the device is awake or asleep.
1300      */
1301     AtomicInteger mWakefulness = new AtomicInteger(PowerManagerInternal.WAKEFULNESS_AWAKE);
1302 
1303     /**
1304      * The uptime of the last time we performed idle maintenance.
1305      */
1306     @GuardedBy("mProcLock")
1307     long mLastIdleTime = SystemClock.uptimeMillis();
1308 
1309     /**
1310      * For reporting to battery stats the current top application.
1311      *
1312      * <p>It has its own lock to avoid from the need of double locking if using the global
1313      * ActivityManagerService lock and proc lock to guard it.</p>
1314      */
1315     @GuardedBy("mCurResumedAppLock")
1316     private String mCurResumedPackage = null;
1317 
1318     @GuardedBy("mCurResumedAppLock")
1319     private int mCurResumedUid = -1;
1320 
1321     /**
1322      * Dedicated lock for {@link #mCurResumedPackage} and {@link #mCurResumedUid}.
1323      */
1324     private final Object mCurResumedAppLock = new Object();
1325 
1326     /**
1327      * For reporting to battery stats the apps currently running foreground
1328      * service.  The ProcessMap is package/uid tuples; each of these contain
1329      * an array of the currently foreground processes.
1330      */
1331     @GuardedBy("this")
1332     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1333             = new ProcessMap<ArrayList<ProcessRecord>>();
1334 
1335     /**
1336      * Set if the systemServer made a call to enterSafeMode.
1337      */
1338     @GuardedBy("this")
1339     boolean mSafeMode;
1340 
1341     @GuardedBy("this")
1342     private String mDebugApp = null;
1343 
1344     @GuardedBy("this")
1345     private boolean mWaitForDebugger = false;
1346 
1347     @GuardedBy("this")
1348     private boolean mDebugTransient = false;
1349 
1350     @GuardedBy("this")
1351     private String mOrigDebugApp = null;
1352 
1353     @GuardedBy("this")
1354     private boolean mOrigWaitForDebugger = false;
1355 
1356     @GuardedBy("this")
1357     boolean mAlwaysFinishActivities = false;
1358 
1359     @GuardedBy("mProcLock")
1360     private String mTrackAllocationApp = null;
1361 
1362     @GuardedBy("this")
1363     String mNativeDebuggingApp = null;
1364 
1365     final Injector mInjector;
1366 
1367     static final class ProcessChangeItem {
1368         static final int CHANGE_ACTIVITIES = 1<<0;
1369         static final int CHANGE_FOREGROUND_SERVICES = 1<<1;
1370         static final int CHANGE_CAPABILITY = 1<<2;
1371         int changes;
1372         int uid;
1373         int pid;
1374         int processState;
1375         int capability;
1376         boolean foregroundActivities;
1377         int foregroundServiceTypes;
1378     }
1379 
1380     @GuardedBy("mOomAdjObserverLock")
1381     OomAdjObserver mCurOomAdjObserver;
1382 
1383     @GuardedBy("mOomAdjObserverLock")
1384     int mCurOomAdjUid;
1385 
1386     /**
1387      * Dedicated lock for {@link #mCurOomAdjObserver} and {@link #mCurOomAdjUid}.
1388      */
1389     final Object mOomAdjObserverLock = new Object();
1390 
1391     interface OomAdjObserver {
onOomAdjMessage(String msg)1392         void onOomAdjMessage(String msg);
1393     }
1394 
1395     final AnrHelper mAnrHelper = new AnrHelper(this);
1396 
1397     /** Set to true after the system has finished booting. */
1398     volatile boolean mBooted = false;
1399 
1400     /**
1401      * Current boot phase.
1402      */
1403     int mBootPhase;
1404 
1405     @VisibleForTesting
1406     public WindowManagerService mWindowManager;
1407     WindowManagerInternal mWmInternal;
1408     @VisibleForTesting
1409     public ActivityTaskManagerService mActivityTaskManager;
1410     @VisibleForTesting
1411     public ActivityTaskManagerInternal mAtmInternal;
1412     UriGrantsManagerInternal mUgmInternal;
1413     @VisibleForTesting
1414     public final ActivityManagerInternal mInternal;
1415     final ActivityThread mSystemThread;
1416 
1417     final UidObserverController mUidObserverController;
1418 
1419     private final class AppDeathRecipient implements IBinder.DeathRecipient {
1420         final ProcessRecord mApp;
1421         final int mPid;
1422         final IApplicationThread mAppThread;
1423 
AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1424         AppDeathRecipient(ProcessRecord app, int pid,
1425                 IApplicationThread thread) {
1426             if (DEBUG_ALL) Slog.v(
1427                 TAG, "New death recipient " + this
1428                  + " for thread " + thread.asBinder());
1429             mApp = app;
1430             mPid = pid;
1431             mAppThread = thread;
1432         }
1433 
1434         @Override
binderDied()1435         public void binderDied() {
1436             if (DEBUG_ALL) Slog.v(
1437                 TAG, "Death received in " + this
1438                 + " for thread " + mAppThread.asBinder());
1439             synchronized(ActivityManagerService.this) {
1440                 appDiedLocked(mApp, mPid, mAppThread, true, null);
1441             }
1442         }
1443     }
1444 
1445     static final int SHOW_ERROR_UI_MSG = 1;
1446     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1447     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1448     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1449     static final int SERVICE_TIMEOUT_MSG = 12;
1450     static final int UPDATE_TIME_ZONE = 13;
1451     static final int PROC_START_TIMEOUT_MSG = 20;
1452     static final int KILL_APPLICATION_MSG = 22;
1453     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1454     static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
1455     static final int CLEAR_DNS_CACHE_MSG = 28;
1456     static final int UPDATE_HTTP_PROXY_MSG = 29;
1457     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1458     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1459     static final int REPORT_MEM_USAGE_MSG = 33;
1460     static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1461     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1462     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1463     static final int ABORT_DUMPHEAP_MSG = 51;
1464     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1465     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1466     static final int IDLE_UIDS_MSG = 58;
1467     static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1468     static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1469     static final int PUSH_TEMP_ALLOWLIST_UI_MSG = 68;
1470     static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1471     static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70;
1472     static final int KILL_APP_ZYGOTE_MSG = 71;
1473     static final int BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG = 72;
1474     static final int WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG = 73;
1475 
1476     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1477 
1478     /**
1479      * Flag whether the current user is a "monkey", i.e. whether
1480      * the UI is driven by a UI automation tool.
1481      */
1482     private volatile boolean mUserIsMonkey;
1483 
1484     @VisibleForTesting
1485     public final ServiceThread mHandlerThread;
1486     final MainHandler mHandler;
1487     final Handler mUiHandler;
1488     final ServiceThread mProcStartHandlerThread;
1489     final Handler mProcStartHandler;
1490 
1491     ActivityManagerConstants mConstants;
1492 
1493     // Encapsulates the global setting "hidden_api_blacklist_exemptions"
1494     final HiddenApiSettings mHiddenApiBlacklist;
1495 
1496     private final PlatformCompat mPlatformCompat;
1497 
1498     PackageManagerInternal mPackageManagerInt;
1499     PermissionManagerServiceInternal mPermissionManagerInt;
1500     private TestUtilityService mTestUtilityService;
1501 
1502     /**
1503      * Whether to force background check on all apps (for battery saver) or not.
1504      */
1505     @CompositeRWLock({"this", "mProcLock"})
1506     private boolean mForceBackgroundCheck;
1507 
1508     private static String sTheRealBuildSerial = Build.UNKNOWN;
1509 
1510     @GuardedBy("mProcLock")
1511     private ParcelFileDescriptor[] mLifeMonitorFds;
1512 
1513     static final HostingRecord sNullHostingRecord = new HostingRecord(null);
1514     /**
1515      * Used to notify activity lifecycle events.
1516      */
1517     @Nullable volatile ContentCaptureManagerInternal mContentCaptureService;
1518 
1519     /*
1520      * The default duration for the binder heavy hitter auto sampler
1521      */
1522     private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS = 300000L;
1523 
1524     /**
1525      * The default throttling duration for the binder heavy hitter auto sampler
1526      */
1527     private static final long BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS = 3600000L;
1528 
1529     /**
1530      * The last time when the binder heavy hitter auto sampler started.
1531      */
1532     @GuardedBy("mProcLock")
1533     private long mLastBinderHeavyHitterAutoSamplerStart = 0L;
1534 
1535     final AppProfiler mAppProfiler;
1536 
1537     private static final int INDEX_NATIVE_PSS = 0;
1538     private static final int INDEX_NATIVE_SWAP_PSS = 1;
1539     private static final int INDEX_NATIVE_RSS = 2;
1540     private static final int INDEX_DALVIK_PSS = 3;
1541     private static final int INDEX_DALVIK_SWAP_PSS = 4;
1542     private static final int INDEX_DALVIK_RSS = 5;
1543     private static final int INDEX_OTHER_PSS = 6;
1544     private static final int INDEX_OTHER_SWAP_PSS = 7;
1545     private static final int INDEX_OTHER_RSS = 8;
1546     private static final int INDEX_TOTAL_PSS = 9;
1547     private static final int INDEX_TOTAL_SWAP_PSS = 10;
1548     private static final int INDEX_TOTAL_RSS = 11;
1549     private static final int INDEX_TOTAL_NATIVE_PSS = 12;
1550     private static final int INDEX_TOTAL_MEMTRACK_GRAPHICS = 13;
1551     private static final int INDEX_TOTAL_MEMTRACK_GL = 14;
1552     private static final int INDEX_LAST = 15;
1553 
1554     /**
1555      * Used to notify activity lifecycle events.
1556      */
1557     @Nullable
1558     volatile ActivityManagerInternal.VoiceInteractionManagerProvider
1559             mVoiceInteractionManagerProvider;
1560 
1561     final class UiHandler extends Handler {
UiHandler()1562         public UiHandler() {
1563             super(com.android.server.UiThread.get().getLooper(), null, true);
1564         }
1565 
1566         @Override
handleMessage(Message msg)1567         public void handleMessage(Message msg) {
1568             switch (msg.what) {
1569                 case SHOW_ERROR_UI_MSG: {
1570                     mAppErrors.handleShowAppErrorUi(msg);
1571                     ensureBootCompleted();
1572                 } break;
1573                 case SHOW_NOT_RESPONDING_UI_MSG: {
1574                     mAppErrors.handleShowAnrUi(msg);
1575                     ensureBootCompleted();
1576                 } break;
1577                 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1578                     HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1579                     synchronized (mProcLock) {
1580                         ProcessRecord proc = (ProcessRecord) data.get("app");
1581                         if (proc == null) {
1582                             Slog.e(TAG, "App not found when showing strict mode dialog.");
1583                             break;
1584                         }
1585                         if (proc.mErrorState.getDialogController().hasViolationDialogs()) {
1586                             Slog.e(TAG, "App already has strict mode dialog: " + proc);
1587                             return;
1588                         }
1589                         AppErrorResult res = (AppErrorResult) data.get("result");
1590                         if (mAtmInternal.showStrictModeViolationDialog()) {
1591                             proc.mErrorState.getDialogController().showViolationDialogs(res);
1592                         } else {
1593                             // The device is asleep, so just pretend that the user
1594                             // saw a crash dialog and hit "force quit".
1595                             res.set(0);
1596                         }
1597                     }
1598                     ensureBootCompleted();
1599                 } break;
1600                 case WAIT_FOR_DEBUGGER_UI_MSG: {
1601                     synchronized (mProcLock) {
1602                         ProcessRecord app = (ProcessRecord) msg.obj;
1603                         if (msg.arg1 != 0) {
1604                             if (!app.hasWaitedForDebugger()) {
1605                                 app.mErrorState.getDialogController().showDebugWaitingDialogs();
1606                                 app.setWaitedForDebugger(true);
1607                             }
1608                         } else {
1609                             app.mErrorState.getDialogController().clearWaitingDialog();
1610                         }
1611                     }
1612                 } break;
1613                 case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1614                     mProcessList.dispatchProcessesChanged();
1615                     break;
1616                 }
1617                 case DISPATCH_PROCESS_DIED_UI_MSG: {
1618                     if (false) { // DO NOT SUBMIT WITH TRUE
1619                         maybeTriggerWatchdog();
1620                     }
1621                     final int pid = msg.arg1;
1622                     final int uid = msg.arg2;
1623                     mProcessList.dispatchProcessDied(pid, uid);
1624                     break;
1625                 }
1626                 case DISPATCH_OOM_ADJ_OBSERVER_MSG: {
1627                     dispatchOomAdjObserver((String) msg.obj);
1628                 } break;
1629                 case PUSH_TEMP_ALLOWLIST_UI_MSG: {
1630                     pushTempAllowlist();
1631                 } break;
1632             }
1633         }
1634     }
1635 
1636     final class MainHandler extends Handler {
MainHandler(Looper looper)1637         public MainHandler(Looper looper) {
1638             super(looper, null, true);
1639         }
1640 
1641         @Override
handleMessage(Message msg)1642         public void handleMessage(Message msg) {
1643             switch (msg.what) {
1644             case GC_BACKGROUND_PROCESSES_MSG: {
1645                 synchronized (ActivityManagerService.this) {
1646                     mAppProfiler.performAppGcsIfAppropriateLocked();
1647                 }
1648             } break;
1649             case SERVICE_TIMEOUT_MSG: {
1650                 mServices.serviceTimeout((ProcessRecord) msg.obj);
1651             } break;
1652             case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1653                 mServices.serviceForegroundTimeout((ServiceRecord) msg.obj);
1654             } break;
1655             case SERVICE_FOREGROUND_CRASH_MSG: {
1656                 SomeArgs args = (SomeArgs) msg.obj;
1657                 mServices.serviceForegroundCrash(
1658                         (ProcessRecord) args.arg1,
1659                         (String) args.arg2,
1660                         (ComponentName) args.arg3);
1661                 args.recycle();
1662             } break;
1663             case UPDATE_TIME_ZONE: {
1664                 synchronized (mProcLock) {
1665                     mProcessList.forEachLruProcessesLOSP(false, app -> {
1666                         final IApplicationThread thread = app.getThread();
1667                         if (thread != null) {
1668                             try {
1669                                 thread.updateTimeZone();
1670                             } catch (RemoteException ex) {
1671                                 Slog.w(TAG, "Failed to update time zone for: "
1672                                         + app.info.processName);
1673                             }
1674                             }
1675                         });
1676                     }
1677             } break;
1678             case CLEAR_DNS_CACHE_MSG: {
1679                 synchronized (mProcLock) {
1680                     mProcessList.clearAllDnsCacheLOSP();
1681                 }
1682             } break;
1683             case UPDATE_HTTP_PROXY_MSG: {
1684                 mProcessList.setAllHttpProxy();
1685             } break;
1686             case PROC_START_TIMEOUT_MSG: {
1687                 ProcessRecord app = (ProcessRecord) msg.obj;
1688                 synchronized (ActivityManagerService.this) {
1689                     processStartTimedOutLocked(app);
1690                 }
1691             } break;
1692             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1693                 ProcessRecord app = (ProcessRecord) msg.obj;
1694                 synchronized (ActivityManagerService.this) {
1695                     mCpHelper.processContentProviderPublishTimedOutLocked(app);
1696                 }
1697             } break;
1698             case KILL_APPLICATION_MSG: {
1699                 synchronized (ActivityManagerService.this) {
1700                     final int appId = msg.arg1;
1701                     final int userId = msg.arg2;
1702                     Bundle bundle = (Bundle) msg.obj;
1703                     String pkg = bundle.getString("pkg");
1704                     String reason = bundle.getString("reason");
1705                     forceStopPackageLocked(pkg, appId, false, false, true, false,
1706                             false, userId, reason);
1707                 }
1708             } break;
1709 
1710                 case KILL_APP_ZYGOTE_MSG: {
1711                     synchronized (ActivityManagerService.this) {
1712                         final AppZygote appZygote = (AppZygote) msg.obj;
1713                         mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */);
1714                     }
1715                 } break;
1716             case CHECK_EXCESSIVE_POWER_USE_MSG: {
1717                 checkExcessivePowerUsage();
1718                 removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
1719                 Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
1720                 sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
1721             } break;
1722             case REPORT_MEM_USAGE_MSG: {
1723                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>) msg.obj;
1724                 Thread thread = new Thread() {
1725                     @Override public void run() {
1726                         mAppProfiler.reportMemUsage(memInfos);
1727                     }
1728                 };
1729                 thread.start();
1730                 break;
1731             }
1732             case UPDATE_TIME_PREFERENCE_MSG: {
1733                 // The user's time format preference might have changed.
1734                 // For convenience we re-use the Intent extra values.
1735                 synchronized (mProcLock) {
1736                     mProcessList.updateAllTimePrefsLOSP(msg.arg1);
1737                 }
1738                 break;
1739             }
1740             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1741                 final int uid = msg.arg1;
1742                 final byte[] firstPacket = (byte[]) msg.obj;
1743 
1744                 synchronized (mProcLock) {
1745                     synchronized (mPidsSelfLocked) {
1746                         for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1747                             final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1748                             final IApplicationThread thread = p.getThread();
1749                             if (p.uid == uid && thread != null) {
1750                                 try {
1751                                     thread.notifyCleartextNetwork(firstPacket);
1752                                 } catch (RemoteException ignored) {
1753                                 }
1754                             }
1755                         }
1756                     }
1757                 }
1758             } break;
1759             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1760                 mAppProfiler.handlePostDumpHeapNotification();
1761             } break;
1762             case ABORT_DUMPHEAP_MSG: {
1763                 mAppProfiler.handleAbortDumpHeap((String) msg.obj);
1764             } break;
1765             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
1766                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
1767                 try {
1768                     connection.shutdown();
1769                 } catch (RemoteException e) {
1770                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
1771                 }
1772                 // Only a UiAutomation can set this flag and now that
1773                 // it is finished we make sure it is reset to its default.
1774                 mUserIsMonkey = false;
1775             } break;
1776             case IDLE_UIDS_MSG: {
1777                 idleUids();
1778             } break;
1779             case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
1780                 synchronized (mProcLock) {
1781                     mProcessList.handleAllTrustStorageUpdateLOSP();
1782                 }
1783             } break;
1784                 case BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG: {
1785                     handleBinderHeavyHitterAutoSamplerTimeOut();
1786                 } break;
1787                 case WAIT_FOR_CONTENT_PROVIDER_TIMEOUT_MSG: {
1788                     synchronized (ActivityManagerService.this) {
1789                         ((ContentProviderRecord) msg.obj).onProviderPublishStatusLocked(false);
1790                     }
1791                 } break;
1792             }
1793         }
1794     }
1795 
1796 
setSystemProcess()1797     public void setSystemProcess() {
1798         try {
1799             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
1800                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
1801             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
1802             ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
1803                     DUMP_FLAG_PRIORITY_HIGH);
1804             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
1805             ServiceManager.addService("dbinfo", new DbBinder(this));
1806             mAppProfiler.setCpuInfoService();
1807             ServiceManager.addService("permission", new PermissionController(this));
1808             ServiceManager.addService("processinfo", new ProcessInfoService(this));
1809             ServiceManager.addService("cacheinfo", new CacheBinder(this));
1810 
1811             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
1812                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
1813             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
1814 
1815             synchronized (this) {
1816                 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
1817                         false,
1818                         0,
1819                         new HostingRecord("system"));
1820                 app.setPersistent(true);
1821                 app.setPid(MY_PID);
1822                 app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
1823                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
1824                 addPidLocked(app);
1825                 updateLruProcessLocked(app, false, null);
1826                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
1827             }
1828         } catch (PackageManager.NameNotFoundException e) {
1829             throw new RuntimeException(
1830                     "Unable to find android system package", e);
1831         }
1832 
1833         // Start watching app ops after we and the package manager are up and running.
1834         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
1835                 new IAppOpsCallback.Stub() {
1836                     @Override public void opChanged(int op, int uid, String packageName) {
1837                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
1838                             if (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
1839                                     != AppOpsManager.MODE_ALLOWED) {
1840                                 runInBackgroundDisabled(uid);
1841                             }
1842                         }
1843                     }
1844                 });
1845 
1846         final int[] cameraOp = {AppOpsManager.OP_CAMERA};
1847         mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
1848             @Override
1849             public void opActiveChanged(int op, int uid, String packageName, String attributionTag,
1850                     boolean active, @AttributionFlags int attributionFlags,
1851                     int attributionChainId) {
1852                 cameraActiveChanged(uid, active);
1853             }
1854         });
1855     }
1856 
setWindowManager(WindowManagerService wm)1857     public void setWindowManager(WindowManagerService wm) {
1858         synchronized (this) {
1859             mWindowManager = wm;
1860             mWmInternal = LocalServices.getService(WindowManagerInternal.class);
1861             mActivityTaskManager.setWindowManager(wm);
1862         }
1863     }
1864 
1865     /**
1866      * @param usageStatsManager shouldn't be null
1867      */
setUsageStatsManager(@onNull UsageStatsManagerInternal usageStatsManager)1868     public void setUsageStatsManager(@NonNull UsageStatsManagerInternal usageStatsManager) {
1869         mUsageStatsService = usageStatsManager;
1870         mActivityTaskManager.setUsageStatsManager(usageStatsManager);
1871     }
1872 
1873     /**
1874      * Sets the internal content capture manager service.
1875      *
1876      * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock.
1877      */
setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)1878     public void setContentCaptureManager(
1879             @Nullable ContentCaptureManagerInternal contentCaptureManager) {
1880         mContentCaptureService = contentCaptureManager;
1881     }
1882 
startObservingNativeCrashes()1883     public void startObservingNativeCrashes() {
1884         final NativeCrashListener ncl = new NativeCrashListener(this);
1885         ncl.start();
1886     }
1887 
1888     /**
1889      * Sets a policy for handling app ops.
1890      *
1891      * @param appOpsPolicy The policy.
1892      */
setAppOpsPolicy(@ullable CheckOpsDelegate appOpsPolicy)1893     public void setAppOpsPolicy(@Nullable CheckOpsDelegate appOpsPolicy) {
1894         mAppOpsService.setAppOpsPolicy(appOpsPolicy);
1895     }
1896 
getAppOpsService()1897     public IAppOpsService getAppOpsService() {
1898         return mAppOpsService;
1899     }
1900 
1901     /**
1902      * Sets the internal voice interaction manager service.
1903      */
setVoiceInteractionManagerProvider( @ullable ActivityManagerInternal.VoiceInteractionManagerProvider provider)1904     private void setVoiceInteractionManagerProvider(
1905             @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) {
1906         mVoiceInteractionManagerProvider = provider;
1907     }
1908 
1909     static class MemBinder extends Binder {
1910         ActivityManagerService mActivityManagerService;
1911         private final PriorityDump.PriorityDumper mPriorityDumper =
1912                 new PriorityDump.PriorityDumper() {
1913             @Override
1914             public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args,
1915                     boolean asProto) {
1916                 dump(fd, pw, new String[] {"-a"}, asProto);
1917             }
1918 
1919             @Override
1920             public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
1921                 mActivityManagerService.dumpApplicationMemoryUsage(
1922                         fd, pw, "  ", args, false, null, asProto);
1923             }
1924         };
1925 
MemBinder(ActivityManagerService activityManagerService)1926         MemBinder(ActivityManagerService activityManagerService) {
1927             mActivityManagerService = activityManagerService;
1928         }
1929 
1930         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)1931         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1932             try {
1933                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
1934 
1935                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
1936                         "meminfo", pw)) return;
1937                 PriorityDump.dump(mPriorityDumper, fd, pw, args);
1938             } finally {
1939                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
1940             }
1941         }
1942     }
1943 
1944     static class GraphicsBinder extends Binder {
1945         ActivityManagerService mActivityManagerService;
GraphicsBinder(ActivityManagerService activityManagerService)1946         GraphicsBinder(ActivityManagerService activityManagerService) {
1947             mActivityManagerService = activityManagerService;
1948         }
1949 
1950         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)1951         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1952             try {
1953                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
1954 
1955                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
1956                         "gfxinfo", pw)) return;
1957                 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
1958             } finally {
1959                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
1960             }
1961         }
1962     }
1963 
1964     static class DbBinder extends Binder {
1965         ActivityManagerService mActivityManagerService;
DbBinder(ActivityManagerService activityManagerService)1966         DbBinder(ActivityManagerService activityManagerService) {
1967             mActivityManagerService = activityManagerService;
1968         }
1969 
1970         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)1971         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1972             try {
1973                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
1974 
1975                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
1976                         "dbinfo", pw)) return;
1977                 mActivityManagerService.dumpDbInfo(fd, pw, args);
1978             } finally {
1979                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
1980             }
1981         }
1982     }
1983 
1984     static class CacheBinder extends Binder {
1985         ActivityManagerService mActivityManagerService;
1986 
CacheBinder(ActivityManagerService activityManagerService)1987         CacheBinder(ActivityManagerService activityManagerService) {
1988             mActivityManagerService = activityManagerService;
1989         }
1990 
1991         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)1992         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1993             try {
1994                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
1995 
1996                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
1997                         "cacheinfo", pw)) {
1998                     return;
1999                 }
2000 
2001                 mActivityManagerService.dumpBinderCacheContents(fd, pw, args);
2002             } finally {
2003                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2004             }
2005         }
2006     }
2007 
2008     public static final class Lifecycle extends SystemService {
2009         private final ActivityManagerService mService;
2010         private static ActivityTaskManagerService sAtm;
2011 
Lifecycle(Context context)2012         public Lifecycle(Context context) {
2013             super(context);
2014             mService = new ActivityManagerService(context, sAtm);
2015         }
2016 
startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2017         public static ActivityManagerService startService(
2018                 SystemServiceManager ssm, ActivityTaskManagerService atm) {
2019             sAtm = atm;
2020             return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2021         }
2022 
2023         @Override
onStart()2024         public void onStart() {
2025             mService.start();
2026         }
2027 
2028         @Override
onBootPhase(int phase)2029         public void onBootPhase(int phase) {
2030             mService.mBootPhase = phase;
2031             if (phase == PHASE_SYSTEM_SERVICES_READY) {
2032                 mService.mBatteryStatsService.systemServicesReady();
2033                 mService.mServices.systemServicesReady();
2034             } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
2035                 mService.startBroadcastObservers();
2036             } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2037                 mService.mPackageWatchdog.onPackagesReady();
2038             }
2039         }
2040 
2041         @Override
onUserStopped(@onNull TargetUser user)2042         public void onUserStopped(@NonNull TargetUser user) {
2043             mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier());
2044         }
2045 
getService()2046         public ActivityManagerService getService() {
2047             return mService;
2048         }
2049     }
2050 
maybeLogUserspaceRebootEvent()2051     private void maybeLogUserspaceRebootEvent() {
2052         if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) {
2053             return;
2054         }
2055         final int userId = mUserController.getCurrentUserId();
2056         if (userId != UserHandle.USER_SYSTEM) {
2057             // Only log for user0.
2058             return;
2059         }
2060         // TODO(b/148767783): should we check all profiles under user0?
2061         UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId),
2062                 BackgroundThread.getExecutor());
2063     }
2064 
2065     /**
2066      * Encapsulates global settings related to hidden API enforcement behaviour, including tracking
2067      * the latest value via a content observer.
2068      */
2069     static class HiddenApiSettings extends ContentObserver
2070             implements DeviceConfig.OnPropertiesChangedListener {
2071 
2072         private final Context mContext;
2073         private boolean mBlacklistDisabled;
2074         private String mExemptionsStr;
2075         private List<String> mExemptions = Collections.emptyList();
2076         private int mLogSampleRate = -1;
2077         private int mStatslogSampleRate = -1;
2078         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
2079 
2080         /**
2081          * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
2082          * the range 0 to 0x10000 inclusive.
2083          *
2084          * @hide
2085          */
2086         public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE =
2087                 "hidden_api_access_log_sampling_rate";
2088 
2089         /**
2090          * Sampling rate for hidden API access event logging with statslog, as an integer in the
2091          * range 0 to 0x10000 inclusive.
2092          *
2093          * @hide
2094          */
2095         public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
2096                 "hidden_api_access_statslog_sampling_rate";
2097 
onPropertiesChanged(DeviceConfig.Properties properties)2098         public void onPropertiesChanged(DeviceConfig.Properties properties) {
2099             int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0);
2100             if (logSampleRate < 0 || logSampleRate > 0x10000) {
2101                 logSampleRate = -1;
2102             }
2103             if (logSampleRate != -1 && logSampleRate != mLogSampleRate) {
2104                 mLogSampleRate = logSampleRate;
2105                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
2106             }
2107 
2108             int statslogSampleRate =
2109                     properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
2110             if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) {
2111                 statslogSampleRate = -1;
2112             }
2113             if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) {
2114                 mStatslogSampleRate = statslogSampleRate;
2115                 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
2116             }
2117         }
2118 
HiddenApiSettings(Handler handler, Context context)2119         public HiddenApiSettings(Handler handler, Context context) {
2120             super(handler);
2121             mContext = context;
2122         }
2123 
registerObserver()2124         public void registerObserver() {
2125             mContext.getContentResolver().registerContentObserver(
2126                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
2127                     false,
2128                     this);
2129             mContext.getContentResolver().registerContentObserver(
2130                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
2131                     false,
2132                     this);
2133             DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT,
2134                     mContext.getMainExecutor(), this);
2135             update();
2136         }
2137 
update()2138         private void update() {
2139             String exemptions = Settings.Global.getString(mContext.getContentResolver(),
2140                     Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS);
2141             if (!TextUtils.equals(exemptions, mExemptionsStr)) {
2142                 mExemptionsStr = exemptions;
2143                 if ("*".equals(exemptions)) {
2144                     mBlacklistDisabled = true;
2145                     mExemptions = Collections.emptyList();
2146                 } else {
2147                     mBlacklistDisabled = false;
2148                     mExemptions = TextUtils.isEmpty(exemptions)
2149                             ? Collections.emptyList()
2150                             : Arrays.asList(exemptions.split(","));
2151                 }
2152                 if (!ZYGOTE_PROCESS.setApiDenylistExemptions(mExemptions)) {
2153                   Slog.e(TAG, "Failed to set API blacklist exemptions!");
2154                   // leave mExemptionsStr as is, so we don't try to send the same list again.
2155                   mExemptions = Collections.emptyList();
2156                 }
2157             }
2158             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
2159         }
2160 
getValidEnforcementPolicy(String settingsKey)2161         private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) {
2162             int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey,
2163                     ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT);
2164             if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) {
2165                 return policy;
2166             } else {
2167                 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
2168             }
2169         }
2170 
isDisabled()2171         boolean isDisabled() {
2172             return mBlacklistDisabled;
2173         }
2174 
getPolicy()2175         @HiddenApiEnforcementPolicy int getPolicy() {
2176             return mPolicy;
2177         }
2178 
onChange(boolean selfChange)2179         public void onChange(boolean selfChange) {
2180             update();
2181         }
2182     }
2183 
getAppOpsManager()2184     AppOpsManager getAppOpsManager() {
2185         if (mAppOpsManager == null) {
2186             mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
2187         }
2188         return mAppOpsManager;
2189     }
2190 
2191     /**
2192      * Provides the basic functionality for activity task related tests when a handler thread is
2193      * given to initialize the dependency members.
2194      */
2195     @VisibleForTesting
ActivityManagerService(Injector injector, ServiceThread handlerThread)2196     public ActivityManagerService(Injector injector, ServiceThread handlerThread) {
2197         final boolean hasHandlerThread = handlerThread != null;
2198         mInjector = injector;
2199         mContext = mInjector.getContext();
2200         mUiContext = null;
2201         mAppErrors = null;
2202         mPackageWatchdog = null;
2203         mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */);
2204         mBatteryStatsService = null;
2205         mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null;
2206         mHandlerThread = handlerThread;
2207         mConstants = hasHandlerThread
2208                 ? new ActivityManagerConstants(mContext, this, mHandler) : null;
2209         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
2210         mPlatformCompat = null;
2211         mProcessList = injector.getProcessList(this);
2212         mProcessList.init(this, activeUids, mPlatformCompat);
2213         mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(), null);
2214         mPhantomProcessList = new PhantomProcessList(this);
2215         mOomAdjuster = hasHandlerThread
2216                 ? new OomAdjuster(this, mProcessList, activeUids, handlerThread) : null;
2217 
2218         mIntentFirewall = hasHandlerThread
2219                 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null;
2220         mProcessStats = null;
2221         mCpHelper = new ContentProviderHelper(this, false);
2222         // For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from
2223         // {@link ActivityTaskSupervisor#cleanUpRemovedTaskLocked}.
2224         mServices = hasHandlerThread ? new ActiveServices(this) : null;
2225         mSystemThread = null;
2226         mUiHandler = injector.getUiHandler(null /* service */);
2227         mUidObserverController = new UidObserverController(mUiHandler);
2228         mUserController = hasHandlerThread ? new UserController(this) : null;
2229         mPendingIntentController = hasHandlerThread
2230                 ? new PendingIntentController(handlerThread.getLooper(), mUserController,
2231                         mConstants) : null;
2232         mProcStartHandlerThread = null;
2233         mProcStartHandler = null;
2234         mHiddenApiBlacklist = null;
2235         mFactoryTest = FACTORY_TEST_OFF;
2236         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2237         mInternal = new LocalService();
2238         mPendingStartActivityUids = new PendingStartActivityUids(mContext);
2239         mUseFifoUiScheduling = false;
2240         mEnableOffloadQueue = false;
2241         mFgBroadcastQueue = mBgBroadcastQueue = mOffloadBroadcastQueue = null;
2242     }
2243 
2244     // Note: This method is invoked on the main thread but may need to attach various
2245     // handlers to other threads.  So take care to be explicit about the looper.
ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2246     public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
2247         LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2248         mInjector = new Injector(systemContext);
2249         mContext = systemContext;
2250 
2251         mFactoryTest = FactoryTest.getMode();
2252         mSystemThread = ActivityThread.currentActivityThread();
2253         mUiContext = mSystemThread.getSystemUiContext();
2254 
2255         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2256 
2257         mHandlerThread = new ServiceThread(TAG,
2258                 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2259         mHandlerThread.start();
2260         mHandler = new MainHandler(mHandlerThread.getLooper());
2261         mUiHandler = mInjector.getUiHandler(this);
2262 
2263         mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2264                 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2265         mProcStartHandlerThread.start();
2266         mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
2267 
2268         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2269         final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2270         mPlatformCompat = (PlatformCompat) ServiceManager.getService(
2271                 Context.PLATFORM_COMPAT_SERVICE);
2272         mProcessList = mInjector.getProcessList(this);
2273         mProcessList.init(this, activeUids, mPlatformCompat);
2274         mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
2275                 new LowMemDetector(this));
2276         mPhantomProcessList = new PhantomProcessList(this);
2277         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2278 
2279         // Broadcast policy parameters
2280         final BroadcastConstants foreConstants = new BroadcastConstants(
2281                 Settings.Global.BROADCAST_FG_CONSTANTS);
2282         foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2283 
2284         final BroadcastConstants backConstants = new BroadcastConstants(
2285                 Settings.Global.BROADCAST_BG_CONSTANTS);
2286         backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2287 
2288         final BroadcastConstants offloadConstants = new BroadcastConstants(
2289                 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2290         offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2291         // by default, no "slow" policy in this queue
2292         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2293 
2294         mEnableOffloadQueue = SystemProperties.getBoolean(
2295                 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
2296 
2297         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2298                 "foreground", foreConstants, false);
2299         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2300                 "background", backConstants, true);
2301         mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
2302                 "offload", offloadConstants, true);
2303         mBroadcastQueues[0] = mFgBroadcastQueue;
2304         mBroadcastQueues[1] = mBgBroadcastQueue;
2305         mBroadcastQueues[2] = mOffloadBroadcastQueue;
2306 
2307         mServices = new ActiveServices(this);
2308         mCpHelper = new ContentProviderHelper(this, true);
2309         mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2310         mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2311         mUidObserverController = new UidObserverController(mUiHandler);
2312 
2313         final File systemDir = SystemServiceManager.ensureSystemDir();
2314 
2315         // TODO: Move creation of battery stats service outside of activity manager service.
2316         mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
2317                 BackgroundThread.get().getHandler());
2318         mBatteryStatsService.getActiveStatistics().readLocked();
2319         mBatteryStatsService.scheduleWriteToDisk();
2320         mOnBattery = DEBUG_POWER ? true
2321                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2322         mBatteryStatsService.getActiveStatistics().setCallback(this);
2323         mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2324 
2325         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2326 
2327         mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2328 
2329         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2330 
2331         mUserController = new UserController(this);
2332 
2333         mPendingIntentController = new PendingIntentController(
2334                 mHandlerThread.getLooper(), mUserController, mConstants);
2335 
2336         mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;
2337 
2338         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2339         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2340 
2341         mActivityTaskManager = atm;
2342         mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2343                 DisplayThread.get().getLooper());
2344         mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2345 
2346         mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2347 
2348         Watchdog.getInstance().addMonitor(this);
2349         Watchdog.getInstance().addThread(mHandler);
2350 
2351         // bind background threads to little cores
2352         // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2353         // make sure we've already adjusted system_server's internal view of itself first
2354         updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2355         try {
2356             Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2357                     Process.THREAD_GROUP_SYSTEM);
2358             Process.setThreadGroupAndCpuset(
2359                     mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
2360                     Process.THREAD_GROUP_SYSTEM);
2361         } catch (Exception e) {
2362             Slog.w(TAG, "Setting background thread cpuset failed");
2363         }
2364 
2365         mInternal = new LocalService();
2366         mPendingStartActivityUids = new PendingStartActivityUids(mContext);
2367         mTraceErrorLogger = new TraceErrorLogger();
2368     }
2369 
setSystemServiceManager(SystemServiceManager mgr)2370     public void setSystemServiceManager(SystemServiceManager mgr) {
2371         mSystemServiceManager = mgr;
2372     }
2373 
setInstaller(Installer installer)2374     public void setInstaller(Installer installer) {
2375         mInstaller = installer;
2376     }
2377 
start()2378     private void start() {
2379         removeAllProcessGroups();
2380 
2381         mBatteryStatsService.publish();
2382         mAppOpsService.publish();
2383         Slog.d("AppOps", "AppOpsService published");
2384         LocalServices.addService(ActivityManagerInternal.class, mInternal);
2385         LocalManagerRegistry.addManager(ActivityManagerLocal.class,
2386                 (ActivityManagerLocal) mInternal);
2387         mActivityTaskManager.onActivityManagerInternalAdded();
2388         mPendingIntentController.onActivityManagerInternalAdded();
2389         mAppProfiler.onActivityManagerInternalAdded();
2390     }
2391 
initPowerManagement()2392     public void initPowerManagement() {
2393         mActivityTaskManager.onInitPowerManagement();
2394         mBatteryStatsService.initPowerManagement();
2395         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2396     }
2397 
getBackgroundLaunchBroadcasts()2398     private ArraySet<String> getBackgroundLaunchBroadcasts() {
2399         if (mBackgroundLaunchBroadcasts == null) {
2400             mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2401         }
2402         return mBackgroundLaunchBroadcasts;
2403     }
2404 
2405     /**
2406      * Ensures that the given package name has an explicit set of allowed associations.
2407      * If it does not, give it an empty set.
2408      */
requireAllowedAssociationsLocked(String packageName)2409     void requireAllowedAssociationsLocked(String packageName) {
2410         ensureAllowedAssociations();
2411         if (mAllowedAssociations.get(packageName) == null) {
2412             mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName,
2413                     new ArraySet<>(), /* isDebuggable = */ false));
2414         }
2415     }
2416 
2417     /**
2418      * Returns true if the package {@code pkg1} running under user handle {@code uid1} is
2419      * allowed association with the package {@code pkg2} running under user handle {@code uid2}.
2420      * <p> If either of the packages are running as  part of the core system, then the
2421      * association is implicitly allowed.
2422      */
validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2423     boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) {
2424         ensureAllowedAssociations();
2425         // Interactions with the system uid are always allowed, since that is the core system
2426         // that everyone needs to be able to interact with. Also allow reflexive associations
2427         // within the same uid.
2428         if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID
2429                 || UserHandle.getAppId(uid2) == SYSTEM_UID) {
2430             return true;
2431         }
2432 
2433         // Check for association on both source and target packages.
2434         PackageAssociationInfo pai = mAllowedAssociations.get(pkg1);
2435         if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) {
2436             return false;
2437         }
2438         pai = mAllowedAssociations.get(pkg2);
2439         if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) {
2440             return false;
2441         }
2442         // If no explicit associations are provided in the manifest, then assume the app is
2443         // allowed associations with any package.
2444         return true;
2445     }
2446 
2447     /** Sets up allowed associations for system prebuilt packages from system config (if needed). */
ensureAllowedAssociations()2448     private void ensureAllowedAssociations() {
2449         if (mAllowedAssociations == null) {
2450             ArrayMap<String, ArraySet<String>> allowedAssociations =
2451                     SystemConfig.getInstance().getAllowedAssociations();
2452             mAllowedAssociations = new ArrayMap<>(allowedAssociations.size());
2453             PackageManagerInternal pm = getPackageManagerInternal();
2454             for (int i = 0; i < allowedAssociations.size(); i++) {
2455                 final String pkg = allowedAssociations.keyAt(i);
2456                 final ArraySet<String> asc = allowedAssociations.valueAt(i);
2457 
2458                 // Query latest debuggable flag from package-manager.
2459                 boolean isDebuggable = false;
2460                 try {
2461                     ApplicationInfo ai = AppGlobals.getPackageManager()
2462                             .getApplicationInfo(pkg, MATCH_ALL, 0);
2463                     if (ai != null) {
2464                         isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2465                     }
2466                 } catch (RemoteException e) {
2467                     /* ignore */
2468                 }
2469                 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable));
2470             }
2471         }
2472     }
2473 
2474     /** Updates allowed associations for app info (specifically, based on debuggability).  */
updateAssociationForApp(ApplicationInfo appInfo)2475     private void updateAssociationForApp(ApplicationInfo appInfo) {
2476         ensureAllowedAssociations();
2477         PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName);
2478         if (pai != null) {
2479             pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
2480         }
2481     }
2482 
2483     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)2484     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2485             throws RemoteException {
2486         if (code == SYSPROPS_TRANSACTION) {
2487             // We need to tell all apps about the system property change.
2488             ArrayList<IBinder> procs = new ArrayList<IBinder>();
2489             synchronized (mProcLock) {
2490                 final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
2491                         mProcessList.getProcessNamesLOSP().getMap();
2492                 final int numOfNames = pmap.size();
2493                 for (int ip = 0; ip < numOfNames; ip++) {
2494                     SparseArray<ProcessRecord> apps = pmap.valueAt(ip);
2495                     final int numOfApps = apps.size();
2496                     for (int ia = 0; ia < numOfApps; ia++) {
2497                         ProcessRecord app = apps.valueAt(ia);
2498                         final IApplicationThread thread = app.getThread();
2499                         if (thread != null) {
2500                             procs.add(thread.asBinder());
2501                         }
2502                     }
2503                 }
2504             }
2505 
2506             int N = procs.size();
2507             for (int i=0; i<N; i++) {
2508                 Parcel data2 = Parcel.obtain();
2509                 try {
2510                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2511                             Binder.FLAG_ONEWAY);
2512                 } catch (RemoteException e) {
2513                 }
2514                 data2.recycle();
2515             }
2516         }
2517         try {
2518             return super.onTransact(code, data, reply, flags);
2519         } catch (RuntimeException e) {
2520             // The activity manager only throws certain exceptions intentionally, so let's
2521             // log all others.
2522             if (!(e instanceof SecurityException
2523                     || e instanceof IllegalArgumentException
2524                     || e instanceof IllegalStateException)) {
2525                 Slog.wtf(TAG, "Activity Manager Crash."
2526                         + " UID:" + Binder.getCallingUid()
2527                         + " PID:" + Binder.getCallingPid()
2528                         + " TRANS:" + code, e);
2529             }
2530             throw e;
2531         }
2532     }
2533 
updateCpuStats()2534     void updateCpuStats() {
2535         mAppProfiler.updateCpuStats();
2536     }
2537 
updateCpuStatsNow()2538     void updateCpuStatsNow() {
2539         mAppProfiler.updateCpuStatsNow();
2540     }
2541 
2542     @Override
batteryNeedsCpuUpdate()2543     public void batteryNeedsCpuUpdate() {
2544         updateCpuStatsNow();
2545     }
2546 
2547     @Override
batteryPowerChanged(boolean onBattery)2548     public void batteryPowerChanged(boolean onBattery) {
2549         // When plugging in, update the CPU stats first before changing
2550         // the plug state.
2551         updateCpuStatsNow();
2552         synchronized (mProcLock) {
2553             mOnBattery = DEBUG_POWER ? true : onBattery;
2554             mOomAdjProfiler.batteryPowerChanged(onBattery);
2555         }
2556     }
2557 
2558     @Override
batteryStatsReset()2559     public void batteryStatsReset() {
2560         mOomAdjProfiler.reset();
2561     }
2562 
2563     @Override
batterySendBroadcast(Intent intent)2564     public void batterySendBroadcast(Intent intent) {
2565         synchronized (this) {
2566             broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null, null,
2567                     OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
2568                     Binder.getCallingPid(), UserHandle.USER_ALL);
2569         }
2570     }
2571 
2572     /**
2573      * Initialize the application bind args. These are passed to each
2574      * process when the bindApplication() IPC is sent to the process. They're
2575      * lazily setup to make sure the services are running when they're asked for.
2576      */
getCommonServicesLocked(boolean isolated)2577     private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
2578         // Isolated processes won't get this optimization, so that we don't
2579         // violate the rules about which services they have access to.
2580         if (isolated) {
2581             if (mIsolatedAppBindArgs == null) {
2582                 mIsolatedAppBindArgs = new ArrayMap<>(1);
2583                 addServiceToMap(mIsolatedAppBindArgs, "package");
2584                 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr");
2585             }
2586             return mIsolatedAppBindArgs;
2587         }
2588 
2589         if (mAppBindArgs == null) {
2590             mAppBindArgs = new ArrayMap<>();
2591 
2592             // Add common services.
2593             // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too.
2594             // Enable the check in ApplicationThread.bindApplication() to make sure.
2595             addServiceToMap(mAppBindArgs, "package");
2596             addServiceToMap(mAppBindArgs, "permissionmgr");
2597             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
2598             addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE);
2599             addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE);
2600             addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE);
2601             addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE);
2602             addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE);
2603             addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
2604             addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
2605             addServiceToMap(mAppBindArgs, "graphicsstats");
2606             addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
2607             addServiceToMap(mAppBindArgs, "content");
2608             addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
2609             addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
2610             addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
2611             addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
2612             addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
2613             addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
2614             addServiceToMap(mAppBindArgs, "mount");
2615             addServiceToMap(mAppBindArgs, Context.PLATFORM_COMPAT_SERVICE);
2616         }
2617         return mAppBindArgs;
2618     }
2619 
addServiceToMap(ArrayMap<String, IBinder> map, String name)2620     private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) {
2621         final IBinder service = ServiceManager.getService(name);
2622         if (service != null) {
2623             map.put(name, service);
2624             if (false) {
2625                 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache.");
2626             }
2627         }
2628     }
2629 
2630     @Override
setFocusedRootTask(int taskId)2631     public void setFocusedRootTask(int taskId) {
2632         mActivityTaskManager.setFocusedRootTask(taskId);
2633     }
2634 
2635     /** Sets the task stack listener that gets callbacks when a task stack changes. */
2636     @Override
registerTaskStackListener(ITaskStackListener listener)2637     public void registerTaskStackListener(ITaskStackListener listener) {
2638         mActivityTaskManager.registerTaskStackListener(listener);
2639     }
2640 
2641     /**
2642      * Unregister a task stack listener so that it stops receiving callbacks.
2643      */
2644     @Override
unregisterTaskStackListener(ITaskStackListener listener)2645     public void unregisterTaskStackListener(ITaskStackListener listener) {
2646         mActivityTaskManager.unregisterTaskStackListener(listener);
2647     }
2648 
2649     @GuardedBy("this")
updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2650     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2651             ProcessRecord client) {
2652         mProcessList.updateLruProcessLocked(app, activityChange, client);
2653     }
2654 
2655     @GuardedBy("this")
removeLruProcessLocked(ProcessRecord app)2656     final void removeLruProcessLocked(ProcessRecord app) {
2657         mProcessList.removeLruProcessLocked(app);
2658     }
2659 
2660     @GuardedBy("this")
getProcessRecordLocked(String processName, int uid)2661     final ProcessRecord getProcessRecordLocked(String processName, int uid) {
2662         return mProcessList.getProcessRecordLocked(processName, uid);
2663     }
2664 
2665     @GuardedBy(anyOf = {"this", "mProcLock"})
getProcessNamesLOSP()2666     final ProcessMap<ProcessRecord> getProcessNamesLOSP() {
2667         return mProcessList.getProcessNamesLOSP();
2668     }
2669 
notifyPackageUse(String packageName, int reason)2670     void notifyPackageUse(String packageName, int reason) {
2671         getPackageManagerInternal().notifyPackageUse(packageName, reason);
2672     }
2673 
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2674     boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
2675             String processName, String abiOverride, int uid, Runnable crashHandler) {
2676         synchronized(this) {
2677             ApplicationInfo info = new ApplicationInfo();
2678             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
2679             // For isolated processes, the former contains the parent's uid and the latter the
2680             // actual uid of the isolated process.
2681             // In the special case introduced by this method (which is, starting an isolated
2682             // process directly from the SystemServer without an actual parent app process) the
2683             // closest thing to a parent's uid is SYSTEM_UID.
2684             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
2685             // the |isolated| logic in the ProcessRecord constructor.
2686             info.uid = SYSTEM_UID;
2687             info.processName = processName;
2688             info.className = entryPoint;
2689             info.packageName = "android";
2690             info.seInfoUser = SELinuxUtil.COMPLETE_STR;
2691             info.targetSdkVersion = Build.VERSION.SDK_INT;
2692             ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */,
2693                     false /* knownToBeDead */, 0 /* intentFlags */,
2694                     sNullHostingRecord  /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY,
2695                     true /* allowWhileBooting */, true /* isolated */,
2696                     uid, abiOverride, entryPoint, entryPointArgs, crashHandler);
2697             return proc != null;
2698         }
2699     }
2700 
2701     @GuardedBy("this")
startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated)2702     final ProcessRecord startProcessLocked(String processName,
2703             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2704             HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
2705             boolean isolated) {
2706         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
2707                 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
2708                 null /* ABI override */, null /* entryPoint */,
2709                 null /* entryPointArgs */, null /* crashHandler */);
2710     }
2711 
isAllowedWhileBooting(ApplicationInfo ai)2712     boolean isAllowedWhileBooting(ApplicationInfo ai) {
2713         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2714     }
2715 
2716     /**
2717      * Update battery stats on the activity' usage.
2718      * @param activity
2719      * @param uid
2720      * @param userId
2721      * @param resumed
2722      */
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)2723     void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) {
2724         if (DEBUG_SWITCH) {
2725             Slog.d(TAG_SWITCH,
2726                     "updateBatteryStats: comp=" + activity + "res=" + resumed);
2727         }
2728         mBatteryStatsService.updateBatteryStatsOnActivityUsage(activity.getPackageName(),
2729                 activity.getShortClassName(), uid, userId, resumed);
2730     }
2731 
2732     /**
2733      * Update UsageStas on the activity's usage.
2734      * @param activity
2735      * @param userId
2736      * @param event
2737      * @param appToken ActivityRecord's appToken.
2738      * @param taskRoot Task's root
2739      */
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)2740     public void updateActivityUsageStats(ComponentName activity, int userId, int event,
2741             IBinder appToken, ComponentName taskRoot) {
2742         if (DEBUG_SWITCH) {
2743             Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp="
2744                     + activity + " hash=" + appToken.hashCode() + " event=" + event);
2745         }
2746         if (mUsageStatsService != null) {
2747             mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(), taskRoot);
2748             if (event == Event.ACTIVITY_RESUMED) {
2749                 // Report component usage as an activity is an app component
2750                 mUsageStatsService.reportEvent(
2751                         activity.getPackageName(), userId, Event.APP_COMPONENT_USED);
2752             }
2753         }
2754         ContentCaptureManagerInternal contentCaptureService = mContentCaptureService;
2755         if (contentCaptureService != null && (event == Event.ACTIVITY_PAUSED
2756                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED
2757                 || event == Event.ACTIVITY_DESTROYED)) {
2758             contentCaptureService.notifyActivityEvent(userId, activity, event);
2759         }
2760         // TODO(b/201234353): Move the logic to client side.
2761         if (mVoiceInteractionManagerProvider != null && (event == Event.ACTIVITY_PAUSED
2762                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED)) {
2763             mVoiceInteractionManagerProvider.notifyActivityEventChanged();
2764         }
2765     }
2766 
2767     /**
2768      * Update UsageStats on this package's usage.
2769      * @param packageName
2770      * @param userId
2771      * @param event
2772      */
updateActivityUsageStats(String packageName, int userId, int event)2773     public void updateActivityUsageStats(String packageName, int userId, int event) {
2774         if (DEBUG_SWITCH) {
2775             Slog.d(TAG_SWITCH, "updateActivityUsageStats: package="
2776                     + packageName + " event=" + event);
2777         }
2778         if (mUsageStatsService != null) {
2779             mUsageStatsService.reportEvent(packageName, userId, event);
2780         }
2781     }
2782 
2783     /**
2784      * Update Usages on this foreground service's usage.
2785      * @param service
2786      * @param userId
2787      * @param started
2788      */
updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)2789     void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) {
2790         if (DEBUG_SWITCH) {
2791             Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp="
2792                     + service + " started=" + started);
2793         }
2794         if (mUsageStatsService != null) {
2795             mUsageStatsService.reportEvent(service, userId,
2796                     started ? UsageEvents.Event.FOREGROUND_SERVICE_START
2797                             : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null);
2798         }
2799     }
2800 
compatibilityInfoForPackage(ApplicationInfo ai)2801     CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
2802         return mAtmInternal.compatibilityInfoForPackage(ai);
2803     }
2804 
enforceNotIsolatedCaller(String caller)2805     /* package */ void enforceNotIsolatedCaller(String caller) {
2806         if (UserHandle.isIsolated(Binder.getCallingUid())) {
2807             throw new SecurityException("Isolated process not allowed to call " + caller);
2808         }
2809     }
2810 
2811     @Override
setPackageScreenCompatMode(String packageName, int mode)2812     public void setPackageScreenCompatMode(String packageName, int mode) {
2813         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
2814     }
2815 
hasUsageStatsPermission(String callingPackage)2816     private boolean hasUsageStatsPermission(String callingPackage) {
2817         final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS,
2818                 Binder.getCallingUid(), callingPackage, null, false, "", false).getOpMode();
2819         if (mode == AppOpsManager.MODE_DEFAULT) {
2820             return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
2821                     == PackageManager.PERMISSION_GRANTED;
2822         }
2823         return mode == AppOpsManager.MODE_ALLOWED;
2824     }
2825 
2826     @Override
getPackageProcessState(String packageName, String callingPackage)2827     public int getPackageProcessState(String packageName, String callingPackage) {
2828         if (!hasUsageStatsPermission(callingPackage)) {
2829             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
2830                     "getPackageProcessState");
2831         }
2832 
2833         final int[] procState = {PROCESS_STATE_NONEXISTENT};
2834         synchronized (mProcLock) {
2835             mProcessList.forEachLruProcessesLOSP(false, proc -> {
2836                 if (procState[0] > proc.mState.getSetProcState()) {
2837                     if (proc.getPkgList().containsKey(packageName) || (proc.getPkgDeps() != null
2838                                 && proc.getPkgDeps().contains(packageName))) {
2839                         procState[0] = proc.mState.getSetProcState();
2840                     }
2841                 }
2842             });
2843         }
2844         return procState[0];
2845     }
2846 
2847     @Override
setProcessMemoryTrimLevel(String process, int userId, int level)2848     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
2849             throws RemoteException {
2850         if (!isCallerShell()) {
2851             throw new SecurityException("Only shell can call it");
2852         }
2853         synchronized (this) {
2854             final ProcessRecord app = findProcessLOSP(process, userId, "setProcessMemoryTrimLevel");
2855             if (app == null) {
2856                 throw new IllegalArgumentException("Unknown process: " + process);
2857             }
2858             final IApplicationThread thread = app.getThread();
2859             if (thread == null) {
2860                 throw new IllegalArgumentException("Process has no app thread");
2861             }
2862             if (app.mProfile.getTrimMemoryLevel() >= level) {
2863                 throw new IllegalArgumentException(
2864                         "Unable to set a higher trim level than current level");
2865             }
2866             if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
2867                     app.mState.getCurProcState() > PROCESS_STATE_IMPORTANT_FOREGROUND)) {
2868                 throw new IllegalArgumentException("Unable to set a background trim level "
2869                     + "on a foreground process");
2870             }
2871             thread.scheduleTrimMemory(level);
2872             synchronized (mProcLock) {
2873                 app.mProfile.setTrimMemoryLevel(level);
2874             }
2875             return true;
2876         }
2877     }
2878 
dispatchOomAdjObserver(String msg)2879     void dispatchOomAdjObserver(String msg) {
2880         OomAdjObserver observer;
2881         synchronized (mOomAdjObserverLock) {
2882             observer = mCurOomAdjObserver;
2883         }
2884 
2885         if (observer != null) {
2886             observer.onOomAdjMessage(msg);
2887         }
2888     }
2889 
setOomAdjObserver(int uid, OomAdjObserver observer)2890     void setOomAdjObserver(int uid, OomAdjObserver observer) {
2891         synchronized (mOomAdjObserverLock) {
2892             mCurOomAdjUid = uid;
2893             mCurOomAdjObserver = observer;
2894         }
2895     }
2896 
clearOomAdjObserver()2897     void clearOomAdjObserver() {
2898         synchronized (mOomAdjObserverLock) {
2899             mCurOomAdjUid = -1;
2900             mCurOomAdjObserver = null;
2901         }
2902     }
2903 
reportUidInfoMessageLocked(String tag, String msg, int uid)2904     void reportUidInfoMessageLocked(String tag, String msg, int uid) {
2905         Slog.i(TAG, msg);
2906         synchronized (mOomAdjObserverLock) {
2907             if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) {
2908                 mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
2909             }
2910         }
2911     }
2912 
2913     /**
2914      * @deprecated use {@link #startActivityWithFeature} instead
2915      */
2916     @Deprecated
2917     @Override
startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)2918     public int startActivity(IApplicationThread caller, String callingPackage,
2919             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
2920             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
2921         return mActivityTaskManager.startActivity(caller, callingPackage, null, intent,
2922                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
2923     }
2924 
2925     @Override
startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)2926     public int startActivityWithFeature(IApplicationThread caller, String callingPackage,
2927             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
2928             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
2929             Bundle bOptions) {
2930         return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent,
2931                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
2932     }
2933 
2934     /**
2935      * @deprecated use {@link #startActivityAsUserWithFeature} instead
2936      */
2937     @Deprecated
2938     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)2939     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
2940             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
2941             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
2942         return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType,
2943                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId);
2944     }
2945 
2946     @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)2947     public final int startActivityAsUserWithFeature(IApplicationThread caller,
2948             String callingPackage, String callingFeatureId, Intent intent, String resolvedType,
2949             IBinder resultTo, String resultWho, int requestCode, int startFlags,
2950             ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
2951         return mActivityTaskManager.startActivityAsUser(caller, callingPackage,
2952                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
2953                     startFlags, profilerInfo, bOptions, userId);
2954     }
2955 
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)2956     WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
2957             @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
2958             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
2959             Bundle bOptions, int userId) {
2960             return mActivityTaskManager.startActivityAndWait(caller, callingPackage,
2961                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
2962                     startFlags, profilerInfo, bOptions, userId);
2963     }
2964 
2965     @Override
startActivityFromRecents(int taskId, Bundle bOptions)2966     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
2967         return mActivityTaskManager.startActivityFromRecents(taskId, bOptions);
2968     }
2969 
2970     /**
2971      * This is the internal entry point for handling Activity.finish().
2972      *
2973      * @param token The Binder token referencing the Activity we want to finish.
2974      * @param resultCode Result code, if any, from this Activity.
2975      * @param resultData Result data (Intent), if any, from this Activity.
2976      * @param finishTask Whether to finish the task associated with this Activity.
2977      *
2978      * @return Returns true if the activity successfully finished, or false if it is still running.
2979      */
2980     @Override
finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)2981     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
2982             int finishTask) {
2983         return ActivityClient.getInstance().finishActivity(token, resultCode, resultData,
2984                 finishTask);
2985     }
2986 
2987     @Override
setRequestedOrientation(IBinder token, int requestedOrientation)2988     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
2989         ActivityClient.getInstance().setRequestedOrientation(token, requestedOrientation);
2990     }
2991 
2992     @Override
finishHeavyWeightApp()2993     public final void finishHeavyWeightApp() {
2994         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2995                 != PackageManager.PERMISSION_GRANTED) {
2996             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2997                     + Binder.getCallingPid()
2998                     + ", uid=" + Binder.getCallingUid()
2999                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3000             Slog.w(TAG, msg);
3001             throw new SecurityException(msg);
3002         }
3003         mAtmInternal.finishHeavyWeightApp();
3004     }
3005 
3006     @Override
crashApplicationWithType(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId)3007     public void crashApplicationWithType(int uid, int initialPid, String packageName, int userId,
3008             String message, boolean force, int exceptionTypeId) {
3009         crashApplicationWithTypeWithExtras(uid, initialPid, packageName, userId, message,
3010                 force, exceptionTypeId, null);
3011     }
3012 
3013     @Override
crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName, int userId, String message, boolean force, int exceptionTypeId, @Nullable Bundle extras)3014     public void crashApplicationWithTypeWithExtras(int uid, int initialPid, String packageName,
3015             int userId, String message, boolean force, int exceptionTypeId,
3016             @Nullable Bundle extras) {
3017         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3018                 != PackageManager.PERMISSION_GRANTED) {
3019             String msg = "Permission Denial: crashApplication() from pid="
3020                     + Binder.getCallingPid()
3021                     + ", uid=" + Binder.getCallingUid()
3022                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3023             Slog.w(TAG, msg);
3024             throw new SecurityException(msg);
3025         }
3026 
3027         synchronized(this) {
3028             mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId,
3029                     message, force, exceptionTypeId, extras);
3030         }
3031     }
3032 
3033     /**
3034      * Main function for removing an existing process from the activity manager
3035      * as a result of that process going away.  Clears out all connections
3036      * to the process.
3037      */
3038     @GuardedBy("this")
handleAppDiedLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, boolean fromBinderDied)3039     final void handleAppDiedLocked(ProcessRecord app, int pid,
3040             boolean restarting, boolean allowRestart, boolean fromBinderDied) {
3041         boolean kept = cleanUpApplicationRecordLocked(app, pid, restarting, allowRestart, -1,
3042                 false /*replacingPid*/, fromBinderDied);
3043         if (!kept && !restarting) {
3044             removeLruProcessLocked(app);
3045             if (pid > 0) {
3046                 ProcessList.remove(pid);
3047             }
3048         }
3049 
3050         mAppProfiler.onAppDiedLocked(app);
3051 
3052         mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
3053             Slog.w(TAG, "Crash of app " + app.processName
3054                     + " running instrumentation " + app.getActiveInstrumentation().mClass);
3055             Bundle info = new Bundle();
3056             info.putString("shortMsg", "Process crashed.");
3057             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3058         });
3059     }
3060 
3061     @GuardedBy(anyOf = {"this", "mProcLock"})
getRecordForAppLOSP(IApplicationThread thread)3062     ProcessRecord getRecordForAppLOSP(IApplicationThread thread) {
3063         if (thread == null) {
3064             return null;
3065         }
3066 
3067         ProcessRecord record = mProcessList.getLRURecordForAppLOSP(thread);
3068         if (record != null) return record;
3069 
3070         // Validation: if it isn't in the LRU list, it shouldn't exist, but let's
3071         // double-check that.
3072         final IBinder threadBinder = thread.asBinder();
3073         final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
3074                 mProcessList.getProcessNamesLOSP().getMap();
3075         for (int i = pmap.size()-1; i >= 0; i--) {
3076             final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
3077             for (int j = procs.size()-1; j >= 0; j--) {
3078                 final ProcessRecord proc = procs.valueAt(j);
3079                 final IApplicationThread procThread = proc.getThread();
3080                 if (procThread != null && procThread.asBinder() == threadBinder) {
3081                     Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
3082                             + proc);
3083                     return proc;
3084                 }
3085             }
3086         }
3087 
3088         return null;
3089     }
3090 
3091     @GuardedBy("this")
appDiedLocked(ProcessRecord app, String reason)3092     final void appDiedLocked(ProcessRecord app, String reason) {
3093         appDiedLocked(app, app.getPid(), app.getThread(), false, reason);
3094     }
3095 
3096     @GuardedBy("this")
appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3097     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
3098             boolean fromBinderDied, String reason) {
3099         // First check if this ProcessRecord is actually active for the pid.
3100         final ProcessRecord curProc;
3101         synchronized (mPidsSelfLocked) {
3102             curProc = mPidsSelfLocked.get(pid);
3103         }
3104         if (curProc != app) {
3105             if (!fromBinderDied || !mProcessList.handleDyingAppDeathLocked(app, pid)) {
3106                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
3107             }
3108             return;
3109         }
3110 
3111         mBatteryStatsService.noteProcessDied(app.info.uid, pid);
3112 
3113         if (!app.isKilled()) {
3114             if (!fromBinderDied) {
3115                 killProcessQuiet(pid);
3116                 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER,
3117                         ApplicationExitInfo.SUBREASON_UNKNOWN, reason);
3118             }
3119             ProcessList.killProcessGroup(app.uid, pid);
3120             synchronized (mProcLock) {
3121                 app.setKilled(true);
3122             }
3123         }
3124 
3125         // Clean up already done if the process has been re-started.
3126         IApplicationThread appThread;
3127         final int setAdj = app.mState.getSetAdj();
3128         final int setProcState = app.mState.getSetProcState();
3129         if (app.getPid() == pid && (appThread = app.getThread()) != null
3130                 && appThread.asBinder() == thread.asBinder()) {
3131             boolean doLowMem = app.getActiveInstrumentation() == null;
3132             boolean doOomAdj = doLowMem;
3133             if (!app.isKilledByAm()) {
3134                 reportUidInfoMessageLocked(TAG,
3135                         "Process " + app.processName + " (pid " + pid + ") has died: "
3136                         + ProcessList.makeOomAdjString(setAdj, true) + " "
3137                         + ProcessList.makeProcStateString(setProcState), app.info.uid);
3138                 mAppProfiler.setAllowLowerMemLevelLocked(true);
3139             } else {
3140                 // Note that we always want to do oom adj to update our state with the
3141                 // new number of procs.
3142                 mAppProfiler.setAllowLowerMemLevelLocked(false);
3143                 doLowMem = false;
3144             }
3145             EventLogTags.writeAmProcDied(app.userId, pid, app.processName, setAdj, setProcState);
3146             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3147                 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
3148             handleAppDiedLocked(app, pid, false, true, fromBinderDied);
3149 
3150             if (doOomAdj) {
3151                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
3152             }
3153             if (doLowMem) {
3154                 mAppProfiler.doLowMemReportIfNeededLocked(app);
3155             }
3156         } else if (app.getPid() != pid) {
3157             // A new process has already been started.
3158             reportUidInfoMessageLocked(TAG,
3159                     "Process " + app.processName + " (pid " + pid
3160                             + ") has died and restarted (pid " + app.getPid() + ").", app.info.uid);
3161 
3162             EventLogTags.writeAmProcDied(app.userId, app.getPid(), app.processName,
3163                     setAdj, setProcState);
3164         } else if (DEBUG_PROCESSES) {
3165             Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
3166                     + thread.asBinder());
3167         }
3168 
3169         // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal
3170         // for pulling memory stats of other running processes when this process died.
3171         if (!hasMemcg()) {
3172             FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime());
3173         }
3174     }
3175 
3176     /**
3177      * If a stack trace dump file is configured, dump process stack traces.
3178      * @param firstPids of dalvik VM processes to dump stack traces for first
3179      * @param lastPids of dalvik VM processes to dump stack traces for last
3180      * @param nativePids optional list of native pids to dump stack crawls
3181      * @param logExceptionCreatingFile optional writer to which we log errors creating the file
3182      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile)3183     public static File dumpStackTraces(ArrayList<Integer> firstPids,
3184             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3185             ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile) {
3186         return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids,
3187                 logExceptionCreatingFile, null, null);
3188     }
3189 
3190     /**
3191      * If a stack trace dump file is configured, dump process stack traces.
3192      * @param firstPids of dalvik VM processes to dump stack traces for first
3193      * @param lastPids of dalvik VM processes to dump stack traces for last
3194      * @param nativePids optional list of native pids to dump stack crawls
3195      * @param logExceptionCreatingFile optional writer to which we log errors creating the file
3196      * @param subject optional line related to the error
3197      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, String subject)3198     public static File dumpStackTraces(ArrayList<Integer> firstPids,
3199             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3200             ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile,
3201             String subject) {
3202         return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids,
3203                 logExceptionCreatingFile, null, subject);
3204     }
3205 
3206     /**
3207      * @param firstPidOffsets Optional, when it's set, it receives the start/end offset
3208      *                        of the very first pid to be dumped.
3209      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, long[] firstPidOffsets, String subject)3210     /* package */ static File dumpStackTraces(ArrayList<Integer> firstPids,
3211             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3212             ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile,
3213             long[] firstPidOffsets, String subject) {
3214         ArrayList<Integer> extraPids = null;
3215 
3216         Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids);
3217 
3218         // Measure CPU usage as soon as we're called in order to get a realistic sampling
3219         // of the top users at the time of the request.
3220         if (processCpuTracker != null) {
3221             processCpuTracker.init();
3222             try {
3223                 Thread.sleep(200);
3224             } catch (InterruptedException ignored) {
3225             }
3226 
3227             processCpuTracker.update();
3228 
3229             // We'll take the stack crawls of just the top apps using CPU.
3230             final int N = processCpuTracker.countWorkingStats();
3231             extraPids = new ArrayList<>();
3232             for (int i = 0; i < N && extraPids.size() < 5; i++) {
3233                 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
3234                 if (lastPids.indexOfKey(stats.pid) >= 0) {
3235                     if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid);
3236 
3237                     extraPids.add(stats.pid);
3238                 } else {
3239                     Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: "
3240                             + stats.pid);
3241                 }
3242             }
3243         }
3244 
3245         final File tracesDir = new File(ANR_TRACE_DIR);
3246         // Each set of ANR traces is written to a separate file and dumpstate will process
3247         // all such files and add them to a captured bug report if they're recent enough.
3248         maybePruneOldTraces(tracesDir);
3249 
3250         // NOTE: We should consider creating the file in native code atomically once we've
3251         // gotten rid of the old scheme of dumping and lot of the code that deals with paths
3252         // can be removed.
3253         File tracesFile;
3254         try {
3255             tracesFile = createAnrDumpFile(tracesDir);
3256         } catch (IOException e) {
3257             Slog.w(TAG, "Exception creating ANR dump file:", e);
3258             if (logExceptionCreatingFile != null) {
3259                 logExceptionCreatingFile.append("----- Exception creating ANR dump file -----\n");
3260                 e.printStackTrace(new PrintWriter(logExceptionCreatingFile));
3261             }
3262             return null;
3263         }
3264 
3265         if (subject != null) {
3266             try (FileOutputStream fos = new FileOutputStream(tracesFile, true)) {
3267                 String header = "Subject: " + subject + "\n";
3268                 fos.write(header.getBytes(StandardCharsets.UTF_8));
3269             } catch (IOException e) {
3270                 Slog.w(TAG, "Exception writing subject to ANR dump file:", e);
3271             }
3272         }
3273 
3274         Pair<Long, Long> offsets = dumpStackTraces(
3275                 tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids);
3276         if (firstPidOffsets != null) {
3277             if (offsets == null) {
3278                 firstPidOffsets[0] = firstPidOffsets[1] = -1;
3279             } else {
3280                 firstPidOffsets[0] = offsets.first; // Start offset to the ANR trace file
3281                 firstPidOffsets[1] = offsets.second; // End offset to the ANR trace file
3282             }
3283         }
3284         return tracesFile;
3285     }
3286 
3287     @GuardedBy("ActivityManagerService.class")
3288     private static SimpleDateFormat sAnrFileDateFormat;
3289     static final String ANR_FILE_PREFIX = "anr_";
3290 
createAnrDumpFile(File tracesDir)3291     private static synchronized File createAnrDumpFile(File tracesDir) throws IOException {
3292         if (sAnrFileDateFormat == null) {
3293             sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
3294         }
3295 
3296         final String formattedDate = sAnrFileDateFormat.format(new Date());
3297         final File anrFile = new File(tracesDir, ANR_FILE_PREFIX + formattedDate);
3298 
3299         if (anrFile.createNewFile()) {
3300             FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw-------
3301             return anrFile;
3302         } else {
3303             throw new IOException("Unable to create ANR dump file: createNewFile failed");
3304         }
3305     }
3306 
3307     /**
3308      * Prune all trace files that are more than a day old.
3309      *
3310      * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a
3311      * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now
3312      * since it's the system_server that creates trace files for most ANRs.
3313      */
maybePruneOldTraces(File tracesDir)3314     private static void maybePruneOldTraces(File tracesDir) {
3315         final File[] files = tracesDir.listFiles();
3316         if (files == null) return;
3317 
3318         final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64);
3319         final long now = System.currentTimeMillis();
3320         Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
3321         for (int i = 0; i < files.length; ++i) {
3322             if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) {
3323                 if (!files[i].delete()) {
3324                     Slog.w(TAG, "Unable to prune stale trace file: " + files[i]);
3325                 }
3326             }
3327         }
3328     }
3329 
3330     /**
3331      * Dump java traces for process {@code pid} to the specified file. If java trace dumping
3332      * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies
3333      * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent
3334      * attempting to obtain native traces in the case of a failure. Returns the total time spent
3335      * capturing traces.
3336      */
dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)3337     private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) {
3338         final long timeStart = SystemClock.elapsedRealtime();
3339         boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName,
3340                 (int) (timeoutMs / 1000));
3341         if (javaSuccess) {
3342             // Check that something is in the file, actually. Try-catch should not be necessary,
3343             // but better safe than sorry.
3344             try {
3345                 long size = new File(fileName).length();
3346                 if (size < JAVA_DUMP_MINIMUM_SIZE) {
3347                     Slog.w(TAG, "Successfully created Java ANR file is empty!");
3348                     javaSuccess = false;
3349                 }
3350             } catch (Exception e) {
3351                 Slog.w(TAG, "Unable to get ANR file size", e);
3352                 javaSuccess = false;
3353             }
3354         }
3355         if (!javaSuccess) {
3356             Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump.");
3357             if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName,
3358                     (NATIVE_DUMP_TIMEOUT_MS / 1000))) {
3359                 Slog.w(TAG, "Native stack dump failed!");
3360             }
3361         }
3362 
3363         return SystemClock.elapsedRealtime() - timeStart;
3364     }
3365 
3366     /**
3367      * @return The start/end offset of the trace of the very first PID
3368      */
dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)3369     public static Pair<Long, Long> dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids,
3370             ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) {
3371 
3372         Slog.i(TAG, "Dumping to " + tracesFile);
3373 
3374         // We don't need any sort of inotify based monitoring when we're dumping traces via
3375         // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full
3376         // control of all writes to the file in question.
3377 
3378         // We must complete all stack dumps within 20 seconds.
3379         long remainingTime = 20 * 1000;
3380 
3381         // As applications are usually interested with the ANR stack traces, but we can't share with
3382         // them the stack traces other than their own stacks. So after the very first PID is
3383         // dumped, remember the current file size.
3384         long firstPidStart = -1;
3385         long firstPidEnd = -1;
3386 
3387         // First collect all of the stacks of the most important pids.
3388         if (firstPids != null) {
3389             int num = firstPids.size();
3390             for (int i = 0; i < num; i++) {
3391                 final int pid = firstPids.get(i);
3392                 // We don't copy ANR traces from the system_server intentionally.
3393                 final boolean firstPid = i == 0 && MY_PID != pid;
3394                 File tf = null;
3395                 if (firstPid) {
3396                     tf = new File(tracesFile);
3397                     firstPidStart = tf.exists() ? tf.length() : 0;
3398                 }
3399 
3400                 Slog.i(TAG, "Collecting stacks for pid " + pid);
3401                 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile,
3402                                                                 remainingTime);
3403 
3404                 remainingTime -= timeTaken;
3405                 if (remainingTime <= 0) {
3406                     Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + pid
3407                             + "); deadline exceeded.");
3408                     return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
3409                 }
3410 
3411                 if (firstPid) {
3412                     firstPidEnd = tf.length();
3413                 }
3414                 if (DEBUG_ANR) {
3415                     Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms");
3416                 }
3417             }
3418         }
3419 
3420         // Next collect the stacks of the native pids
3421         if (nativePids != null) {
3422             for (int pid : nativePids) {
3423                 Slog.i(TAG, "Collecting stacks for native pid " + pid);
3424                 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime);
3425 
3426                 final long start = SystemClock.elapsedRealtime();
3427                 Debug.dumpNativeBacktraceToFileTimeout(
3428                         pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000));
3429                 final long timeTaken = SystemClock.elapsedRealtime() - start;
3430 
3431                 remainingTime -= timeTaken;
3432                 if (remainingTime <= 0) {
3433                     Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid +
3434                         "); deadline exceeded.");
3435                     return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
3436                 }
3437 
3438                 if (DEBUG_ANR) {
3439                     Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms");
3440                 }
3441             }
3442         }
3443 
3444         // Lastly, dump stacks for all extra PIDs from the CPU tracker.
3445         if (extraPids != null) {
3446             for (int pid : extraPids) {
3447                 Slog.i(TAG, "Collecting stacks for extra pid " + pid);
3448 
3449                 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime);
3450 
3451                 remainingTime -= timeTaken;
3452                 if (remainingTime <= 0) {
3453                     Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid +
3454                             "); deadline exceeded.");
3455                     return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
3456                 }
3457 
3458                 if (DEBUG_ANR) {
3459                     Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms");
3460                 }
3461             }
3462         }
3463         Slog.i(TAG, "Done dumping");
3464         return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
3465     }
3466 
3467     @Override
clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)3468     public boolean clearApplicationUserData(final String packageName, boolean keepState,
3469             final IPackageDataObserver observer, int userId) {
3470         enforceNotIsolatedCaller("clearApplicationUserData");
3471         int uid = Binder.getCallingUid();
3472         int pid = Binder.getCallingPid();
3473         final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false,
3474                 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
3475 
3476         final ApplicationInfo appInfo;
3477         final boolean isInstantApp;
3478 
3479         final long callingId = Binder.clearCallingIdentity();
3480         try {
3481             IPackageManager pm = AppGlobals.getPackageManager();
3482             // Instant packages are not protected
3483             if (getPackageManagerInternal().isPackageDataProtected(
3484                     resolvedUserId, packageName)) {
3485                 throw new SecurityException(
3486                         "Cannot clear data for a protected package: " + packageName);
3487             }
3488 
3489             ApplicationInfo applicationInfo = null;
3490             try {
3491                 applicationInfo = pm.getApplicationInfo(packageName,
3492                         MATCH_UNINSTALLED_PACKAGES, resolvedUserId);
3493             } catch (RemoteException e) {
3494                 /* ignore */
3495             }
3496             appInfo = applicationInfo;
3497 
3498             final boolean clearingOwnUidData = appInfo != null && appInfo.uid == uid;
3499 
3500             if (!clearingOwnUidData && checkComponentPermission(permission.CLEAR_APP_USER_DATA,
3501                         pid, uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
3502                 throw new SecurityException("PID " + pid + " does not have permission "
3503                         + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
3504                         + " of package " + packageName);
3505             }
3506 
3507             final boolean hasInstantMetadata = getPackageManagerInternal()
3508                     .hasInstantApplicationMetadata(packageName, resolvedUserId);
3509             final boolean isUninstalledAppWithoutInstantMetadata =
3510                     (appInfo == null && !hasInstantMetadata);
3511             isInstantApp = (appInfo != null && appInfo.isInstantApp())
3512                     || hasInstantMetadata;
3513             final boolean canAccessInstantApps = checkComponentPermission(
3514                     permission.ACCESS_INSTANT_APPS, pid, uid, -1, true)
3515                     == PackageManager.PERMISSION_GRANTED;
3516 
3517             if (isUninstalledAppWithoutInstantMetadata || (isInstantApp
3518                         && !canAccessInstantApps)) {
3519                 Slog.w(TAG, "Invalid packageName: " + packageName);
3520                 if (observer != null) {
3521                     try {
3522                         observer.onRemoveCompleted(packageName, false);
3523                     } catch (RemoteException e) {
3524                         Slog.i(TAG, "Observer no longer exists.");
3525                     }
3526                 }
3527                 return false;
3528             }
3529 
3530             synchronized (this) {
3531                 if (appInfo != null) {
3532                     forceStopPackageLocked(packageName, appInfo.uid, "clear data");
3533                     mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId);
3534                 }
3535             }
3536 
3537             final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
3538                 @Override
3539                 public void onRemoveCompleted(String packageName, boolean succeeded)
3540                         throws RemoteException {
3541                     if (appInfo != null) {
3542                         synchronized (ActivityManagerService.this) {
3543                             finishForceStopPackageLocked(packageName, appInfo.uid);
3544                         }
3545                     }
3546                     final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3547                             Uri.fromParts("package", packageName, null));
3548                     intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
3549                     intent.putExtra(Intent.EXTRA_UID, (appInfo != null) ? appInfo.uid : -1);
3550                     intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId);
3551                     if (isInstantApp) {
3552                         intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
3553                         broadcastIntentInPackage("android", null, SYSTEM_UID, uid, pid, intent,
3554                                 null, null, 0, null, null, permission.ACCESS_INSTANT_APPS, null,
3555                                 false, false, resolvedUserId, false, null);
3556                     } else {
3557                         broadcastIntentInPackage("android", null, SYSTEM_UID, uid, pid, intent,
3558                                 null, null, 0, null, null, null, null, false, false, resolvedUserId,
3559                                 false, null);
3560                     }
3561 
3562                     if (observer != null) {
3563                         observer.onRemoveCompleted(packageName, succeeded);
3564                     }
3565                 }
3566             };
3567 
3568             try {
3569                 // Clear application user data
3570                 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId);
3571 
3572                 if (appInfo != null) {
3573                     // Restore already established notification state and permission grants,
3574                     // so it told us to keep those intact -- it's about to emplace app data
3575                     // that is appropriate for those bits of system state.
3576                     if (!keepState) {
3577                         // Remove all permissions granted from/to this package
3578                         mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId,
3579                                 true, false);
3580 
3581                         // Reset notification state
3582                         INotificationManager inm = NotificationManager.getService();
3583                         inm.clearData(packageName, appInfo.uid, uid == appInfo.uid);
3584                     }
3585 
3586                     // Clear its scheduled jobs
3587                     JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
3588                     // Clearing data is a user-initiated action.
3589                     js.cancelJobsForUid(appInfo.uid, JobParameters.STOP_REASON_USER,
3590                             JobParameters.INTERNAL_STOP_REASON_DATA_CLEARED, "clear data");
3591 
3592                     // Clear its pending alarms
3593                     AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class);
3594                     ami.removeAlarmsForUid(appInfo.uid);
3595                 }
3596             } catch (RemoteException e) {
3597             }
3598         } finally {
3599             Binder.restoreCallingIdentity(callingId);
3600         }
3601         return true;
3602     }
3603 
3604     @Override
killBackgroundProcesses(final String packageName, int userId)3605     public void killBackgroundProcesses(final String packageName, int userId) {
3606         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3607                 != PackageManager.PERMISSION_GRANTED &&
3608                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3609                         != PackageManager.PERMISSION_GRANTED) {
3610             String msg = "Permission Denial: killBackgroundProcesses() from pid="
3611                     + Binder.getCallingPid()
3612                     + ", uid=" + Binder.getCallingUid()
3613                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3614             Slog.w(TAG, msg);
3615             throw new SecurityException(msg);
3616         }
3617 
3618         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
3619                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
3620         final int[] userIds = mUserController.expandUserId(userId);
3621 
3622         final long callingId = Binder.clearCallingIdentity();
3623         try {
3624             IPackageManager pm = AppGlobals.getPackageManager();
3625             for (int targetUserId : userIds) {
3626                 int appId = -1;
3627                 try {
3628                     appId = UserHandle.getAppId(
3629                             pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
3630                                     targetUserId));
3631                 } catch (RemoteException e) {
3632                 }
3633                 if (appId == -1) {
3634                     Slog.w(TAG, "Invalid packageName: " + packageName);
3635                     return;
3636                 }
3637                 synchronized (this) {
3638                     synchronized (mProcLock) {
3639                         mProcessList.killPackageProcessesLSP(packageName, appId, targetUserId,
3640                                 ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED,
3641                                 ApplicationExitInfo.SUBREASON_UNKNOWN, "kill background");
3642                     }
3643                 }
3644             }
3645         } finally {
3646             Binder.restoreCallingIdentity(callingId);
3647         }
3648     }
3649 
3650     @Override
killAllBackgroundProcesses()3651     public void killAllBackgroundProcesses() {
3652         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3653                 != PackageManager.PERMISSION_GRANTED) {
3654             final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3655                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3656                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3657             Slog.w(TAG, msg);
3658             throw new SecurityException(msg);
3659         }
3660 
3661         final long callingId = Binder.clearCallingIdentity();
3662         try {
3663             synchronized (this) {
3664                 // Allow memory level to go down (the flag needs to be set before updating oom adj)
3665                 // because this method is also used to simulate low memory.
3666                 mAppProfiler.setAllowLowerMemLevelLocked(true);
3667                 synchronized (mProcLock) {
3668                     mProcessList.killPackageProcessesLSP(null /* packageName */, -1 /* appId */,
3669                             UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ,
3670                             ApplicationExitInfo.REASON_USER_REQUESTED,
3671                             ApplicationExitInfo.SUBREASON_UNKNOWN,
3672                             "kill all background");
3673                 }
3674 
3675                 mAppProfiler.doLowMemReportIfNeededLocked(null);
3676             }
3677         } finally {
3678             Binder.restoreCallingIdentity(callingId);
3679         }
3680     }
3681 
3682     /**
3683      * Kills all background processes, except those matching any of the
3684      * specified properties.
3685      *
3686      * @param minTargetSdk the target SDK version at or above which to preserve
3687      *                     processes, or {@code -1} to ignore the target SDK
3688      * @param maxProcState the process state at or below which to preserve
3689      *                     processes, or {@code -1} to ignore the process state
3690      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)3691     void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
3692         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3693                 != PackageManager.PERMISSION_GRANTED) {
3694             final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
3695                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3696                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3697             Slog.w(TAG, msg);
3698             throw new SecurityException(msg);
3699         }
3700 
3701         final long callingId = Binder.clearCallingIdentity();
3702         try {
3703             synchronized (this) {
3704                 synchronized (mProcLock) {
3705                     mProcessList.killAllBackgroundProcessesExceptLSP(minTargetSdk, maxProcState);
3706                 }
3707             }
3708         } finally {
3709             Binder.restoreCallingIdentity(callingId);
3710         }
3711     }
3712 
3713     @Override
forceStopPackage(final String packageName, int userId)3714     public void forceStopPackage(final String packageName, int userId) {
3715         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3716                 != PackageManager.PERMISSION_GRANTED) {
3717             String msg = "Permission Denial: forceStopPackage() from pid="
3718                     + Binder.getCallingPid()
3719                     + ", uid=" + Binder.getCallingUid()
3720                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3721             Slog.w(TAG, msg);
3722             throw new SecurityException(msg);
3723         }
3724         final int callingPid = Binder.getCallingPid();
3725         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
3726                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
3727         final long callingId = Binder.clearCallingIdentity();
3728         try {
3729             IPackageManager pm = AppGlobals.getPackageManager();
3730             synchronized(this) {
3731                 int[] users = userId == UserHandle.USER_ALL
3732                         ? mUserController.getUsers() : new int[] { userId };
3733                 for (int user : users) {
3734                     if (getPackageManagerInternal().isPackageStateProtected(
3735                             packageName, user)) {
3736                         Slog.w(TAG, "Ignoring request to force stop protected package "
3737                                 + packageName + " u" + user);
3738                         return;
3739                     }
3740 
3741                     int pkgUid = -1;
3742                     try {
3743                         pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
3744                                 user);
3745                     } catch (RemoteException e) {
3746                     }
3747                     if (pkgUid == -1) {
3748                         Slog.w(TAG, "Invalid packageName: " + packageName);
3749                         continue;
3750                     }
3751                     try {
3752                         pm.setPackageStoppedState(packageName, true, user);
3753                     } catch (RemoteException e) {
3754                     } catch (IllegalArgumentException e) {
3755                         Slog.w(TAG, "Failed trying to unstop package "
3756                                 + packageName + ": " + e);
3757                     }
3758                     if (mUserController.isUserRunning(user, 0)) {
3759                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
3760                         finishForceStopPackageLocked(packageName, pkgUid);
3761                     }
3762                 }
3763             }
3764         } finally {
3765             Binder.restoreCallingIdentity(callingId);
3766         }
3767     }
3768 
3769     @Override
addPackageDependency(String packageName)3770     public void addPackageDependency(String packageName) {
3771         int callingPid = Binder.getCallingPid();
3772         if (callingPid == myPid()) {
3773             //  Yeah, um, no.
3774             return;
3775         }
3776         ProcessRecord proc;
3777         synchronized (mPidsSelfLocked) {
3778             proc = mPidsSelfLocked.get(Binder.getCallingPid());
3779         }
3780         if (proc != null) {
3781             ArraySet<String> pkgDeps = proc.getPkgDeps();
3782             synchronized (this) {
3783                 synchronized (mProcLock) {
3784                     if (pkgDeps == null) {
3785                         proc.setPkgDeps(pkgDeps = new ArraySet<String>(1));
3786                     }
3787                     pkgDeps.add(packageName);
3788                 }
3789             }
3790         }
3791     }
3792 
3793     /*
3794      * The pkg name and app id have to be specified.
3795      */
3796     @Override
killApplication(String pkg, int appId, int userId, String reason)3797     public void killApplication(String pkg, int appId, int userId, String reason) {
3798         if (pkg == null) {
3799             return;
3800         }
3801         // Make sure the uid is valid.
3802         if (appId < 0) {
3803             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
3804             return;
3805         }
3806         int callerUid = Binder.getCallingUid();
3807         // Only the system server can kill an application
3808         if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
3809             // Post an aysnc message to kill the application
3810             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3811             msg.arg1 = appId;
3812             msg.arg2 = userId;
3813             Bundle bundle = new Bundle();
3814             bundle.putString("pkg", pkg);
3815             bundle.putString("reason", reason);
3816             msg.obj = bundle;
3817             mHandler.sendMessage(msg);
3818         } else {
3819             throw new SecurityException(callerUid + " cannot kill pkg: " +
3820                     pkg);
3821         }
3822     }
3823 
3824     @Override
closeSystemDialogs(String reason)3825     public void closeSystemDialogs(String reason) {
3826         mAtmInternal.closeSystemDialogs(reason);
3827     }
3828 
3829     @Override
getProcessMemoryInfo(int[] pids)3830     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
3831         enforceNotIsolatedCaller("getProcessMemoryInfo");
3832 
3833         final long now = SystemClock.uptimeMillis();
3834         final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME;
3835 
3836         final int callingPid = Binder.getCallingPid();
3837         final int callingUid = Binder.getCallingUid();
3838         final int callingUserId = UserHandle.getUserId(callingUid);
3839         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
3840                 callingUid) == PackageManager.PERMISSION_GRANTED;
3841         // Check REAL_GET_TASKS to see if they are allowed to access other uids
3842         final boolean allUids = mAtmInternal.isGetTasksAllowed(
3843                 "getProcessMemoryInfo", callingPid, callingUid);
3844 
3845         // Check if the caller is actually instrumented and from shell, if it's true, we may lift
3846         // the throttle of PSS info sampling.
3847         boolean isCallerInstrumentedFromShell = false;
3848         synchronized (mProcLock) {
3849             synchronized (mPidsSelfLocked) {
3850                 ProcessRecord caller = mPidsSelfLocked.get(callingPid);
3851                 if (caller != null) {
3852                     final ActiveInstrumentation instr = caller.getActiveInstrumentation();
3853                     isCallerInstrumentedFromShell = instr != null
3854                             && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID);
3855                 }
3856             }
3857         }
3858 
3859         final Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3860         for (int i=pids.length-1; i>=0; i--) {
3861             final Debug.MemoryInfo mi = infos[i] = new Debug.MemoryInfo();
3862             final ProcessRecord proc;
3863             final int oomAdj;
3864             final ProcessProfileRecord profile;
3865             synchronized (mAppProfiler.mProfilerLock) {
3866                 synchronized (mPidsSelfLocked) {
3867                     proc = mPidsSelfLocked.get(pids[i]);
3868                     if (proc != null) {
3869                         profile = proc.mProfile;
3870                         oomAdj = profile.getSetAdj();
3871                     } else {
3872                         profile = null;
3873                         oomAdj = 0;
3874                     }
3875                 }
3876             }
3877             final int targetUid = (proc != null) ? proc.uid : -1;
3878             final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1;
3879 
3880             if (callingUid != targetUid) {
3881                 if (!allUids) {
3882                     continue; // Not allowed to see other UIDs.
3883                 }
3884 
3885                 if (!allUsers && (targetUserId != callingUserId)) {
3886                     continue; // Not allowed to see other users.
3887                 }
3888             }
3889             if (proc != null) {
3890                 synchronized (mAppProfiler.mProfilerLock) {
3891                     if (profile.getLastMemInfoTime() >= lastNow && profile.getLastMemInfo() != null
3892                             && !isCallerInstrumentedFromShell) {
3893                         // It hasn't been long enough that we want to take another sample; return
3894                         // the last one.
3895                         mi.set(profile.getLastMemInfo());
3896                         continue;
3897                     }
3898                 }
3899             }
3900             final long startTime = SystemClock.currentThreadTimeMillis();
3901             final Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
3902             Debug.getMemoryInfo(pids[i], memInfo);
3903             final long duration = SystemClock.currentThreadTimeMillis() - startTime;
3904             mi.set(memInfo);
3905             if (proc != null) {
3906                 synchronized (mAppProfiler.mProfilerLock) {
3907                     profile.setLastMemInfo(memInfo);
3908                     profile.setLastMemInfoTime(SystemClock.uptimeMillis());
3909                     if (profile.getThread() != null && profile.getSetAdj() == oomAdj) {
3910                         // Record this for posterity if the process has been stable.
3911                         profile.addPss(mi.getTotalPss(),
3912                                 mi.getTotalUss(), mi.getTotalRss(), false,
3913                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, duration);
3914                         proc.getPkgList().forEachPackageProcessStats(holder -> {
3915                             final ProcessState state = holder.state;
3916                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
3917                                     proc.info.uid,
3918                                     state != null ? state.getName() : proc.processName,
3919                                     state != null ? state.getPackage() : proc.info.packageName,
3920                                     mi.getTotalPss(),
3921                                     mi.getTotalUss(),
3922                                     mi.getTotalRss(),
3923                                     ProcessStats.ADD_PSS_EXTERNAL_SLOW,
3924                                     duration,
3925                                     holder.appVersion);
3926                         });
3927                     }
3928                 }
3929             }
3930         }
3931         return infos;
3932     }
3933 
3934     @Override
getProcessPss(int[] pids)3935     public long[] getProcessPss(int[] pids) {
3936         enforceNotIsolatedCaller("getProcessPss");
3937 
3938         final int callingPid = Binder.getCallingPid();
3939         final int callingUid = Binder.getCallingUid();
3940         final int userId = UserHandle.getUserId(callingUid);
3941         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
3942                 callingUid) == PackageManager.PERMISSION_GRANTED;
3943         // Check REAL_GET_TASKS to see if they are allowed to access other uids
3944         final boolean allUids = mAtmInternal.isGetTasksAllowed(
3945                 "getProcessPss", callingPid, callingUid);
3946 
3947         final long[] pss = new long[pids.length];
3948         for (int i=pids.length-1; i>=0; i--) {
3949             ProcessRecord proc;
3950             int oomAdj;
3951             synchronized (mProcLock) {
3952                 synchronized (mPidsSelfLocked) {
3953                     proc = mPidsSelfLocked.get(pids[i]);
3954                     oomAdj = proc != null ? proc.mState.getSetAdj() : 0;
3955                 }
3956             }
3957             if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) {
3958                 // The caller is not allow to get information about this other process...
3959                 // just leave it empty.
3960                 continue;
3961             }
3962             final long[] tmpUss = new long[3];
3963             final long startTime = SystemClock.currentThreadTimeMillis();
3964             final long pi = pss[i] = Debug.getPss(pids[i], tmpUss, null);
3965             final long duration = SystemClock.currentThreadTimeMillis() - startTime;
3966             if (proc != null) {
3967                 final ProcessProfileRecord profile = proc.mProfile;
3968                 synchronized (mAppProfiler.mProfilerLock) {
3969                     if (profile.getThread() != null && profile.getSetAdj() == oomAdj) {
3970                         // Record this for posterity if the process has been stable.
3971                         profile.addPss(pi, tmpUss[0], tmpUss[2], false,
3972                                 ProcessStats.ADD_PSS_EXTERNAL, duration);
3973                         proc.getPkgList().forEachPackageProcessStats(holder -> {
3974                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
3975                                     proc.info.uid,
3976                                     holder.state.getName(),
3977                                     holder.state.getPackage(),
3978                                     pi,
3979                                     tmpUss[0],
3980                                     tmpUss[2],
3981                                     ProcessStats.ADD_PSS_EXTERNAL,
3982                                     duration,
3983                                     holder.appVersion);
3984                         });
3985                     }
3986                 }
3987             }
3988         }
3989         return pss;
3990     }
3991 
3992     @Override
killApplicationProcess(String processName, int uid)3993     public void killApplicationProcess(String processName, int uid) {
3994         if (processName == null) {
3995             return;
3996         }
3997 
3998         int callerUid = Binder.getCallingUid();
3999         // Only the system server can kill an application
4000         if (callerUid == SYSTEM_UID) {
4001             synchronized (this) {
4002                 ProcessRecord app = getProcessRecordLocked(processName, uid);
4003                 IApplicationThread thread;
4004                 if (app != null && (thread = app.getThread()) != null) {
4005                     try {
4006                         thread.scheduleSuicide();
4007                     } catch (RemoteException e) {
4008                         // If the other end already died, then our work here is done.
4009                     }
4010                 } else {
4011                     Slog.w(TAG, "Process/uid not found attempting kill of "
4012                             + processName + " / " + uid);
4013                 }
4014             }
4015         } else {
4016             throw new SecurityException(callerUid + " cannot kill app process: " +
4017                     processName);
4018         }
4019     }
4020 
4021     @GuardedBy("this")
forceStopPackageLocked(final String packageName, int uid, String reason)4022     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
4023         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
4024                 false, true, false, false, UserHandle.getUserId(uid), reason);
4025     }
4026 
4027     @GuardedBy("this")
finishForceStopPackageLocked(final String packageName, int uid)4028     private void finishForceStopPackageLocked(final String packageName, int uid) {
4029         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4030                 Uri.fromParts("package", packageName, null));
4031         if (!mProcessesReady) {
4032             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4033                     | Intent.FLAG_RECEIVER_FOREGROUND);
4034         }
4035         intent.putExtra(Intent.EXTRA_UID, uid);
4036         intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
4037         broadcastIntentLocked(null, null, null, intent,
4038                 null, null, 0, null, null, null, null, OP_NONE,
4039                 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
4040                 Binder.getCallingPid(), UserHandle.getUserId(uid));
4041     }
4042 
cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4043     private void cleanupDisabledPackageComponentsLocked(
4044             String packageName, int userId, String[] changedClasses) {
4045 
4046         Set<String> disabledClasses = null;
4047         boolean packageDisabled = false;
4048         IPackageManager pm = AppGlobals.getPackageManager();
4049 
4050         if (changedClasses == null) {
4051             // Nothing changed...
4052             return;
4053         }
4054 
4055         // Determine enable/disable state of the package and its components.
4056         int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4057         for (int i = changedClasses.length - 1; i >= 0; i--) {
4058             final String changedClass = changedClasses[i];
4059 
4060             if (changedClass.equals(packageName)) {
4061                 try {
4062                     // Entire package setting changed
4063                     enabled = pm.getApplicationEnabledSetting(packageName,
4064                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4065                 } catch (Exception e) {
4066                     // No such package/component; probably racing with uninstall.  In any
4067                     // event it means we have nothing further to do here.
4068                     return;
4069                 }
4070                 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4071                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4072                 if (packageDisabled) {
4073                     // Entire package is disabled.
4074                     // No need to continue to check component states.
4075                     disabledClasses = null;
4076                     break;
4077                 }
4078             } else {
4079                 try {
4080                     enabled = pm.getComponentEnabledSetting(
4081                             new ComponentName(packageName, changedClass),
4082                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4083                 } catch (Exception e) {
4084                     // As above, probably racing with uninstall.
4085                     return;
4086                 }
4087                 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4088                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
4089                     if (disabledClasses == null) {
4090                         disabledClasses = new ArraySet<>(changedClasses.length);
4091                     }
4092                     disabledClasses.add(changedClass);
4093                 }
4094             }
4095         }
4096 
4097         if (!packageDisabled && disabledClasses == null) {
4098             // Nothing to do here...
4099             return;
4100         }
4101 
4102         mAtmInternal.cleanupDisabledPackageComponents(
4103                 packageName, disabledClasses, userId, mBooted);
4104 
4105         // Clean-up disabled services.
4106         mServices.bringDownDisabledPackageServicesLocked(
4107                 packageName, disabledClasses, userId, false /* evenPersistent */, true /* doIt */);
4108 
4109         // Clean-up disabled providers.
4110         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4111         mCpHelper.getProviderMap().collectPackageProvidersLocked(
4112                 packageName, disabledClasses, true, false, userId, providers);
4113         for (int i = providers.size() - 1; i >= 0; i--) {
4114             mCpHelper.removeDyingProviderLocked(null, providers.get(i), true);
4115         }
4116 
4117         // Clean-up disabled broadcast receivers.
4118         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4119             mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4120                     packageName, disabledClasses, userId, true);
4121         }
4122 
4123     }
4124 
clearBroadcastQueueForUserLocked(int userId)4125     final boolean clearBroadcastQueueForUserLocked(int userId) {
4126         boolean didSomething = false;
4127         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4128             didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4129                     null, null, userId, true);
4130         }
4131         return didSomething;
4132     }
4133 
4134     @GuardedBy("this")
forceStopAppZygoteLocked(String packageName, int appId, int userId)4135     final void forceStopAppZygoteLocked(String packageName, int appId, int userId) {
4136         if (packageName == null) {
4137             return;
4138         }
4139         if (appId < 0) {
4140             try {
4141                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
4142                         .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
4143             } catch (RemoteException e) {
4144             }
4145         }
4146 
4147         mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */);
4148     }
4149 
4150     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4151     final boolean forceStopPackageLocked(String packageName, int appId,
4152             boolean callerWillRestart, boolean purgeCache, boolean doit,
4153             boolean evenPersistent, boolean uninstalling, int userId, String reason) {
4154         int i;
4155 
4156         if (userId == UserHandle.USER_ALL && packageName == null) {
4157             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
4158         }
4159 
4160         if (appId < 0 && packageName != null) {
4161             try {
4162                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
4163                         .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
4164             } catch (RemoteException e) {
4165             }
4166         }
4167 
4168         boolean didSomething;
4169         if (doit) {
4170             if (packageName != null) {
4171                 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
4172                         + " user=" + userId + ": " + reason);
4173             } else {
4174                 Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
4175             }
4176 
4177             mAppErrors.resetProcessCrashTime(packageName == null, appId, userId);
4178         }
4179 
4180         synchronized (mProcLock) {
4181             // Notify first that the package is stopped, so its process won't be restarted
4182             // unexpectedly if there is an activity of the package without attached process
4183             // becomes visible when killing its other processes with visible activities.
4184             didSomething = mAtmInternal.onForceStopPackage(
4185                     packageName, doit, evenPersistent, userId);
4186 
4187             didSomething |= mProcessList.killPackageProcessesLSP(packageName, appId, userId,
4188                     ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit,
4189                     evenPersistent, true /* setRemoved */, uninstalling,
4190                     packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED
4191                     : ApplicationExitInfo.REASON_USER_REQUESTED,
4192                     ApplicationExitInfo.SUBREASON_UNKNOWN,
4193                     (packageName == null ? ("stop user " + userId) : ("stop " + packageName))
4194                     + " due to " + reason);
4195         }
4196 
4197         if (mServices.bringDownDisabledPackageServicesLocked(
4198                 packageName, null /* filterByClasses */, userId, evenPersistent, doit)) {
4199             if (!doit) {
4200                 return true;
4201             }
4202             didSomething = true;
4203         }
4204 
4205         if (packageName == null) {
4206             // Remove all sticky broadcasts from this user.
4207             mStickyBroadcasts.remove(userId);
4208         }
4209 
4210         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4211         if (mCpHelper.getProviderMap().collectPackageProvidersLocked(packageName, null, doit,
4212                 evenPersistent, userId, providers)) {
4213             if (!doit) {
4214                 return true;
4215             }
4216             didSomething = true;
4217         }
4218         for (i = providers.size() - 1; i >= 0; i--) {
4219             mCpHelper.removeDyingProviderLocked(null, providers.get(i), true);
4220         }
4221 
4222         // Remove transient permissions granted from/to this package/user
4223         mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false);
4224 
4225         if (doit) {
4226             for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
4227                 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4228                         packageName, null, userId, doit);
4229             }
4230         }
4231 
4232         if (packageName == null || uninstalling) {
4233             didSomething |= mPendingIntentController.removePendingIntentsForPackage(
4234                     packageName, userId, appId, doit);
4235         }
4236 
4237         if (doit) {
4238             if (purgeCache && packageName != null) {
4239                 AttributeCache ac = AttributeCache.instance();
4240                 if (ac != null) {
4241                     ac.removePackage(packageName);
4242                 }
4243             }
4244             if (mBooted) {
4245                 mAtmInternal.resumeTopActivities(true /* scheduleIdle */);
4246             }
4247         }
4248 
4249         return didSomething;
4250     }
4251 
4252     @GuardedBy("this")
processStartTimedOutLocked(ProcessRecord app)4253     private final void processStartTimedOutLocked(ProcessRecord app) {
4254         final int pid = app.getPid();
4255         boolean gone = removePidIfNoThreadLocked(app);
4256 
4257         if (gone) {
4258             Slog.w(TAG, "Process " + app + " failed to attach");
4259             EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName);
4260             synchronized (mProcLock) {
4261                 mProcessList.removeProcessNameLocked(app.processName, app.uid);
4262                 mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
4263                 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
4264                 // Take care of any launching providers waiting for this process.
4265                 mCpHelper.cleanupAppInLaunchingProvidersLocked(app, true);
4266                 // Take care of any services that are waiting for the process.
4267                 mServices.processStartTimedOutLocked(app);
4268                 app.killLocked("start timeout", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4269                         true);
4270                 if (app.isolated) {
4271                     mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
4272                 }
4273                 removeLruProcessLocked(app);
4274             }
4275             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4276             if (backupTarget != null && backupTarget.app.getPid() == pid) {
4277                 Slog.w(TAG, "Unattached app died before backup, skipping");
4278                 mHandler.post(new Runnable() {
4279                 @Override
4280                     public void run(){
4281                         try {
4282                             IBackupManager bm = IBackupManager.Stub.asInterface(
4283                                     ServiceManager.getService(Context.BACKUP_SERVICE));
4284                             bm.agentDisconnectedForUser(app.userId, app.info.packageName);
4285                         } catch (RemoteException e) {
4286                             // Can't happen; the backup manager is local
4287                         }
4288                     }
4289                 });
4290             }
4291             if (isPendingBroadcastProcessLocked(pid)) {
4292                 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
4293                 skipPendingBroadcastLocked(pid);
4294             }
4295         } else {
4296             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
4297         }
4298     }
4299 
4300     @GuardedBy("this")
attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4301     private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
4302             int pid, int callingUid, long startSeq) {
4303 
4304         // Find the application record that is being attached...  either via
4305         // the pid if we are running in multiple processes, or just pull the
4306         // next app record if we are emulating process with anonymous threads.
4307         ProcessRecord app;
4308         long startTime = SystemClock.uptimeMillis();
4309         long bindApplicationTimeMillis;
4310         if (pid != MY_PID && pid >= 0) {
4311             synchronized (mPidsSelfLocked) {
4312                 app = mPidsSelfLocked.get(pid);
4313             }
4314             if (app != null && (app.getStartUid() != callingUid || app.getStartSeq() != startSeq)) {
4315                 String processName = null;
4316                 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4317                 if (pending != null) {
4318                     processName = pending.processName;
4319                 }
4320                 final String msg = "attachApplicationLocked process:" + processName
4321                         + " startSeq:" + startSeq
4322                         + " pid:" + pid
4323                         + " belongs to another existing app:" + app.processName
4324                         + " startSeq:" + app.getStartSeq();
4325                 Slog.wtf(TAG, msg);
4326                 // SafetyNet logging for b/131105245.
4327                 EventLog.writeEvent(0x534e4554, "131105245", app.getStartUid(), msg);
4328                 // If there is already an app occupying that pid that hasn't been cleaned up
4329                 cleanUpApplicationRecordLocked(app, pid, false, false, -1,
4330                         true /*replacingPid*/, false /* fromBinderDied */);
4331                 removePidLocked(pid, app);
4332                 app = null;
4333             }
4334         } else {
4335             app = null;
4336         }
4337 
4338         // It's possible that process called attachApplication before we got a chance to
4339         // update the internal state.
4340         if (app == null && startSeq > 0) {
4341             final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4342             if (pending != null && pending.getStartUid() == callingUid
4343                     && pending.getStartSeq() == startSeq
4344                     && mProcessList.handleProcessStartedLocked(pending, pid,
4345                         pending.isUsingWrapper(), startSeq, true)) {
4346                 app = pending;
4347             }
4348         }
4349 
4350         if (app == null) {
4351             Slog.w(TAG, "No pending application record for pid " + pid
4352                     + " (IApplicationThread " + thread + "); dropping process");
4353             EventLogTags.writeAmDropProcess(pid);
4354             if (pid > 0 && pid != MY_PID) {
4355                 killProcessQuiet(pid);
4356                 //TODO: killProcessGroup(app.info.uid, pid);
4357                 // We can't log the app kill info for this process since we don't
4358                 // know who it is, so just skip the logging.
4359             } else {
4360                 try {
4361                     thread.scheduleExit();
4362                 } catch (Exception e) {
4363                     // Ignore exceptions.
4364                 }
4365             }
4366             return false;
4367         }
4368 
4369         // If this application record is still attached to a previous
4370         // process, clean it up now.
4371         if (app.getThread() != null) {
4372             handleAppDiedLocked(app, pid, true, true, false /* fromBinderDied */);
4373         }
4374 
4375         // Tell the process all about itself.
4376 
4377         if (DEBUG_ALL) Slog.v(
4378                 TAG, "Binding process pid " + pid + " to record " + app);
4379 
4380         final String processName = app.processName;
4381         try {
4382             AppDeathRecipient adr = new AppDeathRecipient(
4383                     app, pid, thread);
4384             thread.asBinder().linkToDeath(adr, 0);
4385             app.setDeathRecipient(adr);
4386         } catch (RemoteException e) {
4387             app.resetPackageList(mProcessStats);
4388             mProcessList.startProcessLocked(app,
4389                     new HostingRecord("link fail", processName),
4390                     ZYGOTE_POLICY_FLAG_EMPTY);
4391             return false;
4392         }
4393 
4394         EventLogTags.writeAmProcBound(app.userId, pid, app.processName);
4395 
4396         synchronized (mProcLock) {
4397             app.mState.setCurAdj(ProcessList.INVALID_ADJ);
4398             app.mState.setSetAdj(ProcessList.INVALID_ADJ);
4399             app.mState.setVerifiedAdj(ProcessList.INVALID_ADJ);
4400             mOomAdjuster.setAttachingSchedGroupLSP(app);
4401             app.mState.setForcingToImportant(null);
4402             updateProcessForegroundLocked(app, false, 0, false);
4403             app.mState.setHasShownUi(false);
4404             app.mState.setCached(false);
4405             app.setDebugging(false);
4406             app.setKilledByAm(false);
4407             app.setKilled(false);
4408             // We carefully use the same state that PackageManager uses for
4409             // filtering, since we use this flag to decide if we need to install
4410             // providers when user is unlocked later
4411             app.setUnlocked(StorageManager.isUserKeyUnlocked(app.userId));
4412         }
4413 
4414         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4415 
4416         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4417         List<ProviderInfo> providers = normalMode
4418                                             ? mCpHelper.generateApplicationProvidersLocked(app)
4419                                             : null;
4420 
4421         if (providers != null && mCpHelper.checkAppInLaunchingProvidersLocked(app)) {
4422             Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
4423             msg.obj = app;
4424             mHandler.sendMessageDelayed(msg,
4425                     ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS);
4426         }
4427 
4428         checkTime(startTime, "attachApplicationLocked: before bindApplication");
4429 
4430         if (!normalMode) {
4431             Slog.i(TAG, "Launching preboot mode app: " + app);
4432         }
4433 
4434         if (DEBUG_ALL) Slog.v(
4435             TAG, "New app record " + app
4436             + " thread=" + thread.asBinder() + " pid=" + pid);
4437         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4438         try {
4439             int testMode = ApplicationThreadConstants.DEBUG_OFF;
4440             if (mDebugApp != null && mDebugApp.equals(processName)) {
4441                 testMode = mWaitForDebugger
4442                     ? ApplicationThreadConstants.DEBUG_WAIT
4443                     : ApplicationThreadConstants.DEBUG_ON;
4444                 app.setDebugging(true);
4445                 if (mDebugTransient) {
4446                     mDebugApp = mOrigDebugApp;
4447                     mWaitForDebugger = mOrigWaitForDebugger;
4448                 }
4449             }
4450 
4451             boolean enableTrackAllocation = false;
4452             synchronized (mProcLock) {
4453                 if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
4454                     enableTrackAllocation = true;
4455                     mTrackAllocationApp = null;
4456                 }
4457             }
4458 
4459             // If the app is being launched for restore or full backup, set it up specially
4460             boolean isRestrictedBackupMode = false;
4461             if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) {
4462                 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID
4463                         && ((backupTarget.backupMode == BackupRecord.RESTORE)
4464                                 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL)
4465                                 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL));
4466             }
4467 
4468             final ActiveInstrumentation instr = app.getActiveInstrumentation();
4469 
4470             if (instr != null) {
4471                 notifyPackageUse(instr.mClass.getPackageName(),
4472                                  PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
4473             }
4474             ProtoLog.v(WM_DEBUG_CONFIGURATION, "Binding proc %s with config %s",
4475                     processName, app.getWindowProcessController().getConfiguration());
4476             ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info;
4477             app.setCompat(compatibilityInfoForPackage(appInfo));
4478 
4479             ProfilerInfo profilerInfo = mAppProfiler.setupProfilerInfoLocked(thread, app, instr);
4480 
4481             // We deprecated Build.SERIAL and it is not accessible to
4482             // Instant Apps and target APIs higher than O MR1. Since access to the serial
4483             // is now behind a permission we push down the value.
4484             final String buildSerial = (!appInfo.isInstantApp()
4485                     && appInfo.targetSdkVersion < Build.VERSION_CODES.P)
4486                             ? sTheRealBuildSerial : Build.UNKNOWN;
4487 
4488             // Figure out whether the app needs to run in autofill compat mode.
4489             AutofillOptions autofillOptions = null;
4490             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
4491                 final AutofillManagerInternal afm = LocalServices.getService(
4492                         AutofillManagerInternal.class);
4493                 if (afm != null) {
4494                     autofillOptions = afm.getAutofillOptions(
4495                             app.info.packageName, app.info.longVersionCode, app.userId);
4496                 }
4497             }
4498             ContentCaptureOptions contentCaptureOptions = null;
4499             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
4500                 final ContentCaptureManagerInternal ccm =
4501                         LocalServices.getService(ContentCaptureManagerInternal.class);
4502                 if (ccm != null) {
4503                     contentCaptureOptions = ccm.getOptionsForPackage(app.userId,
4504                             app.info.packageName);
4505                 }
4506             }
4507             SharedMemory serializedSystemFontMap = null;
4508             final FontManagerInternal fm = LocalServices.getService(FontManagerInternal.class);
4509             if (fm != null) {
4510                 serializedSystemFontMap = fm.getSerializedSystemFontMap();
4511             }
4512 
4513             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
4514             bindApplicationTimeMillis = SystemClock.elapsedRealtime();
4515             mAtmInternal.preBindApplication(app.getWindowProcessController());
4516             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
4517             if (mPlatformCompat != null) {
4518                 mPlatformCompat.resetReporting(app.info);
4519             }
4520             final ProviderInfoList providerList = ProviderInfoList.fromList(providers);
4521             if (app.getIsolatedEntryPoint() != null) {
4522                 // This is an isolated process which should just call an entry point instead of
4523                 // being bound to an application.
4524                 thread.runIsolatedEntryPoint(
4525                         app.getIsolatedEntryPoint(), app.getIsolatedEntryPointArgs());
4526             } else if (instr2 != null) {
4527                 thread.bindApplication(processName, appInfo, providerList,
4528                         instr2.mClass,
4529                         profilerInfo, instr2.mArguments,
4530                         instr2.mWatcher,
4531                         instr2.mUiAutomationConnection, testMode,
4532                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
4533                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
4534                         new Configuration(app.getWindowProcessController().getConfiguration()),
4535                         app.getCompat(), getCommonServicesLocked(app.isolated),
4536                         mCoreSettingsObserver.getCoreSettingsLocked(),
4537                         buildSerial, autofillOptions, contentCaptureOptions,
4538                         app.getDisabledCompatChanges(), serializedSystemFontMap);
4539             } else {
4540                 thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
4541                         null, null, null, testMode,
4542                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
4543                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
4544                         new Configuration(app.getWindowProcessController().getConfiguration()),
4545                         app.getCompat(), getCommonServicesLocked(app.isolated),
4546                         mCoreSettingsObserver.getCoreSettingsLocked(),
4547                         buildSerial, autofillOptions, contentCaptureOptions,
4548                         app.getDisabledCompatChanges(), serializedSystemFontMap);
4549             }
4550             if (profilerInfo != null) {
4551                 profilerInfo.closeFd();
4552                 profilerInfo = null;
4553             }
4554 
4555             // Make app active after binding application or client may be running requests (e.g
4556             // starting activities) before it is ready.
4557             synchronized (mProcLock) {
4558                 app.makeActive(thread, mProcessStats);
4559                 checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
4560             }
4561             updateLruProcessLocked(app, false, null);
4562             checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
4563             final long now = SystemClock.uptimeMillis();
4564             synchronized (mAppProfiler.mProfilerLock) {
4565                 app.mProfile.setLastRequestedGc(now);
4566                 app.mProfile.setLastLowMemory(now);
4567             }
4568         } catch (Exception e) {
4569             // We need kill the process group here. (b/148588589)
4570             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
4571             app.resetPackageList(mProcessStats);
4572             app.unlinkDeathRecipient();
4573             app.killLocked("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4574                     true);
4575             handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */);
4576             return false;
4577         }
4578 
4579         // Remove this record from the list of starting applications.
4580         mPersistentStartingProcesses.remove(app);
4581         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
4582                 "Attach application locked removing on hold: " + app);
4583         mProcessesOnHold.remove(app);
4584 
4585         boolean badApp = false;
4586         boolean didSomething = false;
4587 
4588         // See if the top visible activity is waiting to run in this process...
4589         if (normalMode) {
4590             try {
4591                 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
4592             } catch (Exception e) {
4593                 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
4594                 badApp = true;
4595             }
4596         }
4597 
4598         // Find any services that should be running in this process...
4599         if (!badApp) {
4600             try {
4601                 didSomething |= mServices.attachApplicationLocked(app, processName);
4602                 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
4603             } catch (Exception e) {
4604                 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
4605                 badApp = true;
4606             }
4607         }
4608 
4609         // Check if a next-broadcast receiver is in this process...
4610         if (!badApp && isPendingBroadcastProcessLocked(pid)) {
4611             try {
4612                 didSomething |= sendPendingBroadcastsLocked(app);
4613                 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
4614             } catch (Exception e) {
4615                 // If the app died trying to launch the receiver we declare it 'bad'
4616                 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
4617                 badApp = true;
4618             }
4619         }
4620 
4621         // Check whether the next backup agent is in this process...
4622         if (!badApp && backupTarget != null && backupTarget.app == app) {
4623             if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
4624                     "New app is backup target, launching agent for " + app);
4625             notifyPackageUse(backupTarget.appInfo.packageName,
4626                              PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
4627             try {
4628                 thread.scheduleCreateBackupAgent(backupTarget.appInfo,
4629                         compatibilityInfoForPackage(backupTarget.appInfo),
4630                         backupTarget.backupMode, backupTarget.userId, backupTarget.operationType);
4631             } catch (Exception e) {
4632                 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
4633                 badApp = true;
4634             }
4635         }
4636 
4637         if (badApp) {
4638             app.killLocked("error during init", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4639                     true);
4640             handleAppDiedLocked(app, pid, false, true, false /* fromBinderDied */);
4641             return false;
4642         }
4643 
4644         if (!didSomething) {
4645             updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
4646             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
4647         }
4648 
4649         FrameworkStatsLog.write(
4650                 FrameworkStatsLog.PROCESS_START_TIME,
4651                 app.info.uid,
4652                 pid,
4653                 app.info.packageName,
4654                 FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD,
4655                 app.getStartTime(),
4656                 (int) (bindApplicationTimeMillis - app.getStartTime()),
4657                 (int) (SystemClock.elapsedRealtime() - app.getStartTime()),
4658                 app.getHostingRecord().getType(),
4659                 (app.getHostingRecord().getName() != null ? app.getHostingRecord().getName() : ""));
4660         return true;
4661     }
4662 
4663     @Override
attachApplication(IApplicationThread thread, long startSeq)4664     public final void attachApplication(IApplicationThread thread, long startSeq) {
4665         if (thread == null) {
4666             throw new SecurityException("Invalid application interface");
4667         }
4668         synchronized (this) {
4669             int callingPid = Binder.getCallingPid();
4670             final int callingUid = Binder.getCallingUid();
4671             final long origId = Binder.clearCallingIdentity();
4672             attachApplicationLocked(thread, callingPid, callingUid, startSeq);
4673             Binder.restoreCallingIdentity(origId);
4674         }
4675     }
4676 
checkTime(long startTime, String where)4677     void checkTime(long startTime, String where) {
4678         long now = SystemClock.uptimeMillis();
4679         if ((now - startTime) > 50) {
4680             // If we are taking more than 50ms, log about it.
4681             Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where);
4682         }
4683     }
4684 
4685     @Override
showBootMessage(final CharSequence msg, final boolean always)4686     public void showBootMessage(final CharSequence msg, final boolean always) {
4687         if (Binder.getCallingUid() != myUid()) {
4688             throw new SecurityException();
4689         }
4690         mWindowManager.showBootMessage(msg, always);
4691     }
4692 
finishBooting()4693     final void finishBooting() {
4694         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
4695                 Trace.TRACE_TAG_ACTIVITY_MANAGER);
4696         t.traceBegin("FinishBooting");
4697 
4698         synchronized (this) {
4699             if (!mBootAnimationComplete) {
4700                 mCallFinishBooting = true;
4701                 return;
4702             }
4703             mCallFinishBooting = false;
4704         }
4705 
4706         // Let the ART runtime in zygote and system_server know that the boot completed.
4707         ZYGOTE_PROCESS.bootCompleted();
4708         VMRuntime.bootCompleted();
4709 
4710         IntentFilter pkgFilter = new IntentFilter();
4711         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4712         pkgFilter.addDataScheme("package");
4713         mContext.registerReceiver(new BroadcastReceiver() {
4714             @Override
4715             public void onReceive(Context context, Intent intent) {
4716                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4717                 if (pkgs != null) {
4718                     for (String pkg : pkgs) {
4719                         synchronized (ActivityManagerService.this) {
4720                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
4721                                     0, "query restart")) {
4722                                 setResultCode(Activity.RESULT_OK);
4723                                 return;
4724                             }
4725                         }
4726                     }
4727                 }
4728             }
4729         }, pkgFilter);
4730 
4731         // Inform checkpointing systems of success
4732         try {
4733             // This line is needed to CTS test for the correct exception handling
4734             // See b/138952436#comment36 for context
4735             Slog.i(TAG, "About to commit checkpoint");
4736             IStorageManager storageManager = PackageHelper.getStorageManager();
4737             storageManager.commitChanges();
4738         } catch (Exception e) {
4739             PowerManager pm = (PowerManager)
4740                      mInjector.getContext().getSystemService(Context.POWER_SERVICE);
4741             pm.reboot("Checkpoint commit failed");
4742         }
4743 
4744         // Let system services know.
4745         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED);
4746 
4747         synchronized (this) {
4748             // Ensure that any processes we had put on hold are now started
4749             // up.
4750             final int NP = mProcessesOnHold.size();
4751             if (NP > 0) {
4752                 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold);
4753                 for (int ip = 0; ip < NP; ip++) {
4754                     if (DEBUG_PROCESSES) {
4755                         Slog.v(TAG_PROCESSES, "Starting process on hold: " + procs.get(ip));
4756                     }
4757                     mProcessList.startProcessLocked(procs.get(ip),
4758                             new HostingRecord("on-hold"),
4759                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
4760                 }
4761             }
4762             if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
4763                 return;
4764             }
4765             // Start looking for apps that are abusing wake locks.
4766             Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
4767             mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
4768             // Check if we are performing userspace reboot before setting sys.boot_completed to
4769             // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys
4770             // .boot_completed is 1.
4771             if (InitProperties.userspace_reboot_in_progress().orElse(false)) {
4772                 UserspaceRebootLogger.noteUserspaceRebootSuccess();
4773             }
4774             // Tell anyone interested that we are done booting!
4775             SystemProperties.set("sys.boot_completed", "1");
4776 
4777             // And trigger dev.bootcomplete if we are not showing encryption progress
4778             if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse(""))
4779                     || "".equals(VoldProperties.encrypt_progress().orElse(""))) {
4780                 SystemProperties.set("dev.bootcomplete", "1");
4781             }
4782             mUserController.sendBootCompleted(
4783                     new IIntentReceiver.Stub() {
4784                         @Override
4785                         public void performReceive(Intent intent, int resultCode,
4786                                 String data, Bundle extras, boolean ordered,
4787                                 boolean sticky, int sendingUser) {
4788                             synchronized (mProcLock) {
4789                                 mAppProfiler.requestPssAllProcsLPr(
4790                                         SystemClock.uptimeMillis(), true, false);
4791                             }
4792                         }
4793                     });
4794             maybeLogUserspaceRebootEvent();
4795             mUserController.scheduleStartProfiles();
4796         }
4797         // UART is on if init's console service is running, send a warning notification.
4798         showConsoleNotificationIfActive();
4799 
4800         t.traceEnd();
4801     }
4802 
showConsoleNotificationIfActive()4803     private void showConsoleNotificationIfActive() {
4804         if (!SystemProperties.get("init.svc.console").equals("running")) {
4805             return;
4806         }
4807         String title = mContext
4808                 .getString(com.android.internal.R.string.console_running_notification_title);
4809         String message = mContext
4810                 .getString(com.android.internal.R.string.console_running_notification_message);
4811         Notification notification =
4812                 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
4813                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
4814                         .setWhen(0)
4815                         .setOngoing(true)
4816                         .setTicker(title)
4817                         .setDefaults(0)  // please be quiet
4818                         .setColor(mContext.getColor(
4819                                 com.android.internal.R.color
4820                                         .system_notification_accent_color))
4821                         .setContentTitle(title)
4822                         .setContentText(message)
4823                         .setVisibility(Notification.VISIBILITY_PUBLIC)
4824                         .build();
4825 
4826         NotificationManager notificationManager =
4827                 mContext.getSystemService(NotificationManager.class);
4828         notificationManager.notifyAsUser(
4829                 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL);
4830 
4831     }
4832 
4833     @Override
bootAnimationComplete()4834     public void bootAnimationComplete() {
4835         if (DEBUG_ALL) Slog.d(TAG, "bootAnimationComplete: Callers=" + Debug.getCallers(4));
4836 
4837         final boolean callFinishBooting;
4838         synchronized (this) {
4839             callFinishBooting = mCallFinishBooting;
4840             mBootAnimationComplete = true;
4841         }
4842         if (callFinishBooting) {
4843             finishBooting();
4844         }
4845     }
4846 
ensureBootCompleted()4847     final void ensureBootCompleted() {
4848         boolean booting;
4849         boolean enableScreen;
4850         synchronized (this) {
4851             booting = mBooting;
4852             mBooting = false;
4853             enableScreen = !mBooted;
4854             mBooted = true;
4855         }
4856 
4857         if (booting) {
4858             finishBooting();
4859         }
4860 
4861         if (enableScreen) {
4862             mAtmInternal.enableScreenAfterBoot(mBooted);
4863         }
4864     }
4865 
4866     /**
4867      * @deprecated Use {@link #getIntentSenderWithFeature} instead
4868      */
4869     @Deprecated
4870     @Override
getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)4871     public IIntentSender getIntentSender(int type,
4872             String packageName, IBinder token, String resultWho,
4873             int requestCode, Intent[] intents, String[] resolvedTypes,
4874             int flags, Bundle bOptions, int userId) {
4875         return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode,
4876                 intents, resolvedTypes, flags, bOptions, userId);
4877     }
4878 
4879     @Override
getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)4880     public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId,
4881             IBinder token, String resultWho, int requestCode, Intent[] intents,
4882             String[] resolvedTypes, int flags, Bundle bOptions, int userId) {
4883         enforceNotIsolatedCaller("getIntentSender");
4884 
4885         return getIntentSenderWithFeatureAsApp(type, packageName, featureId, token, resultWho,
4886                 requestCode, intents, resolvedTypes, flags, bOptions, userId,
4887                 Binder.getCallingUid());
4888     }
4889 
4890     /**
4891      * System-internal callers can invoke this with owningUid being the app's own identity
4892      * rather than the public API's behavior of always assigning ownership to the actual
4893      * caller identity.  This will create an IntentSender as though the package/userid/uid app
4894      * were the caller, so that the ultimate PendingIntent is triggered with only the app's
4895      * capabilities and not the system's.  Used in cases like notification groups where
4896      * the OS must synthesize a PendingIntent on an app's behalf.
4897      */
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)4898     public IIntentSender getIntentSenderWithFeatureAsApp(int type, String packageName,
4899             String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents,
4900             String[] resolvedTypes, int flags, Bundle bOptions, int userId, int owningUid) {
4901         // NOTE: The service lock isn't held in this method because nothing in the method requires
4902         // the service lock to be held.
4903 
4904         // Refuse possible leaked file descriptors
4905         if (intents != null) {
4906             if (intents.length < 1) {
4907                 throw new IllegalArgumentException("Intents array length must be >= 1");
4908             }
4909             for (int i=0; i<intents.length; i++) {
4910                 Intent intent = intents[i];
4911                 if (intent != null) {
4912                     if (intent.hasFileDescriptors()) {
4913                         throw new IllegalArgumentException("File descriptors passed in Intent");
4914                     }
4915                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
4916                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4917                         throw new IllegalArgumentException(
4918                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4919                     }
4920                     intents[i] = new Intent(intent);
4921                 }
4922             }
4923             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
4924                 throw new IllegalArgumentException(
4925                         "Intent array length does not match resolvedTypes length");
4926             }
4927         }
4928         if (bOptions != null) {
4929             if (bOptions.hasFileDescriptors()) {
4930                 throw new IllegalArgumentException("File descriptors passed in options");
4931             }
4932         }
4933 
4934         int origUserId = userId;
4935         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), owningUid, userId,
4936                 type == ActivityManager.INTENT_SENDER_BROADCAST,
4937                 ALLOW_NON_FULL, "getIntentSender", null);
4938         if (origUserId == UserHandle.USER_CURRENT) {
4939             // We don't want to evaluate this until the pending intent is
4940             // actually executed.  However, we do want to always do the
4941             // security checking for it above.
4942             userId = UserHandle.USER_CURRENT;
4943         }
4944         try {
4945             if (owningUid != 0 && owningUid != SYSTEM_UID) {
4946                 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
4947                         MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(owningUid));
4948                 if (!UserHandle.isSameApp(owningUid, uid)) {
4949                     String msg = "Permission Denial: getIntentSender() from pid="
4950                             + Binder.getCallingPid()
4951                             + ", uid=" + owningUid
4952                             + ", (need uid=" + uid + ")"
4953                             + " is not allowed to send as package " + packageName;
4954                     Slog.w(TAG, msg);
4955                     throw new SecurityException(msg);
4956                 }
4957             }
4958 
4959             if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
4960                 return mAtmInternal.getIntentSender(type, packageName, featureId, owningUid,
4961                         userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
4962                         bOptions);
4963             }
4964             return mPendingIntentController.getIntentSender(type, packageName, featureId,
4965                     owningUid, userId, token, resultWho, requestCode, intents, resolvedTypes,
4966                     flags, bOptions);
4967         } catch (RemoteException e) {
4968             throw new SecurityException(e);
4969         }
4970     }
4971 
4972     @Override
sendIntentSender(IIntentSender target, IBinder allowlistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)4973     public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code,
4974             Intent intent, String resolvedType,
4975             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
4976         if (target instanceof PendingIntentRecord) {
4977             return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType,
4978                     allowlistToken, finishedReceiver, requiredPermission, options);
4979         } else {
4980             if (intent == null) {
4981                 // Weird case: someone has given us their own custom IIntentSender, and now
4982                 // they have someone else trying to send to it but of course this isn't
4983                 // really a PendingIntent, so there is no base Intent, and the caller isn't
4984                 // supplying an Intent... but we never want to dispatch a null Intent to
4985                 // a receiver, so um...  let's make something up.
4986                 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
4987                 intent = new Intent(Intent.ACTION_MAIN);
4988             }
4989             try {
4990                 target.send(code, intent, resolvedType, allowlistToken, null,
4991                         requiredPermission, options);
4992             } catch (RemoteException e) {
4993             }
4994             // Platform code can rely on getting a result back when the send is done, but if
4995             // this intent sender is from outside of the system we can't rely on it doing that.
4996             // So instead we don't give it the result receiver, and instead just directly
4997             // report the finish immediately.
4998             if (finishedReceiver != null) {
4999                 try {
5000                     finishedReceiver.performReceive(intent, 0,
5001                             null, null, false, false, UserHandle.getCallingUserId());
5002                 } catch (RemoteException e) {
5003                 }
5004             }
5005             return 0;
5006         }
5007     }
5008 
5009     @Override
cancelIntentSender(IIntentSender sender)5010     public void cancelIntentSender(IIntentSender sender) {
5011         mPendingIntentController.cancelIntentSender(sender);
5012     }
5013 
5014     @Override
registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5015     public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) {
5016         mPendingIntentController.registerIntentSenderCancelListener(sender, receiver);
5017     }
5018 
5019     @Override
unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5020     public void unregisterIntentSenderCancelListener(IIntentSender sender,
5021             IResultReceiver receiver) {
5022         mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver);
5023     }
5024 
5025     @Override
getInfoForIntentSender(IIntentSender sender)5026     public PendingIntentInfo getInfoForIntentSender(IIntentSender sender) {
5027         if (sender instanceof PendingIntentRecord) {
5028             PendingIntentRecord res = (PendingIntentRecord) sender;
5029             return new PendingIntentInfo(
5030                     res.key.packageName,
5031                     res.uid,
5032                     (res.key.flags & PendingIntent.FLAG_IMMUTABLE) != 0,
5033                     res.key.type);
5034         } else {
5035             return new PendingIntentInfo(null, -1, false, ActivityManager.INTENT_SENDER_UNKNOWN);
5036         }
5037     }
5038 
5039     @Override
isIntentSenderTargetedToPackage(IIntentSender pendingResult)5040     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5041         if (!(pendingResult instanceof PendingIntentRecord)) {
5042             return false;
5043         }
5044         try {
5045             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5046             if (res.key.allIntents == null) {
5047                 return false;
5048             }
5049             for (int i=0; i<res.key.allIntents.length; i++) {
5050                 Intent intent = res.key.allIntents[i];
5051                 if (intent.getPackage() != null && intent.getComponent() != null) {
5052                     return false;
5053                 }
5054             }
5055             return true;
5056         } catch (ClassCastException e) {
5057         }
5058         return false;
5059     }
5060 
5061     @Override
isIntentSenderAnActivity(IIntentSender pendingResult)5062     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
5063         if (!(pendingResult instanceof PendingIntentRecord)) {
5064             return false;
5065         }
5066         try {
5067             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5068             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
5069                 return true;
5070             }
5071             return false;
5072         } catch (ClassCastException e) {
5073         }
5074         return false;
5075     }
5076 
5077     @Override
getIntentForIntentSender(IIntentSender pendingResult)5078     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
5079         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5080                 "getIntentForIntentSender()");
5081         if (!(pendingResult instanceof PendingIntentRecord)) {
5082             return null;
5083         }
5084         try {
5085             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5086             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
5087         } catch (ClassCastException e) {
5088         }
5089         return null;
5090     }
5091 
5092     @Override
queryIntentComponentsForIntentSender( IIntentSender pendingResult, int matchFlags)5093     public ParceledListSlice<ResolveInfo> queryIntentComponentsForIntentSender(
5094             IIntentSender pendingResult, int matchFlags) {
5095         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5096                 "queryIntentComponentsForIntentSender()");
5097         Preconditions.checkNotNull(pendingResult);
5098         final PendingIntentRecord res;
5099         try {
5100             res = (PendingIntentRecord) pendingResult;
5101         } catch (ClassCastException e) {
5102             return null;
5103         }
5104         final Intent intent = res.key.requestIntent;
5105         if (intent == null) {
5106             return null;
5107         }
5108         final int userId = res.key.userId;
5109         switch (res.key.type) {
5110             case ActivityManager.INTENT_SENDER_ACTIVITY:
5111                 return new ParceledListSlice<>(mContext.getPackageManager()
5112                         .queryIntentActivitiesAsUser(intent, matchFlags, userId));
5113             case ActivityManager.INTENT_SENDER_SERVICE:
5114             case ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE:
5115                 return new ParceledListSlice<>(mContext.getPackageManager()
5116                         .queryIntentServicesAsUser(intent, matchFlags, userId));
5117             case ActivityManager.INTENT_SENDER_BROADCAST:
5118                 return new ParceledListSlice<>(mContext.getPackageManager()
5119                         .queryBroadcastReceiversAsUser(intent, matchFlags, userId));
5120             default: // ActivityManager.INTENT_SENDER_ACTIVITY_RESULT
5121                 throw new IllegalStateException("Unsupported intent sender type: " + res.key.type);
5122         }
5123     }
5124 
5125     @Override
getTagForIntentSender(IIntentSender pendingResult, String prefix)5126     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
5127         if (!(pendingResult instanceof PendingIntentRecord)) {
5128             return null;
5129         }
5130         try {
5131             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5132             synchronized (this) {
5133                 return getTagForIntentSenderLocked(res, prefix);
5134             }
5135         } catch (ClassCastException e) {
5136         }
5137         return null;
5138     }
5139 
getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5140     String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
5141         final Intent intent = res.key.requestIntent;
5142         if (intent != null) {
5143             if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
5144                     || res.lastTagPrefix.equals(prefix))) {
5145                 return res.lastTag;
5146             }
5147             res.lastTagPrefix = prefix;
5148             final StringBuilder sb = new StringBuilder(128);
5149             if (prefix != null) {
5150                 sb.append(prefix);
5151             }
5152             if (intent.getAction() != null) {
5153                 sb.append(intent.getAction());
5154             } else if (intent.getComponent() != null) {
5155                 intent.getComponent().appendShortString(sb);
5156             } else {
5157                 sb.append("?");
5158             }
5159             return res.lastTag = sb.toString();
5160         }
5161         return null;
5162     }
5163 
5164     @Override
setProcessLimit(int max)5165     public void setProcessLimit(int max) {
5166         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5167                 "setProcessLimit()");
5168         synchronized (this) {
5169             mConstants.setOverrideMaxCachedProcesses(max);
5170             trimApplicationsLocked(true, OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
5171         }
5172     }
5173 
5174     @Override
getProcessLimit()5175     public int getProcessLimit() {
5176         synchronized (this) {
5177             return mConstants.getOverrideMaxCachedProcesses();
5178         }
5179     }
5180 
importanceTokenDied(ImportanceToken token)5181     void importanceTokenDied(ImportanceToken token) {
5182         synchronized (ActivityManagerService.this) {
5183             ProcessRecord pr = null;
5184             synchronized (mPidsSelfLocked) {
5185                 ImportanceToken cur
5186                     = mImportantProcesses.get(token.pid);
5187                 if (cur != token) {
5188                     return;
5189                 }
5190                 mImportantProcesses.remove(token.pid);
5191                 pr = mPidsSelfLocked.get(token.pid);
5192                 if (pr == null) {
5193                     return;
5194                 }
5195                 pr.mState.setForcingToImportant(null);
5196                 updateProcessForegroundLocked(pr, false, 0, false);
5197             }
5198             updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5199         }
5200     }
5201 
5202     @Override
setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5203     public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
5204         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5205                 "setProcessImportant()");
5206         synchronized(this) {
5207             boolean changed = false;
5208 
5209             ProcessRecord pr = null;
5210             synchronized (mPidsSelfLocked) {
5211                 pr = mPidsSelfLocked.get(pid);
5212                 if (pr == null && isForeground) {
5213                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5214                     return;
5215                 }
5216                 ImportanceToken oldToken = mImportantProcesses.get(pid);
5217                 if (oldToken != null) {
5218                     oldToken.token.unlinkToDeath(oldToken, 0);
5219                     mImportantProcesses.remove(pid);
5220                     if (pr != null) {
5221                         pr.mState.setForcingToImportant(null);
5222                     }
5223                     changed = true;
5224                 }
5225                 if (isForeground && token != null) {
5226                     ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
5227                         @Override
5228                         public void binderDied() {
5229                             importanceTokenDied(this);
5230                         }
5231                     };
5232                     try {
5233                         token.linkToDeath(newToken, 0);
5234                         mImportantProcesses.put(pid, newToken);
5235                         pr.mState.setForcingToImportant(newToken);
5236                         changed = true;
5237                     } catch (RemoteException e) {
5238                         // If the process died while doing this, we will later
5239                         // do the cleanup with the process death link.
5240                     }
5241                 }
5242             }
5243 
5244             if (changed) {
5245                 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5246             }
5247         }
5248     }
5249 
isAppForeground(int uid)5250     private boolean isAppForeground(int uid) {
5251         synchronized (mProcLock) {
5252             UidRecord uidRec = mProcessList.mActiveUids.get(uid);
5253             if (uidRec == null || uidRec.isIdle()) {
5254                 return false;
5255             }
5256             return uidRec.getCurProcState() <= PROCESS_STATE_IMPORTANT_FOREGROUND;
5257         }
5258     }
5259 
isAppBad(final String processName, final int uid)5260     private boolean isAppBad(final String processName, final int uid) {
5261         return mAppErrors.isBadProcess(processName, uid);
5262     }
5263 
5264     // NOTE: this is an internal method used by the OnShellCommand implementation only and should
5265     // be guarded by permission checking.
getUidState(int uid)5266     int getUidState(int uid) {
5267         synchronized (mProcLock) {
5268             return mProcessList.getUidProcStateLOSP(uid);
5269         }
5270     }
5271 
5272     @GuardedBy("this")
getUidStateLocked(int uid)5273     int getUidStateLocked(int uid) {
5274         return mProcessList.getUidProcStateLOSP(uid);
5275     }
5276 
5277     // =========================================================
5278     // PROCESS INFO
5279     // =========================================================
5280 
5281     static class ProcessInfoService extends IProcessInfoService.Stub {
5282         final ActivityManagerService mActivityManagerService;
ProcessInfoService(ActivityManagerService activityManagerService)5283         ProcessInfoService(ActivityManagerService activityManagerService) {
5284             mActivityManagerService = activityManagerService;
5285         }
5286 
5287         @Override
getProcessStatesFromPids( int[] pids, int[] states)5288         public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
5289             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5290                     /*in*/ pids, /*out*/ states, null);
5291         }
5292 
5293         @Override
getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5294         public void getProcessStatesAndOomScoresFromPids(
5295                 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5296             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5297                     /*in*/ pids, /*out*/ states, /*out*/ scores);
5298         }
5299     }
5300 
5301     /**
5302      * For each PID in the given input array, write the current process state
5303      * for that process into the states array, or -1 to indicate that no
5304      * process with the given PID exists. If scores array is provided, write
5305      * the oom score for the process into the scores array, with INVALID_ADJ
5306      * indicating the PID doesn't exist.
5307      */
getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5308     public void getProcessStatesAndOomScoresForPIDs(
5309             /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5310         if (scores != null) {
5311             enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
5312                     "getProcessStatesAndOomScoresForPIDs()");
5313         }
5314 
5315         if (pids == null) {
5316             throw new NullPointerException("pids");
5317         } else if (states == null) {
5318             throw new NullPointerException("states");
5319         } else if (pids.length != states.length) {
5320             throw new IllegalArgumentException("pids and states arrays have different lengths!");
5321         } else if (scores != null && pids.length != scores.length) {
5322             throw new IllegalArgumentException("pids and scores arrays have different lengths!");
5323         }
5324 
5325         synchronized (mProcLock) {
5326             synchronized (mPidsSelfLocked) {
5327                 for (int i = 0; i < pids.length; i++) {
5328                     ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
5329                     if (pr != null) {
5330                         final boolean isPendingTop =
5331                                 mPendingStartActivityUids.isPendingTopPid(pr.uid, pids[i]);
5332                         states[i] = isPendingTop ? PROCESS_STATE_TOP : pr.mState.getCurProcState();
5333                         if (scores != null) {
5334                             scores[i] = isPendingTop
5335                                     ? (ProcessList.FOREGROUND_APP_ADJ - 1) : pr.mState.getCurAdj();
5336                         }
5337                     } else {
5338                         states[i] = PROCESS_STATE_NONEXISTENT;
5339                         if (scores != null) {
5340                             scores[i] = ProcessList.INVALID_ADJ;
5341                         }
5342                     }
5343                 }
5344             }
5345         }
5346     }
5347 
5348     // =========================================================
5349     // PERMISSIONS
5350     // =========================================================
5351 
5352     static class PermissionController extends IPermissionController.Stub {
5353         ActivityManagerService mActivityManagerService;
PermissionController(ActivityManagerService activityManagerService)5354         PermissionController(ActivityManagerService activityManagerService) {
5355             mActivityManagerService = activityManagerService;
5356         }
5357 
5358         @Override
checkPermission(String permission, int pid, int uid)5359         public boolean checkPermission(String permission, int pid, int uid) {
5360             return mActivityManagerService.checkPermission(permission, pid,
5361                     uid) == PackageManager.PERMISSION_GRANTED;
5362         }
5363 
5364         @Override
noteOp(String op, int uid, String packageName)5365         public int noteOp(String op, int uid, String packageName) {
5366             // TODO moltmann: Allow to specify featureId
5367             return mActivityManagerService.mAppOpsService
5368                     .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null,
5369                             false, "", false).getOpMode();
5370         }
5371 
5372         @Override
getPackagesForUid(int uid)5373         public String[] getPackagesForUid(int uid) {
5374             return mActivityManagerService.mContext.getPackageManager()
5375                     .getPackagesForUid(uid);
5376         }
5377 
5378         @Override
isRuntimePermission(String permission)5379         public boolean isRuntimePermission(String permission) {
5380             try {
5381                 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
5382                         .getPermissionInfo(permission, 0);
5383                 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
5384                         == PermissionInfo.PROTECTION_DANGEROUS;
5385             } catch (NameNotFoundException nnfe) {
5386                 Slog.e(TAG, "No such permission: "+ permission, nnfe);
5387             }
5388             return false;
5389         }
5390 
5391         @Override
getPackageUid(String packageName, int flags)5392         public int getPackageUid(String packageName, int flags) {
5393             try {
5394                 return mActivityManagerService.mContext.getPackageManager()
5395                         .getPackageUid(packageName, flags);
5396             } catch (NameNotFoundException nnfe) {
5397                 return -1;
5398             }
5399         }
5400     }
5401 
5402     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
5403         @Override
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5404         public int checkComponentPermission(String permission, int pid, int uid,
5405                 int owningUid, boolean exported) {
5406             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
5407                     owningUid, exported);
5408         }
5409 
5410         @Override
getAMSLock()5411         public Object getAMSLock() {
5412             return ActivityManagerService.this;
5413         }
5414     }
5415 
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5416     public static int checkComponentPermission(String permission, int pid, int uid,
5417             int owningUid, boolean exported) {
5418         if (pid == MY_PID) {
5419             return PackageManager.PERMISSION_GRANTED;
5420         }
5421         // If there is an explicit permission being checked, and this is coming from a process
5422         // that has been denied access to that permission, then just deny.  Ultimately this may
5423         // not be quite right -- it means that even if the caller would have access for another
5424         // reason (such as being the owner of the component it is trying to access), it would still
5425         // fail.  This also means the system and root uids would be able to deny themselves
5426         // access to permissions, which...  well okay. ¯\_(ツ)_/¯
5427         if (permission != null) {
5428             synchronized (sActiveProcessInfoSelfLocked) {
5429                 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid);
5430                 if (procInfo != null && procInfo.deniedPermissions != null
5431                         && procInfo.deniedPermissions.contains(permission)) {
5432                     return PackageManager.PERMISSION_DENIED;
5433                 }
5434             }
5435         }
5436         return ActivityManager.checkComponentPermission(permission, uid,
5437                 owningUid, exported);
5438     }
5439 
5440     /**
5441      * As the only public entry point for permissions checking, this method
5442      * can enforce the semantic that requesting a check on a null global
5443      * permission is automatically denied.  (Internally a null permission
5444      * string is used when calling {@link #checkComponentPermission} in cases
5445      * when only uid-based security is needed.)
5446      *
5447      * This can be called with or without the global lock held.
5448      */
5449     @Override
checkPermission(String permission, int pid, int uid)5450     public int checkPermission(String permission, int pid, int uid) {
5451         if (permission == null) {
5452             return PackageManager.PERMISSION_DENIED;
5453         }
5454         return checkComponentPermission(permission, pid, uid, -1, true);
5455     }
5456 
5457     /**
5458      * Binder IPC calls go through the public entry point.
5459      * This can be called with or without the global lock held.
5460      */
checkCallingPermission(String permission)5461     int checkCallingPermission(String permission) {
5462         return checkPermission(permission,
5463                 Binder.getCallingPid(),
5464                 Binder.getCallingUid());
5465     }
5466 
5467     /**
5468      * This can be called with or without the global lock held.
5469      */
enforceCallingPermission(String permission, String func)5470     void enforceCallingPermission(String permission, String func) {
5471         if (checkCallingPermission(permission)
5472                 == PackageManager.PERMISSION_GRANTED) {
5473             return;
5474         }
5475 
5476         String msg = "Permission Denial: " + func + " from pid="
5477                 + Binder.getCallingPid()
5478                 + ", uid=" + Binder.getCallingUid()
5479                 + " requires " + permission;
5480         Slog.w(TAG, msg);
5481         throw new SecurityException(msg);
5482     }
5483 
5484     /**
5485      * This can be called with or without the global lock held.
5486      */
enforcePermission(String permission, int pid, int uid, String func)5487     void enforcePermission(String permission, int pid, int uid, String func) {
5488         if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) {
5489             return;
5490         }
5491 
5492         String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid
5493                 + " requires " + permission;
5494         Slog.w(TAG, msg);
5495         throw new SecurityException(msg);
5496     }
5497 
isAppStartModeDisabled(int uid, String packageName)5498     public boolean isAppStartModeDisabled(int uid, String packageName) {
5499         synchronized (mProcLock) {
5500             return getAppStartModeLOSP(uid, packageName, 0, -1, false, true, false)
5501                     == ActivityManager.APP_START_MODE_DISABLED;
5502         }
5503     }
5504 
isInRestrictedBucket(int userId, String packageName, long nowElapsed)5505     private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) {
5506         return UsageStatsManager.STANDBY_BUCKET_RESTRICTED
5507                 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed);
5508     }
5509 
5510     // Unified app-op and target sdk check
5511     @GuardedBy(anyOf = {"this", "mProcLock"})
appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)5512     int appRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
5513         // Apps that target O+ are always subject to background check
5514         if (packageTargetSdk >= Build.VERSION_CODES.O) {
5515             if (DEBUG_BACKGROUND_CHECK) {
5516                 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
5517             }
5518             return ActivityManager.APP_START_MODE_DELAYED_RIGID;
5519         }
5520         // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery.
5521         if (mOnBattery // Short-circuit in common case.
5522                 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS
5523                 && isInRestrictedBucket(
5524                         UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) {
5525             if (DEBUG_BACKGROUND_CHECK) {
5526                 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket");
5527             }
5528             return ActivityManager.APP_START_MODE_DELAYED;
5529         }
5530         // Not in the RESTRICTED bucket so policy is based on AppOp check.
5531         int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND,
5532                 uid, packageName, null, "");
5533         if (DEBUG_BACKGROUND_CHECK) {
5534             Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
5535         }
5536         switch (appop) {
5537             case AppOpsManager.MODE_ALLOWED:
5538                 // If force-background-check is enabled, restrict all apps that aren't allowlisted.
5539                 if (mForceBackgroundCheck &&
5540                         !UserHandle.isCore(uid) &&
5541                         !isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ true)) {
5542                     if (DEBUG_BACKGROUND_CHECK) {
5543                         Slog.i(TAG, "Force background check: " +
5544                                 uid + "/" + packageName + " restricted");
5545                     }
5546                     return ActivityManager.APP_START_MODE_DELAYED;
5547                 }
5548                 return ActivityManager.APP_START_MODE_NORMAL;
5549             case AppOpsManager.MODE_IGNORED:
5550                 return ActivityManager.APP_START_MODE_DELAYED;
5551             default:
5552                 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
5553         }
5554     }
5555 
5556     // Service launch is available to apps with run-in-background exemptions but
5557     // some other background operations are not.  If we're doing a check
5558     // of service-launch policy, allow those callers to proceed unrestricted.
5559     @GuardedBy(anyOf = {"this", "mProcLock"})
appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk)5560     int appServicesRestrictedInBackgroundLOSP(int uid, String packageName, int packageTargetSdk) {
5561         // Persistent app?
5562         if (mPackageManagerInt.isPackagePersistent(packageName)) {
5563             if (DEBUG_BACKGROUND_CHECK) {
5564                 Slog.i(TAG, "App " + uid + "/" + packageName
5565                         + " is persistent; not restricted in background");
5566             }
5567             return ActivityManager.APP_START_MODE_NORMAL;
5568         }
5569 
5570         // Non-persistent but background whitelisted?
5571         if (uidOnBackgroundAllowlistLOSP(uid)) {
5572             if (DEBUG_BACKGROUND_CHECK) {
5573                 Slog.i(TAG, "App " + uid + "/" + packageName
5574                         + " on background allowlist; not restricted in background");
5575             }
5576             return ActivityManager.APP_START_MODE_NORMAL;
5577         }
5578 
5579         // Is this app on the battery whitelist?
5580         if (isOnDeviceIdleAllowlistLOSP(uid, /*allowExceptIdleToo=*/ false)) {
5581             if (DEBUG_BACKGROUND_CHECK) {
5582                 Slog.i(TAG, "App " + uid + "/" + packageName
5583                         + " on idle allowlist; not restricted in background");
5584             }
5585             return ActivityManager.APP_START_MODE_NORMAL;
5586         }
5587 
5588         // None of the service-policy criteria apply, so we apply the common criteria
5589         return appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk);
5590     }
5591 
5592     @GuardedBy(anyOf = {"this", "mProcLock"})
getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)5593     int getAppStartModeLOSP(int uid, String packageName, int packageTargetSdk,
5594             int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) {
5595         if (mInternal.isPendingTopUid(uid)) {
5596             return ActivityManager.APP_START_MODE_NORMAL;
5597         }
5598         UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
5599         if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
5600                 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
5601                 + (uidRec != null ? uidRec.isIdle() : false));
5602         if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.isIdle()) {
5603             boolean ephemeral;
5604             if (uidRec == null) {
5605                 ephemeral = getPackageManagerInternal().isPackageEphemeral(
5606                         UserHandle.getUserId(uid), packageName);
5607             } else {
5608                 ephemeral = uidRec.isEphemeral();
5609             }
5610 
5611             if (ephemeral) {
5612                 // We are hard-core about ephemeral apps not running in the background.
5613                 return ActivityManager.APP_START_MODE_DISABLED;
5614             } else {
5615                 if (disabledOnly) {
5616                     // The caller is only interested in whether app starts are completely
5617                     // disabled for the given package (that is, it is an instant app).  So
5618                     // we don't need to go further, which is all just seeing if we should
5619                     // apply a "delayed" mode for a regular app.
5620                     return ActivityManager.APP_START_MODE_NORMAL;
5621                 }
5622                 final int startMode = (alwaysRestrict)
5623                         ? appRestrictedInBackgroundLOSP(uid, packageName, packageTargetSdk)
5624                         : appServicesRestrictedInBackgroundLOSP(uid, packageName,
5625                                 packageTargetSdk);
5626                 if (DEBUG_BACKGROUND_CHECK) {
5627                     Slog.d(TAG, "checkAllowBackground: uid=" + uid
5628                             + " pkg=" + packageName + " startMode=" + startMode
5629                             + " onallowlist=" + isOnDeviceIdleAllowlistLOSP(uid, false)
5630                             + " onallowlist(ei)=" + isOnDeviceIdleAllowlistLOSP(uid, true));
5631                 }
5632                 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
5633                     // This is an old app that has been forced into a "compatible as possible"
5634                     // mode of background check.  To increase compatibility, we will allow other
5635                     // foreground apps to cause its services to start.
5636                     if (callingPid >= 0) {
5637                         ProcessRecord proc;
5638                         synchronized (mPidsSelfLocked) {
5639                             proc = mPidsSelfLocked.get(callingPid);
5640                         }
5641                         if (proc != null && !ActivityManager.isProcStateBackground(
5642                                 proc.mState.getCurProcState())) {
5643                             // Whoever is instigating this is in the foreground, so we will allow it
5644                             // to go through.
5645                             return ActivityManager.APP_START_MODE_NORMAL;
5646                         }
5647                     }
5648                 }
5649                 return startMode;
5650             }
5651         }
5652         return ActivityManager.APP_START_MODE_NORMAL;
5653     }
5654 
5655     /**
5656      * @return whether a UID is in the system, user or temp doze allowlist.
5657      */
5658     @GuardedBy(anyOf = {"this", "mProcLock"})
isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo)5659     boolean isOnDeviceIdleAllowlistLOSP(int uid, boolean allowExceptIdleToo) {
5660         final int appId = UserHandle.getAppId(uid);
5661 
5662         final int[] allowlist = allowExceptIdleToo
5663                 ? mDeviceIdleExceptIdleAllowlist
5664                 : mDeviceIdleAllowlist;
5665 
5666         return Arrays.binarySearch(allowlist, appId) >= 0
5667                 || Arrays.binarySearch(mDeviceIdleTempAllowlist, appId) >= 0
5668                 || mPendingTempAllowlist.indexOfKey(uid) >= 0;
5669     }
5670 
5671     /**
5672      * Is the uid allowlisted to start FGS?
5673      * @param uid
5674      * @return a TempAllowListEntry if the uid is allowed.
5675      *         null if the uid is not allowed.
5676      */
5677     @Nullable
5678     @GuardedBy(anyOf = {"this", "mProcLock"})
isAllowlistedForFgsStartLOSP(int uid)5679     FgsTempAllowListItem isAllowlistedForFgsStartLOSP(int uid) {
5680         if (Arrays.binarySearch(mDeviceIdleExceptIdleAllowlist, UserHandle.getAppId(uid)) >= 0) {
5681             return FAKE_TEMP_ALLOW_LIST_ITEM;
5682         }
5683         final Pair<Long, FgsTempAllowListItem> entry = mFgsStartTempAllowList.get(uid);
5684         return entry == null ? null : entry.second;
5685     }
5686 
5687     /**
5688      * @return allowlist tag for a uid from mPendingTempAllowlist, null if not currently on
5689      * the allowlist
5690      */
5691     @GuardedBy(anyOf = {"this", "mProcLock"})
getPendingTempAllowlistTagForUidLOSP(int uid)5692     String getPendingTempAllowlistTagForUidLOSP(int uid) {
5693         final PendingTempAllowlist ptw = mPendingTempAllowlist.get(uid);
5694         return ptw != null ? ptw.tag : null;
5695     }
5696 
5697     @VisibleForTesting
grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)5698     public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) {
5699         getPackageManagerInternal()
5700                 .grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/);
5701     }
5702 
5703     /**
5704      * @param uri This uri must NOT contain an embedded userId.
5705      * @param userId The userId in which the uri is to be resolved.
5706      */
5707     @Override
checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)5708     public int checkUriPermission(Uri uri, int pid, int uid,
5709             final int modeFlags, int userId, IBinder callerToken) {
5710         enforceNotIsolatedCaller("checkUriPermission");
5711 
5712         // Our own process gets to do everything.
5713         if (pid == MY_PID) {
5714             return PackageManager.PERMISSION_GRANTED;
5715         }
5716         return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, modeFlags)
5717                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
5718     }
5719 
5720     @Override
checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, final int modeFlags, IBinder callerToken)5721     public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid,
5722             final int modeFlags, IBinder callerToken) {
5723         final int size = uris.size();
5724         int[] res = new int[size];
5725         // Default value DENIED.
5726         Arrays.fill(res, PackageManager.PERMISSION_DENIED);
5727 
5728         for (int i = 0; i < size; i++) {
5729             final Uri uri = uris.get(i);
5730             final int userId = ContentProvider.getUserIdFromUri(uri, mContext.getUserId());
5731             res[i] = checkUriPermission(ContentProvider.getUriWithoutUserId(uri), pid, uid,
5732                     modeFlags, userId, callerToken);
5733         }
5734         return res;
5735     }
5736 
5737     /**
5738      * @param uri This uri must NOT contain an embedded userId.
5739      * @param userId The userId in which the uri is to be resolved.
5740      */
5741     @Override
grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)5742     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
5743             final int modeFlags, int userId) {
5744         enforceNotIsolatedCaller("grantUriPermission");
5745         GrantUri grantUri = new GrantUri(userId, uri, modeFlags);
5746         synchronized (this) {
5747             final ProcessRecord r = getRecordForAppLOSP(caller);
5748             if (r == null) {
5749                 throw new SecurityException("Unable to find app for caller "
5750                         + caller
5751                         + " when granting permission to uri " + grantUri);
5752             }
5753             if (targetPkg == null) {
5754                 throw new IllegalArgumentException("null target");
5755             }
5756 
5757             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
5758                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
5759                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
5760                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
5761 
5762             final Intent intent = new Intent();
5763             intent.setData(uri);
5764             intent.setFlags(modeFlags);
5765 
5766             final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent,
5767                     r.uid, targetPkg, UserHandle.getUserId(r.uid));
5768             mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null);
5769         }
5770     }
5771 
5772     /**
5773      * @param uri This uri must NOT contain an embedded userId.
5774      * @param userId The userId in which the uri is to be resolved.
5775      */
5776     @Override
revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)5777     public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
5778             final int modeFlags, int userId) {
5779         enforceNotIsolatedCaller("revokeUriPermission");
5780         synchronized (this) {
5781             final ProcessRecord r = getRecordForAppLOSP(caller);
5782             if (r == null) {
5783                 throw new SecurityException("Unable to find app for caller "
5784                         + caller
5785                         + " when revoking permission to uri " + uri);
5786             }
5787             if (uri == null) {
5788                 Slog.w(TAG, "revokeUriPermission: null uri");
5789                 return;
5790             }
5791 
5792             if (!Intent.isAccessUriMode(modeFlags)) {
5793                 return;
5794             }
5795 
5796             final String authority = uri.getAuthority();
5797             final ProviderInfo pi = mCpHelper.getProviderInfoLocked(authority, userId,
5798                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
5799             if (pi == null) {
5800                 Slog.w(TAG, "No content provider found for permission revoke: "
5801                         + uri.toSafeString());
5802                 return;
5803             }
5804 
5805             mUgmInternal.revokeUriPermission(targetPackage, r.uid,
5806                     new GrantUri(userId, uri, modeFlags), modeFlags);
5807         }
5808     }
5809 
5810     @Override
showWaitingForDebugger(IApplicationThread who, boolean waiting)5811     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5812         synchronized (mProcLock) {
5813             final ProcessRecord app = who != null ? getRecordForAppLOSP(who) : null;
5814             if (app == null) return;
5815 
5816             Message msg = Message.obtain();
5817             msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
5818             msg.obj = app;
5819             msg.arg1 = waiting ? 1 : 0;
5820             mUiHandler.sendMessage(msg);
5821         }
5822     }
5823 
5824     @Override
getMemoryInfo(ActivityManager.MemoryInfo outInfo)5825     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
5826         mProcessList.getMemoryInfo(outInfo);
5827     }
5828 
5829     // =========================================================
5830     // TASK MANAGEMENT
5831     // =========================================================
5832 
5833     @Override
getTasks(int maxNum)5834     public List<RunningTaskInfo> getTasks(int maxNum) {
5835         return mActivityTaskManager.getTasks(maxNum);
5836     }
5837 
5838     @Override
cancelTaskWindowTransition(int taskId)5839     public void cancelTaskWindowTransition(int taskId) {
5840         mActivityTaskManager.cancelTaskWindowTransition(taskId);
5841     }
5842 
5843     @Override
setTaskResizeable(int taskId, int resizeableMode)5844     public void setTaskResizeable(int taskId, int resizeableMode) {
5845         mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);
5846     }
5847 
5848     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)5849     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
5850         mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);
5851     }
5852 
5853     @Override
getTaskBounds(int taskId)5854     public Rect getTaskBounds(int taskId) {
5855         return mActivityTaskManager.getTaskBounds(taskId);
5856     }
5857 
5858     @Override
removeTask(int taskId)5859     public boolean removeTask(int taskId) {
5860         return mActivityTaskManager.removeTask(taskId);
5861     }
5862 
5863     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)5864     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
5865             int flags, Bundle bOptions) {
5866         mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);
5867     }
5868 
5869     /**
5870      * Attempts to move a task backwards in z-order (the order of activities within the task is
5871      * unchanged).
5872      *
5873      * There are several possible results of this call:
5874      * - if the task is locked, then we will show the lock toast
5875      * - if there is a task behind the provided task, then that task is made visible and resumed as
5876      *   this task is moved to the back
5877      * - otherwise, if there are no other tasks in the stack:
5878      *     - if this task is in the pinned stack, then we remove the stack completely, which will
5879      *       have the effect of moving the task to the top or bottom of the fullscreen stack
5880      *       (depending on whether it is visible)
5881      *     - otherwise, we simply return home and hide this task
5882      *
5883      * @param token A reference to the activity we wish to move
5884      * @param nonRoot If false then this only works if the activity is the root
5885      *                of a task; if true it will work for any activity in a task.
5886      * @return Returns true if the move completed, false if not.
5887      */
5888     @Override
moveActivityTaskToBack(IBinder token, boolean nonRoot)5889     public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
5890         return ActivityClient.getInstance().moveActivityTaskToBack(token, nonRoot);
5891     }
5892 
5893     @Override
moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop)5894     public void moveTaskToRootTask(int taskId, int rootTaskId, boolean toTop) {
5895         mActivityTaskManager.moveTaskToRootTask(taskId, rootTaskId, toTop);
5896     }
5897 
5898     @Override
getRecentTasks(int maxNum, int flags, int userId)5899     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
5900             int userId) {
5901         return mActivityTaskManager.getRecentTasks(maxNum, flags, userId);
5902     }
5903 
5904     @Override
getAllRootTaskInfos()5905     public List<RootTaskInfo> getAllRootTaskInfos() {
5906         return mActivityTaskManager.getAllRootTaskInfos();
5907     }
5908 
5909     @Override
getTaskForActivity(IBinder token, boolean onlyRoot)5910     public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5911         return ActivityClient.getInstance().getTaskForActivity(token, onlyRoot);
5912     }
5913 
5914     @Override
updateDeviceOwner(String packageName)5915     public void updateDeviceOwner(String packageName) {
5916         final int callingUid = Binder.getCallingUid();
5917         if (callingUid != 0 && callingUid != SYSTEM_UID) {
5918             throw new SecurityException("updateDeviceOwner called from non-system process");
5919         }
5920         synchronized (this) {
5921             mDeviceOwnerName = packageName;
5922         }
5923     }
5924 
5925     @Override
updateLockTaskPackages(int userId, String[] packages)5926     public void updateLockTaskPackages(int userId, String[] packages) {
5927         mActivityTaskManager.updateLockTaskPackages(userId, packages);
5928     }
5929 
5930     @Override
isInLockTaskMode()5931     public boolean isInLockTaskMode() {
5932         return mActivityTaskManager.isInLockTaskMode();
5933     }
5934 
5935     @Override
getLockTaskModeState()5936     public int getLockTaskModeState() {
5937         return mActivityTaskManager.getLockTaskModeState();
5938     }
5939 
5940     @Override
startSystemLockTaskMode(int taskId)5941     public void startSystemLockTaskMode(int taskId) throws RemoteException {
5942         mActivityTaskManager.startSystemLockTaskMode(taskId);
5943     }
5944 
5945     /**
5946      * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The
5947      * PackageManager could be unavailable at construction time and therefore needs to be accessed
5948      * on demand.
5949      */
5950     @VisibleForTesting
getPackageManager()5951     public IPackageManager getPackageManager() {
5952         return AppGlobals.getPackageManager();
5953     }
5954 
5955     @VisibleForTesting
getPackageManagerInternal()5956     public PackageManagerInternal getPackageManagerInternal() {
5957         // Intentionally hold no locks: in case of race conditions, the mPackageManagerInt will
5958         // be set to the same value anyway.
5959         if (mPackageManagerInt == null) {
5960             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
5961         }
5962         return mPackageManagerInt;
5963     }
5964 
getPermissionManagerInternal()5965     private PermissionManagerServiceInternal getPermissionManagerInternal() {
5966         // Intentionally hold no locks: in case of race conditions, the mPermissionManagerInt will
5967         // be set to the same value anyway.
5968         if (mPermissionManagerInt == null) {
5969             mPermissionManagerInt =
5970                     LocalServices.getService(PermissionManagerServiceInternal.class);
5971         }
5972         return mPermissionManagerInt;
5973     }
5974 
getTestUtilityServiceLocked()5975     private TestUtilityService getTestUtilityServiceLocked() {
5976         if (mTestUtilityService == null) {
5977             mTestUtilityService =
5978                     LocalServices.getService(TestUtilityService.class);
5979         }
5980         return mTestUtilityService;
5981     }
5982 
5983     @Override
appNotResponding(final String reason)5984     public void appNotResponding(final String reason) {
5985         final int callingPid = Binder.getCallingPid();
5986 
5987         synchronized (mPidsSelfLocked) {
5988             final ProcessRecord app = mPidsSelfLocked.get(callingPid);
5989             if (app == null) {
5990                 throw new SecurityException("Unknown process: " + callingPid);
5991             }
5992 
5993             mAnrHelper.appNotResponding(app, null, app.info, null, null, false,
5994                     "App requested: " + reason);
5995         }
5996     }
5997 
startPersistentApps(int matchFlags)5998     void startPersistentApps(int matchFlags) {
5999         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
6000 
6001         synchronized (this) {
6002             try {
6003                 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
6004                         .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
6005                 for (ApplicationInfo app : apps) {
6006                     if (!"android".equals(app.packageName)) {
6007                         addAppLocked(app, null, false, null /* ABI override */,
6008                                 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
6009                     }
6010                 }
6011             } catch (RemoteException ex) {
6012             }
6013         }
6014     }
6015 
6016     // =========================================================
6017     // CONTENT PROVIDERS
6018     // =========================================================
6019 
getContentProviderHelper()6020     public ContentProviderHelper getContentProviderHelper() {
6021         return mCpHelper;
6022     }
6023 
6024     @Override
getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)6025     public final ContentProviderHolder getContentProvider(
6026             IApplicationThread caller, String callingPackage, String name, int userId,
6027             boolean stable) {
6028         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProvider: ", name);
6029         try {
6030             return mCpHelper.getContentProvider(caller, callingPackage, name, userId, stable);
6031         } finally {
6032             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6033         }
6034     }
6035 
6036     @Override
getContentProviderExternal( String name, int userId, IBinder token, String tag)6037     public ContentProviderHolder getContentProviderExternal(
6038             String name, int userId, IBinder token, String tag) {
6039         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "getContentProviderExternal: ", name);
6040         try {
6041             return mCpHelper.getContentProviderExternal(name, userId, token, tag);
6042         } finally {
6043             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6044         }
6045     }
6046 
6047     /**
6048      * Drop a content provider from a ProcessRecord's bookkeeping
6049      */
6050     @Override
removeContentProvider(IBinder connection, boolean stable)6051     public void removeContentProvider(IBinder connection, boolean stable) {
6052         mCpHelper.removeContentProvider(connection, stable);
6053     }
6054 
6055     /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */
6056     @Deprecated
6057     @Override
removeContentProviderExternal(String name, IBinder token)6058     public void removeContentProviderExternal(String name, IBinder token) {
6059         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternal: ", name);
6060         try {
6061             removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId());
6062         } finally {
6063             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6064         }
6065     }
6066 
6067     @Override
removeContentProviderExternalAsUser(String name, IBinder token, int userId)6068     public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) {
6069         traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "removeContentProviderExternalAsUser: ", name);
6070         try {
6071             mCpHelper.removeContentProviderExternalAsUser(name, token, userId);
6072         } finally {
6073             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6074         }
6075     }
6076 
6077     @Override
publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)6078     public final void publishContentProviders(IApplicationThread caller,
6079             List<ContentProviderHolder> providers) {
6080         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
6081             final int maxLength = 256;
6082             final StringBuilder sb = new StringBuilder(maxLength);
6083             sb.append("publishContentProviders: ");
6084             if (providers != null) {
6085                 boolean first = true;
6086                 for (int i = 0, size = providers.size(); i < size; i++) {
6087                     final ContentProviderHolder holder = providers.get(i);
6088                     if (holder != null && holder.info != null && holder.info.authority != null) {
6089                         final int len = holder.info.authority.length();
6090                         if (sb.length() + len > maxLength) {
6091                             sb.append("[[TRUNCATED]]");
6092                             break;
6093                         }
6094                         if (!first) {
6095                             sb.append(';');
6096                         } else {
6097                             first = false;
6098                         }
6099                         sb.append(holder.info.authority);
6100                     }
6101                 }
6102             }
6103             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, sb.toString());
6104         }
6105         try {
6106             mCpHelper.publishContentProviders(caller, providers);
6107         } finally {
6108             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6109         }
6110     }
6111 
6112     @Override
refContentProvider(IBinder connection, int stable, int unstable)6113     public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6114         return mCpHelper.refContentProvider(connection, stable, unstable);
6115     }
6116 
6117     @Override
unstableProviderDied(IBinder connection)6118     public void unstableProviderDied(IBinder connection) {
6119         mCpHelper.unstableProviderDied(connection);
6120     }
6121 
6122     @Override
appNotRespondingViaProvider(IBinder connection)6123     public void appNotRespondingViaProvider(IBinder connection) {
6124         mCpHelper.appNotRespondingViaProvider(connection);
6125     }
6126 
6127     /**
6128      * Allows apps to retrieve the MIME type of a URI.
6129      * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
6130      * users, then it does not need permission to access the ContentProvider.
6131      * Either, it needs cross-user uri grants.
6132      *
6133      * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6134      *
6135      * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6136      *     src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6137      *
6138      * @deprecated -- use getProviderMimeTypeAsync.
6139      */
6140     @Deprecated
6141     @Override
getProviderMimeType(Uri uri, int userId)6142     public String getProviderMimeType(Uri uri, int userId) {
6143         return mCpHelper.getProviderMimeType(uri, userId);
6144     }
6145 
6146     /**
6147      * Allows apps to retrieve the MIME type of a URI.
6148      * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
6149      * users, then it does not need permission to access the ContentProvider.
6150      * Either way, it needs cross-user uri grants.
6151      */
6152     @Override
getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback)6153     public void getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback) {
6154         mCpHelper.getProviderMimeTypeAsync(uri, userId, resultCallback);
6155     }
6156 
6157     // =========================================================
6158     // GLOBAL MANAGEMENT
6159     // =========================================================
6160 
6161     @GuardedBy(anyOf = {"this", "mProcLock"})
uidOnBackgroundAllowlistLOSP(final int uid)6162     private boolean uidOnBackgroundAllowlistLOSP(final int uid) {
6163         final int appId = UserHandle.getAppId(uid);
6164         final int[] allowlist = mBackgroundAppIdAllowlist;
6165         for (int i = 0, len = allowlist.length; i < len; i++) {
6166             if (appId == allowlist[i]) {
6167                 return true;
6168             }
6169         }
6170         return false;
6171     }
6172 
6173     @Override
isBackgroundRestricted(String packageName)6174     public boolean isBackgroundRestricted(String packageName) {
6175         final int callingUid = Binder.getCallingUid();
6176         final IPackageManager pm = AppGlobals.getPackageManager();
6177         try {
6178             final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
6179                     UserHandle.getUserId(callingUid));
6180             if (packageUid != callingUid) {
6181                 throw new IllegalArgumentException("Uid " + callingUid
6182                         + " cannot query restriction state for package " + packageName);
6183             }
6184         } catch (RemoteException exc) {
6185             // Ignore.
6186         }
6187         return isBackgroundRestrictedNoCheck(callingUid, packageName);
6188     }
6189 
isBackgroundRestrictedNoCheck(final int uid, final String packageName)6190     boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) {
6191         final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
6192                 uid, packageName);
6193         return mode != AppOpsManager.MODE_ALLOWED;
6194     }
6195 
6196     @Override
backgroundAllowlistUid(final int uid)6197     public void backgroundAllowlistUid(final int uid) {
6198         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
6199             throw new SecurityException("Only the OS may call backgroundAllowlistUid()");
6200         }
6201 
6202         if (DEBUG_BACKGROUND_CHECK) {
6203             Slog.i(TAG, "Adding uid " + uid + " to bg uid allowlist");
6204         }
6205         synchronized (this) {
6206             synchronized (mProcLock) {
6207                 final int num = mBackgroundAppIdAllowlist.length;
6208                 int[] newList = new int[num + 1];
6209                 System.arraycopy(mBackgroundAppIdAllowlist, 0, newList, 0, num);
6210                 newList[num] = UserHandle.getAppId(uid);
6211                 mBackgroundAppIdAllowlist = newList;
6212             }
6213         }
6214     }
6215 
6216     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)6217     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
6218             String abiOverride, int zygotePolicyFlags) {
6219         return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */,
6220                 abiOverride, zygotePolicyFlags);
6221     }
6222 
6223     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags)6224     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
6225             boolean disableHiddenApiChecks, String abiOverride, int zygotePolicyFlags) {
6226         return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks,
6227                 false /* disableTestApiChecks */, abiOverride, zygotePolicyFlags);
6228     }
6229 
6230     // TODO: Move to ProcessList?
6231     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride, int zygotePolicyFlags)6232     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
6233             boolean disableHiddenApiChecks, boolean disableTestApiChecks,
6234             String abiOverride, int zygotePolicyFlags) {
6235         ProcessRecord app;
6236         if (!isolated) {
6237             app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
6238                     info.uid);
6239         } else {
6240             app = null;
6241         }
6242 
6243         if (app == null) {
6244             app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0,
6245                     new HostingRecord("added application",
6246                         customProcess != null ? customProcess : info.processName));
6247             updateLruProcessLocked(app, false, null);
6248             updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
6249         }
6250 
6251         // Report usage as process is persistent and being started.
6252         mUsageStatsService.reportEvent(info.packageName, UserHandle.getUserId(app.uid),
6253                 Event.APP_COMPONENT_USED);
6254 
6255         // This package really, really can not be stopped.
6256         try {
6257             AppGlobals.getPackageManager().setPackageStoppedState(
6258                     info.packageName, false, UserHandle.getUserId(app.uid));
6259         } catch (RemoteException e) {
6260         } catch (IllegalArgumentException e) {
6261             Slog.w(TAG, "Failed trying to unstop package "
6262                     + info.packageName + ": " + e);
6263         }
6264 
6265         if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
6266             app.setPersistent(true);
6267             app.mState.setMaxAdj(ProcessList.PERSISTENT_PROC_ADJ);
6268         }
6269         if (app.getThread() == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6270             mPersistentStartingProcesses.add(app);
6271             mProcessList.startProcessLocked(app, new HostingRecord("added application",
6272                     customProcess != null ? customProcess : app.processName),
6273                     zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks,
6274                     abiOverride);
6275         }
6276 
6277         return app;
6278     }
6279 
unhandledBack()6280     public void unhandledBack() {
6281         mActivityTaskManager.unhandledBack();
6282     }
6283 
6284     // TODO: Move to ContentProviderHelper?
openContentUri(String uriString)6285     public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
6286         enforceNotIsolatedCaller("openContentUri");
6287         final int userId = UserHandle.getCallingUserId();
6288         final Uri uri = Uri.parse(uriString);
6289         String name = uri.getAuthority();
6290         ContentProviderHolder cph = mCpHelper.getContentProviderExternalUnchecked(name, null,
6291                 Binder.getCallingUid(), "*opencontent*", userId);
6292         ParcelFileDescriptor pfd = null;
6293         if (cph != null) {
6294             try {
6295                 // This method is exposed to the VNDK and to avoid changing its
6296                 // signature we just use the first package in the UID. For shared
6297                 // UIDs we may blame the wrong app but that is Okay as they are
6298                 // in the same security/privacy sandbox.
6299                 final int uid = Binder.getCallingUid();
6300                 // Here we handle some of the special UIDs (mediaserver, systemserver, etc)
6301                 final String packageName = AppOpsManager.resolvePackageName(uid,
6302                         /*packageName*/ null);
6303                 final AndroidPackage androidPackage;
6304                 if (packageName != null) {
6305                     androidPackage = mPackageManagerInt.getPackage(packageName);
6306                 } else {
6307                     androidPackage = mPackageManagerInt.getPackage(uid);
6308                 }
6309                 if (androidPackage == null) {
6310                     Log.e(TAG, "Cannot find package for uid: " + uid);
6311                     return null;
6312                 }
6313                 final AttributionSource attributionSource = new AttributionSource(
6314                         Binder.getCallingUid(), androidPackage.getPackageName(), null);
6315                 pfd = cph.provider.openFile(attributionSource, uri, "r", null);
6316             } catch (FileNotFoundException e) {
6317                 // do nothing; pfd will be returned null
6318             } finally {
6319                 // Ensure we're done with the provider.
6320                 mCpHelper.removeContentProviderExternalUnchecked(name, null, userId);
6321             }
6322         } else {
6323             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
6324         }
6325         return pfd;
6326     }
6327 
reportGlobalUsageEvent(int event)6328     void reportGlobalUsageEvent(int event) {
6329         final int currentUserId = mUserController.getCurrentUserId();
6330         mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event);
6331         int[] profiles = mUserController.getCurrentProfileIds();
6332         if (profiles != null) {
6333             for (int i = profiles.length - 1; i >= 0; i--) {
6334                 if (profiles[i] == currentUserId) {
6335                     continue;
6336                 }
6337                 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event);
6338             }
6339         }
6340     }
6341 
reportCurWakefulnessUsageEvent()6342     void reportCurWakefulnessUsageEvent() {
6343         reportGlobalUsageEvent(mWakefulness.get() == PowerManagerInternal.WAKEFULNESS_AWAKE
6344                 ? UsageEvents.Event.SCREEN_INTERACTIVE
6345                 : UsageEvents.Event.SCREEN_NON_INTERACTIVE);
6346     }
6347 
onWakefulnessChanged(int wakefulness)6348     void onWakefulnessChanged(int wakefulness) {
6349         synchronized (this) {
6350             boolean wasAwake = mWakefulness.getAndSet(wakefulness)
6351                     == PowerManagerInternal.WAKEFULNESS_AWAKE;
6352             boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
6353 
6354             if (wasAwake != isAwake) {
6355                 // Also update state in a special way for running foreground services UI.
6356                 mServices.updateScreenStateLocked(isAwake);
6357                 reportCurWakefulnessUsageEvent();
6358                 mActivityTaskManager.onScreenAwakeChanged(isAwake);
6359                 mOomAdjProfiler.onWakefulnessChanged(wakefulness);
6360             }
6361             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
6362         }
6363     }
6364 
6365     @Override
notifyCleartextNetwork(int uid, byte[] firstPacket)6366     public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
6367         mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
6368     }
6369 
6370     @Override
shutdown(int timeout)6371     public boolean shutdown(int timeout) {
6372         if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6373                 != PackageManager.PERMISSION_GRANTED) {
6374             throw new SecurityException("Requires permission "
6375                     + android.Manifest.permission.SHUTDOWN);
6376         }
6377 
6378         final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout);
6379 
6380         mAppOpsService.shutdown();
6381         if (mUsageStatsService != null) {
6382             mUsageStatsService.prepareShutdown();
6383         }
6384         mBatteryStatsService.shutdown();
6385         mProcessStats.shutdown();
6386 
6387         return timedout;
6388     }
6389 
6390     @Override
notifyLockedProfile(@serIdInt int userId)6391     public void notifyLockedProfile(@UserIdInt int userId) {
6392         mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId());
6393     }
6394 
6395     @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)6396     public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
6397         mAtmInternal.startConfirmDeviceCredentialIntent(intent, options);
6398     }
6399 
6400     @Override
stopAppSwitches()6401     public void stopAppSwitches() {
6402         mActivityTaskManager.stopAppSwitches();
6403     }
6404 
6405     @Override
resumeAppSwitches()6406     public void resumeAppSwitches() {
6407         mActivityTaskManager.resumeAppSwitches();
6408     }
6409 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)6410     public void setDebugApp(String packageName, boolean waitForDebugger,
6411             boolean persistent) {
6412         enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6413                 "setDebugApp()");
6414 
6415         final long ident = Binder.clearCallingIdentity();
6416         try {
6417             // Note that this is not really thread safe if there are multiple
6418             // callers into it at the same time, but that's not a situation we
6419             // care about.
6420             if (persistent) {
6421                 final ContentResolver resolver = mContext.getContentResolver();
6422                 Settings.Global.putString(
6423                     resolver, Settings.Global.DEBUG_APP,
6424                     packageName);
6425                 Settings.Global.putInt(
6426                     resolver, Settings.Global.WAIT_FOR_DEBUGGER,
6427                     waitForDebugger ? 1 : 0);
6428             }
6429 
6430             synchronized (this) {
6431                 if (!persistent) {
6432                     mOrigDebugApp = mDebugApp;
6433                     mOrigWaitForDebugger = mWaitForDebugger;
6434                 }
6435                 mDebugApp = packageName;
6436                 mWaitForDebugger = waitForDebugger;
6437                 mDebugTransient = !persistent;
6438                 if (packageName != null) {
6439                     forceStopPackageLocked(packageName, -1, false, false, true, true,
6440                             false, UserHandle.USER_ALL, "set debug app");
6441                 }
6442             }
6443         } finally {
6444             Binder.restoreCallingIdentity(ident);
6445         }
6446     }
6447 
6448     /**
6449      * Set or remove an agent to be run whenever an app with the given process name starts.
6450      *
6451      * This method will not check whether the given process name matches a debuggable app. That
6452      * would require scanning all current packages, and a rescan when new packages are installed
6453      * or updated.
6454      *
6455      * Instead, do the check when an application is started and matched to a stored agent.
6456      *
6457      * @param packageName the process name of the app.
6458      * @param agent the agent string to be used, or null to remove any previously set agent.
6459      */
6460     @Override
setAgentApp(@onNull String packageName, @Nullable String agent)6461     public void setAgentApp(@NonNull String packageName, @Nullable String agent) {
6462         // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
6463         // its own permission.
6464         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
6465                 != PackageManager.PERMISSION_GRANTED) {
6466             throw new SecurityException(
6467                     "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER);
6468         }
6469 
6470         synchronized (mAppProfiler.mProfilerLock) {
6471             mAppProfiler.setAgentAppLPf(packageName, agent);
6472         }
6473     }
6474 
setTrackAllocationApp(ApplicationInfo app, String processName)6475     void setTrackAllocationApp(ApplicationInfo app, String processName) {
6476         if (!Build.IS_DEBUGGABLE) {
6477             if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6478                 throw new SecurityException("Process not debuggable: " + app.packageName);
6479             }
6480         }
6481 
6482         synchronized (mProcLock) {
6483             mTrackAllocationApp = processName;
6484         }
6485     }
6486 
setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)6487     void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) {
6488         synchronized (mAppProfiler.mProfilerLock) {
6489             if (!Build.IS_DEBUGGABLE) {
6490                 boolean isAppDebuggable = (app.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
6491                 boolean isAppProfileable = app.isProfileableByShell();
6492                 if (!isAppDebuggable && !isAppProfileable) {
6493                     throw new SecurityException("Process not debuggable, "
6494                             + "and not profileable by shell: " + app.packageName);
6495                 }
6496             }
6497             mAppProfiler.setProfileAppLPf(processName, profilerInfo);
6498         }
6499     }
6500 
setNativeDebuggingAppLocked(ApplicationInfo app, String processName)6501     void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
6502         if (!Build.IS_DEBUGGABLE) {
6503             if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6504                 throw new SecurityException("Process not debuggable: " + app.packageName);
6505             }
6506         }
6507         mNativeDebuggingApp = processName;
6508     }
6509 
6510     @Override
setAlwaysFinish(boolean enabled)6511     public void setAlwaysFinish(boolean enabled) {
6512         enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6513                 "setAlwaysFinish()");
6514 
6515         final long ident = Binder.clearCallingIdentity();
6516         try {
6517             Settings.Global.putInt(
6518                     mContext.getContentResolver(),
6519                     Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6520 
6521             synchronized (this) {
6522                 mAlwaysFinishActivities = enabled;
6523             }
6524         } finally {
6525             Binder.restoreCallingIdentity(ident);
6526         }
6527     }
6528 
6529     @Override
setActivityController(IActivityController controller, boolean imAMonkey)6530     public void setActivityController(IActivityController controller, boolean imAMonkey) {
6531         if (controller != null) {
6532             Binder.allowBlocking(controller.asBinder());
6533         }
6534         mActivityTaskManager.setActivityController(controller, imAMonkey);
6535     }
6536 
6537     @Override
setUserIsMonkey(boolean userIsMonkey)6538     public void setUserIsMonkey(boolean userIsMonkey) {
6539         synchronized (mProcLock) {
6540             synchronized (mPidsSelfLocked) {
6541                 final int callingPid = Binder.getCallingPid();
6542                 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
6543                 if (proc == null) {
6544                     throw new SecurityException("Unknown process: " + callingPid);
6545                 }
6546                 if (proc.getActiveInstrumentation() == null
6547                         || proc.getActiveInstrumentation().mUiAutomationConnection == null) {
6548                     throw new SecurityException("Only an instrumentation process "
6549                             + "with a UiAutomation can call setUserIsMonkey");
6550                 }
6551             }
6552             mUserIsMonkey = userIsMonkey;
6553         }
6554     }
6555 
6556     @Override
isUserAMonkey()6557     public boolean isUserAMonkey() {
6558         synchronized (mProcLock) {
6559             // If there is a controller also implies the user is a monkey.
6560             return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey();
6561         }
6562     }
6563 
6564     @Override
requestSystemServerHeapDump()6565     public void requestSystemServerHeapDump() {
6566         if (!Build.IS_DEBUGGABLE) {
6567             Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build");
6568             return;
6569         }
6570         if (Binder.getCallingUid() != SYSTEM_UID) {
6571             // This also intentionally excludes secondary profiles from calling this.
6572             throw new SecurityException(
6573                     "Only the system process is allowed to request a system heap dump");
6574         }
6575         ProcessRecord pr;
6576         synchronized (mPidsSelfLocked) {
6577             pr = mPidsSelfLocked.get(myPid());
6578         }
6579         if (pr == null) {
6580             Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid());
6581             return;
6582         }
6583         synchronized (mAppProfiler.mProfilerLock) {
6584             mAppProfiler.startHeapDumpLPf(pr.mProfile, true);
6585         }
6586     }
6587 
6588     /**
6589      * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set
6590      * title and description
6591      */
6592     @Override
requestBugReport(@ugreportParams.BugreportMode int bugreportType)6593     public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) {
6594         requestBugReportWithDescription(null, null, bugreportType);
6595     }
6596 
6597     /**
6598      * Takes a bugreport using bug report API ({@code BugreportManager}) which gets
6599      * triggered by sending a broadcast to Shell.
6600      */
6601     @Override
requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)6602     public void requestBugReportWithDescription(@Nullable String shareTitle,
6603             @Nullable String shareDescription, int bugreportType) {
6604         String type = null;
6605         switch (bugreportType) {
6606             case BugreportParams.BUGREPORT_MODE_FULL:
6607                 type = "bugreportfull";
6608                 break;
6609             case BugreportParams.BUGREPORT_MODE_INTERACTIVE:
6610                 type = "bugreportplus";
6611                 break;
6612             case BugreportParams.BUGREPORT_MODE_REMOTE:
6613                 type = "bugreportremote";
6614                 break;
6615             case BugreportParams.BUGREPORT_MODE_WEAR:
6616                 type = "bugreportwear";
6617                 break;
6618             case BugreportParams.BUGREPORT_MODE_TELEPHONY:
6619                 type = "bugreporttelephony";
6620                 break;
6621             case BugreportParams.BUGREPORT_MODE_WIFI:
6622                 type = "bugreportwifi";
6623                 break;
6624             default:
6625                 throw new IllegalArgumentException(
6626                     "Provided bugreport type is not correct, value: "
6627                         + bugreportType);
6628         }
6629         // Always log caller, even if it does not have permission to dump.
6630         Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid());
6631         enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
6632 
6633         if (!TextUtils.isEmpty(shareTitle)) {
6634             if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
6635                 String errorStr = "shareTitle should be less than "
6636                         + MAX_BUGREPORT_TITLE_SIZE + " characters";
6637                 throw new IllegalArgumentException(errorStr);
6638             }
6639             if (!TextUtils.isEmpty(shareDescription)) {
6640                 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) {
6641                     String errorStr = "shareDescription should be less than "
6642                             + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters";
6643                     throw new IllegalArgumentException(errorStr);
6644                 }
6645             }
6646             Slog.d(TAG, "Bugreport notification title " + shareTitle
6647                     + " description " + shareDescription);
6648         }
6649         // Create intent to trigger Bugreport API via Shell
6650         Intent triggerShellBugreport = new Intent();
6651         triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED);
6652         triggerShellBugreport.setPackage(SHELL_APP_PACKAGE);
6653         triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType);
6654         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6655         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6656         if (shareTitle != null) {
6657             triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle);
6658         }
6659         if (shareDescription != null) {
6660             triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription);
6661         }
6662         final long identity = Binder.clearCallingIdentity();
6663         try {
6664             // Send broadcast to shell to trigger bugreport using Bugreport API
6665             mContext.sendBroadcastAsUser(triggerShellBugreport, UserHandle.SYSTEM);
6666         } finally {
6667             Binder.restoreCallingIdentity(identity);
6668         }
6669     }
6670 
6671     /**
6672      * Takes a telephony bugreport with title and description
6673      */
6674     @Override
requestTelephonyBugReport(String shareTitle, String shareDescription)6675     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
6676         requestBugReportWithDescription(shareTitle, shareDescription,
6677                 BugreportParams.BUGREPORT_MODE_TELEPHONY);
6678     }
6679 
6680     /**
6681      * Takes a minimal bugreport of Wifi-related state with pre-set title and description
6682      */
6683     @Override
requestWifiBugReport(String shareTitle, String shareDescription)6684     public void requestWifiBugReport(String shareTitle, String shareDescription) {
6685         requestBugReportWithDescription(shareTitle, shareDescription,
6686                 BugreportParams.BUGREPORT_MODE_WIFI);
6687     }
6688 
6689     /**
6690      * Takes an interactive bugreport with a progress notification
6691      */
6692     @Override
requestInteractiveBugReport()6693     public void requestInteractiveBugReport() {
6694         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE);
6695     }
6696 
6697     /**
6698      * Takes an interactive bugreport with a progress notification. Also, shows the given title and
6699      * description on the final share notification
6700      */
6701     @Override
requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)6702     public void requestInteractiveBugReportWithDescription(String shareTitle,
6703             String shareDescription) {
6704         requestBugReportWithDescription(shareTitle, shareDescription,
6705                 BugreportParams.BUGREPORT_MODE_INTERACTIVE);
6706     }
6707 
6708     /**
6709      * Takes a bugreport with minimal user interference
6710      */
6711     @Override
requestFullBugReport()6712     public void requestFullBugReport() {
6713         requestBugReportWithDescription(null, null,  BugreportParams.BUGREPORT_MODE_FULL);
6714     }
6715 
6716     /**
6717      * Takes a bugreport remotely
6718      */
6719     @Override
requestRemoteBugReport()6720     public void requestRemoteBugReport() {
6721         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE);
6722     }
6723 
6724     /**
6725      * Launches a bugreport-whitelisted app to handle a bugreport.
6726      *
6727      * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can
6728      * be predefined in the config, meant to be launched with the primary user. The user can
6729      * override this with a different (or same) handler app on possibly a different user. This is
6730      * useful for capturing bug reports from work profile, for instance.
6731      *
6732      * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false
6733      * otherwise.
6734      */
6735     @Override
launchBugReportHandlerApp()6736     public boolean launchBugReportHandlerApp() {
6737         if (!BugReportHandlerUtil.isBugReportHandlerEnabled(mContext)) {
6738             return false;
6739         }
6740 
6741         // Always log caller, even if it does not have permission to dump.
6742         Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid());
6743         enforceCallingPermission(android.Manifest.permission.DUMP,
6744                 "launchBugReportHandlerApp");
6745 
6746         return BugReportHandlerUtil.launchBugReportHandlerApp(mContext);
6747     }
6748 
6749     /**
6750      * Get packages of bugreport-whitelisted apps to handle a bug report.
6751      *
6752      * @return packages of bugreport-whitelisted apps to handle a bug report.
6753      */
6754     @Override
getBugreportWhitelistedPackages()6755     public List<String> getBugreportWhitelistedPackages() {
6756         enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING,
6757                 "getBugreportWhitelistedPackages");
6758         return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages());
6759     }
6760 
registerProcessObserver(IProcessObserver observer)6761     public void registerProcessObserver(IProcessObserver observer) {
6762         enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6763                 "registerProcessObserver()");
6764         mProcessList.registerProcessObserver(observer);
6765     }
6766 
6767     @Override
unregisterProcessObserver(IProcessObserver observer)6768     public void unregisterProcessObserver(IProcessObserver observer) {
6769         mProcessList.unregisterProcessObserver(observer);
6770     }
6771 
6772     @Override
getUidProcessState(int uid, String callingPackage)6773     public int getUidProcessState(int uid, String callingPackage) {
6774         if (!hasUsageStatsPermission(callingPackage)) {
6775             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
6776                     "getUidProcessState");
6777         }
6778 
6779         synchronized (mProcLock) {
6780             return mProcessList.getUidProcStateLOSP(uid);
6781         }
6782     }
6783 
6784     @Override
getUidProcessCapabilities(int uid, String callingPackage)6785     public @ProcessCapability int getUidProcessCapabilities(int uid, String callingPackage) {
6786         if (!hasUsageStatsPermission(callingPackage)) {
6787             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
6788                     "getUidProcessState");
6789         }
6790 
6791         synchronized (mProcLock) {
6792             return mProcessList.getUidProcessCapabilityLOSP(uid);
6793         }
6794     }
6795 
6796     @Override
registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)6797     public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
6798             String callingPackage) {
6799         if (!hasUsageStatsPermission(callingPackage)) {
6800             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
6801                     "registerUidObserver");
6802         }
6803         mUidObserverController.register(observer, which, cutpoint, callingPackage,
6804                 Binder.getCallingUid());
6805     }
6806 
6807     @Override
unregisterUidObserver(IUidObserver observer)6808     public void unregisterUidObserver(IUidObserver observer) {
6809         mUidObserverController.unregister(observer);
6810     }
6811 
6812     @Override
isUidActive(int uid, String callingPackage)6813     public boolean isUidActive(int uid, String callingPackage) {
6814         if (!hasUsageStatsPermission(callingPackage)) {
6815             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
6816                     "isUidActive");
6817         }
6818         synchronized (mProcLock) {
6819             if (isUidActiveLOSP(uid)) {
6820                 return true;
6821             }
6822         }
6823         return mInternal.isPendingTopUid(uid);
6824     }
6825 
6826     @GuardedBy(anyOf = {"this", "mProcLock"})
isUidActiveLOSP(int uid)6827     boolean isUidActiveLOSP(int uid) {
6828         final UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
6829         return uidRecord != null && !uidRecord.isSetIdle();
6830     }
6831 
6832     @Override
setPersistentVrThread(int tid)6833     public void setPersistentVrThread(int tid) {
6834         mActivityTaskManager.setPersistentVrThread(tid);
6835     }
6836 
6837     /**
6838      * Schedule the given thread a normal scheduling priority.
6839      *
6840      * @param tid the tid of the thread to adjust the scheduling of.
6841      * @param suppressLogs {@code true} if any error logging should be disabled.
6842      *
6843      * @return {@code true} if this succeeded.
6844      */
scheduleAsRegularPriority(int tid, boolean suppressLogs)6845     public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
6846         try {
6847             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
6848             return true;
6849         } catch (IllegalArgumentException e) {
6850             if (!suppressLogs) {
6851                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
6852             }
6853         } catch (SecurityException e) {
6854             if (!suppressLogs) {
6855                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
6856             }
6857         }
6858         return false;
6859     }
6860 
6861     /**
6862      * Schedule the given thread an FIFO scheduling priority.
6863      *
6864      * @param tid the tid of the thread to adjust the scheduling of.
6865      * @param suppressLogs {@code true} if any error logging should be disabled.
6866      *
6867      * @return {@code true} if this succeeded.
6868      */
scheduleAsFifoPriority(int tid, boolean suppressLogs)6869     public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
6870         try {
6871             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
6872             return true;
6873         } catch (IllegalArgumentException e) {
6874             if (!suppressLogs) {
6875                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
6876             }
6877         } catch (SecurityException e) {
6878             if (!suppressLogs) {
6879                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
6880             }
6881         }
6882         return false;
6883     }
6884 
6885     @Override
setRenderThread(int tid)6886     public void setRenderThread(int tid) {
6887         synchronized (mProcLock) {
6888             ProcessRecord proc;
6889             int pid = Binder.getCallingPid();
6890             if (pid == Process.myPid()) {
6891                 demoteSystemServerRenderThread(tid);
6892                 return;
6893             }
6894             synchronized (mPidsSelfLocked) {
6895                 proc = mPidsSelfLocked.get(pid);
6896             }
6897             if (proc != null && proc.getRenderThreadTid() == 0 && tid > 0) {
6898                 // ensure the tid belongs to the process
6899                 if (!isThreadInProcess(pid, tid)) {
6900                     throw new IllegalArgumentException(
6901                             "Render thread does not belong to process");
6902                 }
6903                 proc.setRenderThreadTid(tid);
6904                 if (DEBUG_OOM_ADJ) {
6905                     Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
6906                 }
6907                 // promote to FIFO now
6908                 if (proc.mState.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) {
6909                     if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
6910                     if (mUseFifoUiScheduling) {
6911                         setThreadScheduler(proc.getRenderThreadTid(),
6912                                 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
6913                     } else {
6914                         setThreadPriority(proc.getRenderThreadTid(), THREAD_PRIORITY_TOP_APP_BOOST);
6915                     }
6916                 }
6917             } else {
6918                 if (DEBUG_OOM_ADJ) {
6919                     Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? "
6920                             + "PID: " + pid + ", TID: " + tid + " FIFO: " + mUseFifoUiScheduling);
6921                 }
6922             }
6923         }
6924     }
6925 
6926     /**
6927      * We only use RenderThread in system_server to store task snapshots to the disk, which should
6928      * happen in the background. Thus, demote render thread from system_server to a lower priority.
6929      *
6930      * @param tid the tid of the RenderThread
6931      */
demoteSystemServerRenderThread(int tid)6932     private void demoteSystemServerRenderThread(int tid) {
6933         setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
6934     }
6935 
6936     @Override
isVrModePackageEnabled(ComponentName packageName)6937     public boolean isVrModePackageEnabled(ComponentName packageName) {
6938         mActivityTaskManager.enforceSystemHasVrFeature();
6939 
6940         final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
6941 
6942         return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
6943                 VrManagerInternal.NO_ERROR;
6944     }
6945 
isTopActivityImmersive()6946     public boolean isTopActivityImmersive() {
6947         return mActivityTaskManager.isTopActivityImmersive();
6948     }
6949 
6950     @Override
isTopOfTask(IBinder token)6951     public boolean isTopOfTask(IBinder token) {
6952         return ActivityClient.getInstance().isTopOfTask(token);
6953     }
6954 
6955     @Override
setHasTopUi(boolean hasTopUi)6956     public void setHasTopUi(boolean hasTopUi) throws RemoteException {
6957         if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
6958             String msg = "Permission Denial: setHasTopUi() from pid="
6959                     + Binder.getCallingPid()
6960                     + ", uid=" + Binder.getCallingUid()
6961                     + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
6962             Slog.w(TAG, msg);
6963             throw new SecurityException(msg);
6964         }
6965         final int pid = Binder.getCallingPid();
6966         final long origId = Binder.clearCallingIdentity();
6967         try {
6968             synchronized (this) {
6969                 boolean changed = false;
6970                 ProcessRecord pr;
6971                 synchronized (mPidsSelfLocked) {
6972                     pr = mPidsSelfLocked.get(pid);
6973                     if (pr == null) {
6974                         Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
6975                         return;
6976                     }
6977                     if (pr.mState.hasTopUi() != hasTopUi) {
6978                         if (DEBUG_OOM_ADJ) {
6979                             Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
6980                         }
6981                         pr.mState.setHasTopUi(hasTopUi);
6982                         changed = true;
6983                     }
6984                 }
6985                 if (changed) {
6986                     updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
6987                 }
6988             }
6989         } finally {
6990             Binder.restoreCallingIdentity(origId);
6991         }
6992     }
6993 
enterSafeMode()6994     public final void enterSafeMode() {
6995         synchronized(this) {
6996             // It only makes sense to do this before the system is ready
6997             // and started launching other packages.
6998             if (!mSystemReady) {
6999                 try {
7000                     AppGlobals.getPackageManager().enterSafeMode();
7001                 } catch (RemoteException e) {
7002                 }
7003             }
7004 
7005             mSafeMode = true;
7006         }
7007     }
7008 
showSafeModeOverlay()7009     public final void showSafeModeOverlay() {
7010         View v = LayoutInflater.from(mContext).inflate(
7011                 com.android.internal.R.layout.safe_mode, null);
7012         WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7013         lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7014         lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7015         lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7016         lp.gravity = Gravity.BOTTOM | Gravity.START;
7017         lp.format = v.getBackground().getOpacity();
7018         lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7019                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7020         lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
7021         ((WindowManager)mContext.getSystemService(
7022                 Context.WINDOW_SERVICE)).addView(v, lp);
7023     }
7024 
7025     @Override
noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)7026     public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid,
7027             String sourcePkg, String tag) {
7028         if (workSource != null && workSource.isEmpty()) {
7029             workSource = null;
7030         }
7031 
7032         if (sourceUid <= 0 && workSource == null) {
7033             // Try and derive a UID to attribute things to based on the caller.
7034             if (sender != null) {
7035                 if (!(sender instanceof PendingIntentRecord)) {
7036                     return;
7037                 }
7038 
7039                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
7040                 final int callerUid = Binder.getCallingUid();
7041                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
7042             } else {
7043                 // TODO(narayan): Should we throw an exception in this case ? It means that we
7044                 // haven't been able to derive a UID to attribute things to.
7045                 return;
7046             }
7047         }
7048 
7049         int standbyBucket = 0;
7050 
7051         mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag);
7052         if (workSource != null) {
7053             String workSourcePackage = workSource.getPackageName(0);
7054             int workSourceUid = workSource.getAttributionUid();
7055             if (workSourcePackage == null) {
7056                 workSourcePackage = sourcePkg;
7057                 workSourceUid = sourceUid;
7058             }
7059 
7060             if (mUsageStatsService != null) {
7061                 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage,
7062                         UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime());
7063             }
7064 
7065             FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag,
7066                     sourcePkg, standbyBucket);
7067             if (DEBUG_POWER) {
7068                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
7069                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
7070                         + standbyBucket + " wsName=" + workSourcePackage + ")]");
7071             }
7072         } else {
7073             if (mUsageStatsService != null) {
7074                 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg,
7075                         UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime());
7076             }
7077             FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid,
7078                     null, tag, sourcePkg, standbyBucket);
7079             if (DEBUG_POWER) {
7080                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
7081                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
7082                         + standbyBucket + "]");
7083             }
7084         }
7085 
7086     }
7087 
7088     @Override
noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)7089     public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid,
7090             String tag) {
7091         if (workSource != null && workSource.isEmpty()) {
7092             workSource = null;
7093         }
7094 
7095         if (sourceUid <= 0 && workSource == null) {
7096             // Try and derive a UID to attribute things to based on the caller.
7097             if (sender != null) {
7098                 if (!(sender instanceof PendingIntentRecord)) {
7099                     return;
7100                 }
7101 
7102                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
7103                 final int callerUid = Binder.getCallingUid();
7104                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
7105             } else {
7106                 // TODO(narayan): Should we throw an exception in this case ? It means that we
7107                 // haven't been able to derive a UID to attribute things to.
7108                 return;
7109             }
7110         }
7111 
7112         if (DEBUG_POWER) {
7113             Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource +
7114                     ", tag=" + tag + "]");
7115         }
7116 
7117         mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid);
7118     }
7119 
7120     @Override
noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)7121     public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid,
7122             String tag) {
7123         if (workSource != null && workSource.isEmpty()) {
7124             workSource = null;
7125         }
7126 
7127         if (sourceUid <= 0 && workSource == null) {
7128             // Try and derive a UID to attribute things to based on the caller.
7129             if (sender != null) {
7130                 if (!(sender instanceof PendingIntentRecord)) {
7131                     return;
7132                 }
7133 
7134                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
7135                 final int callerUid = Binder.getCallingUid();
7136                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
7137             } else {
7138                 // TODO(narayan): Should we throw an exception in this case ? It means that we
7139                 // haven't been able to derive a UID to attribute things to.
7140                 return;
7141             }
7142         }
7143 
7144         if (DEBUG_POWER) {
7145             Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource +
7146                     ", tag=" + tag + "]");
7147         }
7148 
7149         mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid);
7150     }
7151 
killPids(int[] pids, String pReason, boolean secure)7152     public boolean killPids(int[] pids, String pReason, boolean secure) {
7153         if (Binder.getCallingUid() != SYSTEM_UID) {
7154             throw new SecurityException("killPids only available to the system");
7155         }
7156         final String reason = (pReason == null) ? "Unknown" : pReason;
7157         // XXX Note: don't acquire main activity lock here, because the window
7158         // manager calls in with its locks held.
7159 
7160         boolean killed = false;
7161         final ArrayList<ProcessRecord> killCandidates = new ArrayList<>();
7162         synchronized (mPidsSelfLocked) {
7163             int worstType = 0;
7164             for (int i = 0; i < pids.length; i++) {
7165                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7166                 if (proc != null) {
7167                     int type = proc.mState.getSetAdj();
7168                     if (type > worstType) {
7169                         worstType = type;
7170                     }
7171                 }
7172             }
7173 
7174             // If the worst oom_adj is somewhere in the cached proc LRU range,
7175             // then constrain it so we will kill all cached procs.
7176             if (worstType < ProcessList.CACHED_APP_MAX_ADJ
7177                     && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
7178                 worstType = ProcessList.CACHED_APP_MIN_ADJ;
7179             }
7180 
7181             // If this is not a secure call, don't let it kill processes that
7182             // are important.
7183             if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7184                 worstType = ProcessList.SERVICE_ADJ;
7185             }
7186 
7187             Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
7188             for (int i = 0; i < pids.length; i++) {
7189                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7190                 if (proc == null) {
7191                     continue;
7192                 }
7193                 int adj = proc.mState.getSetAdj();
7194                 if (adj >= worstType && !proc.isKilledByAm()) {
7195                     killCandidates.add(proc);
7196                     killed = true;
7197                 }
7198             }
7199         }
7200         if (!killCandidates.isEmpty()) {
7201             mHandler.post(() -> {
7202                 synchronized (ActivityManagerService.this) {
7203                     for (int i = 0, size = killCandidates.size(); i < size; i++) {
7204                         killCandidates.get(i).killLocked(reason,
7205                                 ApplicationExitInfo.REASON_OTHER,
7206                                 ApplicationExitInfo.SUBREASON_KILL_PID, true);
7207                     }
7208                 }
7209             });
7210         }
7211         return killed;
7212     }
7213 
7214     @Override
killUid(int appId, int userId, String reason)7215     public void killUid(int appId, int userId, String reason) {
7216         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
7217         synchronized (this) {
7218             final long identity = Binder.clearCallingIdentity();
7219             try {
7220                 synchronized (mProcLock) {
7221                     mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId,
7222                             ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
7223                             true /* callerWillRestart */, true /* doit */,
7224                             true /* evenPersistent */, false /* setRemoved */,
7225                             false /* uninstalling */,
7226                             ApplicationExitInfo.REASON_OTHER,
7227                             ApplicationExitInfo.SUBREASON_KILL_UID,
7228                             reason != null ? reason : "kill uid");
7229                 }
7230             } finally {
7231                 Binder.restoreCallingIdentity(identity);
7232             }
7233         }
7234     }
7235 
7236     @Override
killUidForPermissionChange(int appId, int userId, String reason)7237     public void killUidForPermissionChange(int appId, int userId, String reason) {
7238         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
7239         synchronized (this) {
7240             final long identity = Binder.clearCallingIdentity();
7241             try {
7242                 synchronized (mProcLock) {
7243                     mProcessList.killPackageProcessesLSP(null /* packageName */, appId, userId,
7244                             ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
7245                             true /* callerWillRestart */, true /* doit */,
7246                             true /* evenPersistent */, false /* setRemoved */,
7247                             false /* uninstalling */,
7248                             ApplicationExitInfo.REASON_PERMISSION_CHANGE,
7249                             ApplicationExitInfo.SUBREASON_UNKNOWN,
7250                             reason != null ? reason : "kill uid");
7251                 }
7252             } finally {
7253                 Binder.restoreCallingIdentity(identity);
7254             }
7255         }
7256     }
7257 
7258     @Override
killProcessesBelowForeground(String reason)7259     public boolean killProcessesBelowForeground(String reason) {
7260         if (Binder.getCallingUid() != SYSTEM_UID) {
7261             throw new SecurityException("killProcessesBelowForeground() only available to system");
7262         }
7263 
7264         return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7265     }
7266 
killProcessesBelowAdj(int belowAdj, String reason)7267     private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7268         if (Binder.getCallingUid() != SYSTEM_UID) {
7269             throw new SecurityException("killProcessesBelowAdj() only available to system");
7270         }
7271 
7272         boolean killed = false;
7273         synchronized (this) {
7274             synchronized (mProcLock) {
7275                 synchronized (mPidsSelfLocked) {
7276                     final int size = mPidsSelfLocked.size();
7277                     for (int i = 0; i < size; i++) {
7278                         final int pid = mPidsSelfLocked.keyAt(i);
7279                         final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7280                         if (proc == null) continue;
7281 
7282                         final int adj = proc.mState.getSetAdj();
7283                         if (adj > belowAdj && !proc.isKilledByAm()) {
7284                             proc.killLocked(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE,
7285                                     true);
7286                             killed = true;
7287                         }
7288                     }
7289                 }
7290             }
7291         }
7292         return killed;
7293     }
7294 
7295     /**
7296      * Similar to {@link #killPids} but killing will be delayed until the device is idle
7297      * and the given process is imperceptible.
7298      */
7299     @Override
killProcessesWhenImperceptible(int[] pids, String reason)7300     public void killProcessesWhenImperceptible(int[] pids, String reason) {
7301         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
7302                 != PackageManager.PERMISSION_GRANTED) {
7303             throw new SecurityException("Requires permission "
7304                     + android.Manifest.permission.FORCE_STOP_PACKAGES);
7305         }
7306         int callerUid = Binder.getCallingUid();
7307         final long iden = Binder.clearCallingIdentity();
7308         try {
7309             mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid);
7310         } finally {
7311             Binder.restoreCallingIdentity(iden);
7312         }
7313     }
7314 
7315     @Override
hang(final IBinder who, boolean allowRestart)7316     public void hang(final IBinder who, boolean allowRestart) {
7317         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7318                 != PackageManager.PERMISSION_GRANTED) {
7319             throw new SecurityException("Requires permission "
7320                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7321         }
7322 
7323         final IBinder.DeathRecipient death = new DeathRecipient() {
7324             @Override
7325             public void binderDied() {
7326                 synchronized (this) {
7327                     notifyAll();
7328                 }
7329             }
7330         };
7331 
7332         try {
7333             who.linkToDeath(death, 0);
7334         } catch (RemoteException e) {
7335             Slog.w(TAG, "hang: given caller IBinder is already dead.");
7336             return;
7337         }
7338 
7339         synchronized (this) {
7340             Watchdog.getInstance().setAllowRestart(allowRestart);
7341             Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
7342             synchronized (death) {
7343                 while (who.isBinderAlive()) {
7344                     try {
7345                         death.wait();
7346                     } catch (InterruptedException e) {
7347                     }
7348                 }
7349             }
7350             Watchdog.getInstance().setAllowRestart(true);
7351         }
7352     }
7353 
7354     @Override
restart()7355     public void restart() {
7356         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7357                 != PackageManager.PERMISSION_GRANTED) {
7358             throw new SecurityException("Requires permission "
7359                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7360         }
7361 
7362         Log.i(TAG, "Sending shutdown broadcast...");
7363 
7364         BroadcastReceiver br = new BroadcastReceiver() {
7365             @Override public void onReceive(Context context, Intent intent) {
7366                 // Now the broadcast is done, finish up the low-level shutdown.
7367                 Log.i(TAG, "Shutting down activity manager...");
7368                 shutdown(10000);
7369                 Log.i(TAG, "Shutdown complete, restarting!");
7370                 killProcess(myPid());
7371                 System.exit(10);
7372             }
7373         };
7374 
7375         // First send the high-level shut down broadcast.
7376         Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
7377         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
7378         intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
7379         /* For now we are not doing a clean shutdown, because things seem to get unhappy.
7380         mContext.sendOrderedBroadcastAsUser(intent,
7381                 UserHandle.ALL, null, br, mHandler, 0, null, null);
7382         */
7383         br.onReceive(mContext, intent);
7384     }
7385 
7386     @Override
performIdleMaintenance()7387     public void performIdleMaintenance() {
7388         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7389                 != PackageManager.PERMISSION_GRANTED) {
7390             throw new SecurityException("Requires permission "
7391                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7392         }
7393 
7394         synchronized (mProcLock) {
7395             final long now = SystemClock.uptimeMillis();
7396             final long timeSinceLastIdle = now - mLastIdleTime;
7397 
7398             // Compact all non-zygote processes to freshen up the page cache.
7399             mOomAdjuster.mCachedAppOptimizer.compactAllSystem();
7400 
7401             final long lowRamSinceLastIdle = mAppProfiler.getLowRamTimeSinceIdleLPr(now);
7402             mLastIdleTime = now;
7403             mAppProfiler.updateLowRamTimestampLPr(now);
7404 
7405             StringBuilder sb = new StringBuilder(128);
7406             sb.append("Idle maintenance over ");
7407             TimeUtils.formatDuration(timeSinceLastIdle, sb);
7408             sb.append(" low RAM for ");
7409             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
7410             Slog.i(TAG, sb.toString());
7411 
7412             // If at least 1/3 of our time since the last idle period has been spent
7413             // with RAM low, then we want to kill processes.
7414             boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
7415             // If the processes' memory has increased by more than 1% of the total memory,
7416             // or 10 MB, whichever is greater, then the processes' are eligible to be killed.
7417             final long totalMemoryInKb = getTotalMemory() / 1000;
7418             final long memoryGrowthThreshold =
7419                     Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
7420             mProcessList.forEachLruProcessesLOSP(false, proc -> {
7421                 if (proc.getThread() == null) {
7422                     return;
7423                 }
7424                 final ProcessProfileRecord pr = proc.mProfile;
7425                 final ProcessStateRecord state = proc.mState;
7426                 final int setProcState = state.getSetProcState();
7427                 if (state.isNotCachedSinceIdle()) {
7428                     if (setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
7429                             && setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
7430                         final long initialIdlePss, lastPss, lastSwapPss;
7431                         synchronized (mAppProfiler.mProfilerLock) {
7432                             initialIdlePss = pr.getInitialIdlePss();
7433                             lastPss = pr.getLastPss();
7434                             lastSwapPss = pr.getLastSwapPss();
7435                         }
7436                         if (doKilling && initialIdlePss != 0
7437                                 && lastPss > (initialIdlePss * 3 / 2)
7438                                 && lastPss > (initialIdlePss + memoryGrowthThreshold)) {
7439                             final StringBuilder sb2 = new StringBuilder(128);
7440                             sb2.append("Kill");
7441                             sb2.append(proc.processName);
7442                             sb2.append(" in idle maint: pss=");
7443                             sb2.append(lastPss);
7444                             sb2.append(", swapPss=");
7445                             sb2.append(lastSwapPss);
7446                             sb2.append(", initialPss=");
7447                             sb2.append(initialIdlePss);
7448                             sb2.append(", period=");
7449                             TimeUtils.formatDuration(timeSinceLastIdle, sb2);
7450                             sb2.append(", lowRamPeriod=");
7451                             TimeUtils.formatDuration(lowRamSinceLastIdle, sb2);
7452                             Slog.wtfQuiet(TAG, sb2.toString());
7453                             mHandler.post(() -> {
7454                                 synchronized (ActivityManagerService.this) {
7455                                     proc.killLocked("idle maint (pss " + lastPss
7456                                             + " from " + initialIdlePss + ")",
7457                                             ApplicationExitInfo.REASON_OTHER,
7458                                             ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE,
7459                                             true);
7460                                 }
7461                             });
7462                         }
7463                     }
7464                 } else if (setProcState < ActivityManager.PROCESS_STATE_HOME
7465                         && setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
7466                     state.setNotCachedSinceIdle(true);
7467                     synchronized (mAppProfiler.mProfilerLock) {
7468                         pr.setInitialIdlePss(0);
7469                         mAppProfiler.updateNextPssTimeLPf(
7470                                 state.getSetProcState(), proc.mProfile, now, true);
7471                     }
7472                 }
7473             });
7474         }
7475     }
7476 
7477     @Override
sendIdleJobTrigger()7478     public void sendIdleJobTrigger() {
7479         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7480                 != PackageManager.PERMISSION_GRANTED) {
7481             throw new SecurityException("Requires permission "
7482                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7483         }
7484 
7485         final long ident = Binder.clearCallingIdentity();
7486         try {
7487             Intent intent = new Intent(ACTION_TRIGGER_IDLE)
7488                     .setPackage("android")
7489                     .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7490             broadcastIntent(null, intent, null, null, 0, null, null, null,
7491                     OP_NONE, null, false, false, UserHandle.USER_ALL);
7492         } finally {
7493             Binder.restoreCallingIdentity(ident);
7494         }
7495     }
7496 
retrieveSettings()7497     private void retrieveSettings() {
7498         final ContentResolver resolver = mContext.getContentResolver();
7499         mActivityTaskManager.retrieveSettings(resolver);
7500 
7501         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
7502         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
7503         final boolean alwaysFinishActivities =
7504                 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7505         final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver,
7506                 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS);
7507         mHiddenApiBlacklist.registerObserver();
7508         mPlatformCompat.registerContentObserver();
7509 
7510         mAppProfiler.retrieveSettings();
7511 
7512         final Resources res;
7513         synchronized (this) {
7514             mDebugApp = mOrigDebugApp = debugApp;
7515             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7516             mAlwaysFinishActivities = alwaysFinishActivities;
7517             // Load resources only after the current configuration has been set.
7518             res = mContext.getResources();
7519             final boolean userSwitchUiEnabled = !res.getBoolean(
7520                     com.android.internal.R.bool.config_customUserSwitchUi);
7521             final int maxRunningUsers = res.getInteger(
7522                     com.android.internal.R.integer.config_multiuserMaxRunningUsers);
7523             final boolean delayUserDataLocking = res.getBoolean(
7524                     com.android.internal.R.bool.config_multiuserDelayUserDataLocking);
7525             mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers,
7526                     delayUserDataLocking);
7527             mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs;
7528         }
7529         mAppErrors.loadAppsNotReportingCrashesFromConfig(res.getString(
7530                 com.android.internal.R.string.config_appsNotReportingCrashes));
7531     }
7532 
7533     /**
7534      * Ready. Set. Go!
7535      */
systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)7536     public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
7537         t.traceBegin("PhaseActivityManagerReady");
7538         mSystemServiceManager.preSystemReady();
7539         synchronized(this) {
7540             if (mSystemReady) {
7541                 // If we're done calling all the receivers, run the next "boot phase" passed in
7542                 // by the SystemServer
7543                 if (goingCallback != null) {
7544                     goingCallback.run();
7545                 }
7546                 t.traceEnd(); // PhaseActivityManagerReady
7547                 return;
7548             }
7549 
7550             t.traceBegin("controllersReady");
7551             mLocalDeviceIdleController =
7552                     LocalServices.getService(DeviceIdleInternal.class);
7553             mActivityTaskManager.onSystemReady();
7554             // Make sure we have the current profile info, since it is needed for security checks.
7555             mUserController.onSystemReady();
7556             mAppOpsService.systemReady();
7557             mProcessList.onSystemReady();
7558             mSystemReady = true;
7559             t.traceEnd();
7560         }
7561 
7562         try {
7563             sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
7564                     ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
7565                     .getSerial();
7566         } catch (RemoteException e) {}
7567 
7568         t.traceBegin("killProcesses");
7569         ArrayList<ProcessRecord> procsToKill = null;
7570         synchronized(mPidsSelfLocked) {
7571             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7572                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7573                 if (!isAllowedWhileBooting(proc.info)){
7574                     if (procsToKill == null) {
7575                         procsToKill = new ArrayList<ProcessRecord>();
7576                     }
7577                     procsToKill.add(proc);
7578                 }
7579             }
7580         }
7581 
7582         synchronized(this) {
7583             if (procsToKill != null) {
7584                 for (int i = procsToKill.size() - 1; i >= 0; i--) {
7585                     ProcessRecord proc = procsToKill.get(i);
7586                     Slog.i(TAG, "Removing system update proc: " + proc);
7587                     mProcessList.removeProcessLocked(proc, true, false,
7588                             ApplicationExitInfo.REASON_OTHER,
7589                             ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
7590                             "system update done");
7591                 }
7592             }
7593 
7594             // Now that we have cleaned up any update processes, we
7595             // are ready to start launching real processes and know that
7596             // we won't trample on them any more.
7597             mProcessesReady = true;
7598         }
7599         t.traceEnd(); // KillProcesses
7600 
7601         Slog.i(TAG, "System now ready");
7602 
7603         EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
7604 
7605         t.traceBegin("updateTopComponentForFactoryTest");
7606         mAtmInternal.updateTopComponentForFactoryTest();
7607         t.traceEnd();
7608 
7609         t.traceBegin("registerActivityLaunchObserver");
7610         mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
7611         t.traceEnd();
7612 
7613         t.traceBegin("watchDeviceProvisioning");
7614         watchDeviceProvisioning(mContext);
7615         t.traceEnd();
7616 
7617         t.traceBegin("retrieveSettings");
7618         retrieveSettings();
7619         t.traceEnd();
7620 
7621         t.traceBegin("Ugm.onSystemReady");
7622         mUgmInternal.onSystemReady();
7623         t.traceEnd();
7624 
7625         t.traceBegin("updateForceBackgroundCheck");
7626         final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
7627         if (pmi != null) {
7628             pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
7629                     state -> updateForceBackgroundCheck(state.batterySaverEnabled));
7630             updateForceBackgroundCheck(
7631                     pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
7632         } else {
7633             Slog.wtf(TAG, "PowerManagerInternal not found.");
7634         }
7635         t.traceEnd();
7636 
7637         if (goingCallback != null) goingCallback.run();
7638 
7639         t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
7640         // Check the current user here as a user can be started inside goingCallback.run() from
7641         // other system services.
7642         final int currentUserId = mUserController.getCurrentUserId();
7643         Slog.i(TAG, "Current user:" + currentUserId);
7644         if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
7645             // User other than system user has started. Make sure that system user is already
7646             // started before switching user.
7647             throw new RuntimeException("System user not started while current user is:"
7648                     + currentUserId);
7649         }
7650         t.traceEnd();
7651 
7652         t.traceBegin("ActivityManagerStartApps");
7653         mBatteryStatsService.onSystemReady();
7654         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
7655                 Integer.toString(currentUserId), currentUserId);
7656         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
7657                 Integer.toString(currentUserId), currentUserId);
7658 
7659         // On Automotive, at this point the system user has already been started and unlocked,
7660         // and some of the tasks we do here have already been done. So skip those in that case.
7661         // TODO(b/132262830, b/203885241): this workdound shouldn't be necessary once we move the
7662         // headless-user start logic to UserManager-land
7663         final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
7664 
7665         if (bootingSystemUser) {
7666             mSystemServiceManager.onUserStarting(t, currentUserId);
7667         }
7668 
7669         synchronized (this) {
7670             // Only start up encryption-aware persistent apps; once user is
7671             // unlocked we'll come back around and start unaware apps
7672             t.traceBegin("startPersistentApps");
7673             startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
7674             t.traceEnd();
7675 
7676             // Start up initial activity.
7677             mBooting = true;
7678             // Enable home activity for system user, so that the system can always boot. We don't
7679             // do this when the system user is not setup since the setup wizard should be the one
7680             // to handle home activity in this case.
7681             if (UserManager.isSplitSystemUser() &&
7682                     Settings.Secure.getInt(mContext.getContentResolver(),
7683                          Settings.Secure.USER_SETUP_COMPLETE, 0) != 0
7684                     || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
7685                 t.traceBegin("enableHomeActivity");
7686                 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
7687                 try {
7688                     AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
7689                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
7690                             UserHandle.USER_SYSTEM);
7691                 } catch (RemoteException e) {
7692                     throw e.rethrowAsRuntimeException();
7693                 }
7694                 t.traceEnd();
7695             }
7696 
7697             if (bootingSystemUser) {
7698                 t.traceBegin("startHomeOnAllDisplays");
7699                 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
7700                 t.traceEnd();
7701             }
7702 
7703             t.traceBegin("showSystemReadyErrorDialogs");
7704             mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
7705             t.traceEnd();
7706 
7707 
7708             if (bootingSystemUser) {
7709                 t.traceBegin("sendUserStartBroadcast");
7710                 final int callingUid = Binder.getCallingUid();
7711                 final int callingPid = Binder.getCallingPid();
7712                 final long ident = Binder.clearCallingIdentity();
7713                 try {
7714                     Intent intent = new Intent(Intent.ACTION_USER_STARTED);
7715                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7716                             | Intent.FLAG_RECEIVER_FOREGROUND);
7717                     intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
7718                     broadcastIntentLocked(null, null, null, intent,
7719                             null, null, 0, null, null, null, null, OP_NONE,
7720                             null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
7721                             currentUserId);
7722                     intent = new Intent(Intent.ACTION_USER_STARTING);
7723                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7724                     intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
7725                     broadcastIntentLocked(null, null, null, intent, null,
7726                             new IIntentReceiver.Stub() {
7727                                 @Override
7728                                 public void performReceive(Intent intent, int resultCode,
7729                                         String data, Bundle extras, boolean ordered, boolean sticky,
7730                                         int sendingUser) {}
7731                             }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, null, OP_NONE,
7732                             null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
7733                             UserHandle.USER_ALL);
7734                 } catch (Throwable e) {
7735                     Slog.wtf(TAG, "Failed sending first user broadcasts", e);
7736                 } finally {
7737                     Binder.restoreCallingIdentity(ident);
7738                 }
7739                 t.traceEnd();
7740             } else {
7741                 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
7742                         + currentUserId);
7743             }
7744 
7745             t.traceBegin("resumeTopActivities");
7746             mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
7747             t.traceEnd();
7748 
7749             if (bootingSystemUser) {
7750                 t.traceBegin("sendUserSwitchBroadcasts");
7751                 mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
7752                 t.traceEnd();
7753             }
7754 
7755             t.traceBegin("setBinderProxies");
7756             BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
7757                     BINDER_PROXY_LOW_WATERMARK);
7758             BinderInternal.nSetBinderProxyCountEnabled(true);
7759             BinderInternal.setBinderProxyCountCallback(
7760                     (uid) -> {
7761                         Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
7762                                 + Process.myUid());
7763                         BinderProxy.dumpProxyDebugInfo();
7764                         if (uid == Process.SYSTEM_UID) {
7765                             Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
7766                         } else {
7767                             killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
7768                                     "Too many Binders sent to SYSTEM");
7769                             // We need to run a GC here, because killing the processes involved
7770                             // actually isn't guaranteed to free up the proxies; in fact, if the
7771                             // GC doesn't run for a long time, we may even exceed the global
7772                             // proxy limit for a process (20000), resulting in system_server itself
7773                             // being killed.
7774                             // Note that the GC here might not actually clean up all the proxies,
7775                             // because the binder reference decrements will come in asynchronously;
7776                             // but if new processes belonging to the UID keep adding proxies, we
7777                             // will get another callback here, and run the GC again - this time
7778                             // cleaning up the old proxies.
7779                             VMRuntime.getRuntime().requestConcurrentGC();
7780                         }
7781                     }, mHandler);
7782             t.traceEnd(); // setBinderProxies
7783 
7784             t.traceEnd(); // ActivityManagerStartApps
7785             t.traceEnd(); // PhaseActivityManagerReady
7786         }
7787     }
7788 
watchDeviceProvisioning(Context context)7789     private void watchDeviceProvisioning(Context context) {
7790         // setting system property based on whether device is provisioned
7791 
7792         if (isDeviceProvisioned(context)) {
7793             SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
7794         } else {
7795             // watch for device provisioning change
7796             context.getContentResolver().registerContentObserver(
7797                     Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false,
7798                     new ContentObserver(new Handler(Looper.getMainLooper())) {
7799                         @Override
7800                         public void onChange(boolean selfChange) {
7801                             if (isDeviceProvisioned(context)) {
7802                                 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
7803                                 context.getContentResolver().unregisterContentObserver(this);
7804                             }
7805                         }
7806                     });
7807         }
7808     }
7809 
isDeviceProvisioned(Context context)7810     private boolean isDeviceProvisioned(Context context) {
7811         return Settings.Global.getInt(context.getContentResolver(),
7812                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
7813     }
7814 
startBroadcastObservers()7815     private void startBroadcastObservers() {
7816         for (BroadcastQueue queue : mBroadcastQueues) {
7817             queue.start(mContext.getContentResolver());
7818         }
7819     }
7820 
updateForceBackgroundCheck(boolean enabled)7821     private void updateForceBackgroundCheck(boolean enabled) {
7822         synchronized (this) {
7823             synchronized (mProcLock) {
7824                 if (mForceBackgroundCheck != enabled) {
7825                     mForceBackgroundCheck = enabled;
7826 
7827                     if (DEBUG_BACKGROUND_CHECK) {
7828                         Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled"));
7829                     }
7830 
7831                     if (mForceBackgroundCheck) {
7832                         // Stop background services for idle UIDs.
7833                         mProcessList.doStopUidForIdleUidsLocked();
7834                     }
7835                 }
7836             }
7837         }
7838     }
7839 
killAppAtUsersRequest(ProcessRecord app)7840     void killAppAtUsersRequest(ProcessRecord app) {
7841         synchronized (this) {
7842             mAppErrors.killAppAtUserRequestLocked(app);
7843         }
7844     }
7845 
skipCurrentReceiverLocked(ProcessRecord app)7846     void skipCurrentReceiverLocked(ProcessRecord app) {
7847         for (BroadcastQueue queue : mBroadcastQueues) {
7848             queue.skipCurrentReceiverLocked(app);
7849         }
7850     }
7851 
7852     /**
7853      * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7854      * The application process will exit immediately after this call returns.
7855      * @param app object of the crashing app, null for the system server
7856      * @param crashInfo describing the exception
7857      */
handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)7858     public void handleApplicationCrash(IBinder app,
7859             ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
7860         ProcessRecord r = findAppProcess(app, "Crash");
7861         final String processName = app == null ? "system_server"
7862                 : (r == null ? "unknown" : r.processName);
7863 
7864         handleApplicationCrashInner("crash", r, processName, crashInfo);
7865     }
7866 
7867     /* Native crash reporting uses this inner version because it needs to be somewhat
7868      * decoupled from the AM-managed cleanup lifecycle
7869      */
handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)7870     void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
7871             ApplicationErrorReport.CrashInfo crashInfo) {
7872         float loadingProgress = 1;
7873         IncrementalMetrics incrementalMetrics = null;
7874         // Obtain Incremental information if available
7875         if (r != null && r.info != null && r.info.packageName != null) {
7876             IncrementalStatesInfo incrementalStatesInfo =
7877                     mPackageManagerInt.getIncrementalStatesInfo(r.info.packageName, r.uid,
7878                             r.userId);
7879             if (incrementalStatesInfo != null) {
7880                 loadingProgress = incrementalStatesInfo.getProgress();
7881             }
7882             final String codePath = r.info.getCodePath();
7883             if (codePath != null && !codePath.isEmpty()
7884                     && IncrementalManager.isIncrementalPath(codePath)) {
7885                 // Report in the main log about the incremental package
7886                 Slog.e(TAG, "App crashed on incremental package " + r.info.packageName
7887                         + " which is " + ((int) (loadingProgress * 100)) + "% loaded.");
7888                 final IBinder incrementalService = ServiceManager.getService(
7889                         Context.INCREMENTAL_SERVICE);
7890                 if (incrementalService != null) {
7891                     final IncrementalManager incrementalManager = new IncrementalManager(
7892                             IIncrementalService.Stub.asInterface(incrementalService));
7893                     incrementalMetrics = incrementalManager.getMetrics(codePath);
7894                 }
7895             }
7896         }
7897 
7898         EventLogTags.writeAmCrash(Binder.getCallingPid(),
7899                 UserHandle.getUserId(Binder.getCallingUid()), processName,
7900                 r == null ? -1 : r.info.flags,
7901                 crashInfo.exceptionClassName,
7902                 crashInfo.exceptionMessage,
7903                 crashInfo.throwFileName,
7904                 crashInfo.throwLineNumber);
7905 
7906         FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED,
7907                 (r != null) ? r.uid : -1,
7908                 eventType,
7909                 processName,
7910                 (r != null) ? r.getPid() : -1,
7911                 (r != null && r.info != null) ? r.info.packageName : "",
7912                 (r != null && r.info != null) ? (r.info.isInstantApp()
7913                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE
7914                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE)
7915                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE,
7916                 r != null ? (r.isInterestingToUserLocked()
7917                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND
7918                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND)
7919                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN,
7920                 processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER
7921                         : (r != null) ? r.getProcessClassEnum()
7922                                       : ServerProtoEnums.ERROR_SOURCE_UNKNOWN,
7923                 incrementalMetrics != null /* isIncremental */, loadingProgress,
7924                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceOldestPendingRead()
7925                         : -1,
7926                 incrementalMetrics != null ? incrementalMetrics.getStorageHealthStatusCode()
7927                         : -1,
7928                 incrementalMetrics != null ? incrementalMetrics.getDataLoaderStatusCode()
7929                         : -1,
7930                 incrementalMetrics != null && incrementalMetrics.getReadLogsEnabled(),
7931                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastDataLoaderBind()
7932                         : -1,
7933                 incrementalMetrics != null ? incrementalMetrics.getDataLoaderBindDelayMillis()
7934                         : -1,
7935                 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReads()
7936                         : -1,
7937                 incrementalMetrics != null ? incrementalMetrics.getTotalFailedReads()
7938                         : -1,
7939                 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorUid()
7940                         : -1,
7941                 incrementalMetrics != null ? incrementalMetrics.getMillisSinceLastReadError()
7942                         : -1,
7943                 incrementalMetrics != null ? incrementalMetrics.getLastReadErrorNumber()
7944                         : 0,
7945                 incrementalMetrics != null ? incrementalMetrics.getTotalDelayedReadsDurationMillis()
7946                         : -1
7947         );
7948 
7949         final int relaunchReason = r == null ? RELAUNCH_REASON_NONE
7950                         : r.getWindowProcessController().computeRelaunchReason();
7951         final String relaunchReasonString = relaunchReasonToString(relaunchReason);
7952         if (crashInfo.crashTag == null) {
7953             crashInfo.crashTag = relaunchReasonString;
7954         } else {
7955             crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString;
7956         }
7957 
7958         addErrorToDropBox(
7959                 eventType, r, processName, null, null, null, null, null, null, crashInfo,
7960                 new Float(loadingProgress), incrementalMetrics, null);
7961 
7962         mAppErrors.crashApplication(r, crashInfo);
7963     }
7964 
handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)7965     public void handleApplicationStrictModeViolation(
7966             IBinder app,
7967             int penaltyMask,
7968             StrictMode.ViolationInfo info) {
7969         // We're okay if the ProcessRecord is missing; it probably means that
7970         // we're reporting a violation from the system process itself.
7971         final ProcessRecord r = findAppProcess(app, "StrictMode");
7972 
7973         if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) {
7974             Integer stackFingerprint = info.hashCode();
7975             boolean logIt = true;
7976             synchronized (mAlreadyLoggedViolatedStacks) {
7977                 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7978                     logIt = false;
7979                     // TODO: sub-sample into EventLog for these, with
7980                     // the info.durationMillis?  Then we'd get
7981                     // the relative pain numbers, without logging all
7982                     // the stack traces repeatedly.  We'd want to do
7983                     // likewise in the client code, which also does
7984                     // dup suppression, before the Binder call.
7985                 } else {
7986                     if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7987                         mAlreadyLoggedViolatedStacks.clear();
7988                     }
7989                     mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7990                 }
7991             }
7992             if (logIt) {
7993                 logStrictModeViolationToDropBox(r, info);
7994             }
7995         }
7996 
7997         if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) {
7998             AppErrorResult result = new AppErrorResult();
7999             final long origId = Binder.clearCallingIdentity();
8000             try {
8001                 Message msg = Message.obtain();
8002                 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG;
8003                 HashMap<String, Object> data = new HashMap<String, Object>();
8004                 data.put("result", result);
8005                 data.put("app", r);
8006                 data.put("info", info);
8007                 msg.obj = data;
8008                 mUiHandler.sendMessage(msg);
8009             } finally {
8010                 Binder.restoreCallingIdentity(origId);
8011             }
8012             int res = result.get();
8013             Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
8014         }
8015     }
8016 
8017     // Depending on the policy in effect, there could be a bunch of
8018     // these in quick succession so we try to batch these together to
8019     // minimize disk writes, number of dropbox entries, and maximize
8020     // compression, by having more fewer, larger records.
logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)8021     private void logStrictModeViolationToDropBox(
8022             ProcessRecord process,
8023             StrictMode.ViolationInfo info) {
8024         if (info == null) {
8025             return;
8026         }
8027         final boolean isSystemApp = process == null ||
8028                 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8029                                        ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
8030         final String processName = process == null ? "unknown" : process.processName;
8031         final DropBoxManager dbox = (DropBoxManager)
8032                 mContext.getSystemService(Context.DROPBOX_SERVICE);
8033 
8034         // Exit early if the dropbox isn't configured to accept this report type.
8035         final String dropboxTag = processClass(process) + "_strictmode";
8036         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8037 
8038         final StringBuilder sb = new StringBuilder(1024);
8039         synchronized (sb) {
8040             appendDropBoxProcessHeaders(process, processName, sb);
8041             sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8042             sb.append("System-App: ").append(isSystemApp).append("\n");
8043             sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8044             if (info.violationNumThisLoop != 0) {
8045                 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8046             }
8047             if (info.numAnimationsRunning != 0) {
8048                 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8049             }
8050             if (info.broadcastIntentAction != null) {
8051                 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8052             }
8053             if (info.durationMillis != -1) {
8054                 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
8055             }
8056             if (info.numInstances != -1) {
8057                 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8058             }
8059             if (info.tags != null) {
8060                 for (String tag : info.tags) {
8061                     sb.append("Span-Tag: ").append(tag).append("\n");
8062                 }
8063             }
8064             sb.append("\n");
8065             sb.append(info.getStackTrace());
8066             sb.append("\n");
8067             if (info.getViolationDetails() != null) {
8068                 sb.append(info.getViolationDetails());
8069                 sb.append("\n");
8070             }
8071         }
8072 
8073         final String res = sb.toString();
8074         IoThread.getHandler().post(() -> {
8075             dbox.addText(dropboxTag, res);
8076         });
8077     }
8078 
8079     /**
8080      * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8081      * @param app object of the crashing app, null for the system server
8082      * @param tag reported by the caller
8083      * @param system whether this wtf is coming from the system
8084      * @param crashInfo describing the context of the error
8085      * @return true if the process should exit immediately (WTF is fatal)
8086      */
8087     @Override
handleApplicationWtf(@ullable final IBinder app, @Nullable final String tag, boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)8088     public boolean handleApplicationWtf(@Nullable final IBinder app, @Nullable final String tag,
8089             boolean system, @NonNull final ApplicationErrorReport.ParcelableCrashInfo crashInfo,
8090             int immediateCallerPid) {
8091         final int callingUid = Binder.getCallingUid();
8092         final int callingPid = Binder.getCallingPid();
8093 
8094         // Internal callers in RuntimeInit should always generate a crashInfo.
8095         Preconditions.checkNotNull(crashInfo);
8096 
8097         // If this is coming from the system, we could very well have low-level
8098         // system locks held, so we want to do this all asynchronously.  And we
8099         // never want this to become fatal, so there is that too.
8100         //
8101         // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller
8102         // is within the system server, if it calls Log.wtf() without clearning the calling
8103         // identity, callingPid would still be of a remote caller. So we explicltly pass the
8104         // process PID from the caller.
8105         if (system || (immediateCallerPid == Process.myPid())) {
8106             mHandler.post(new Runnable() {
8107                 @Override public void run() {
8108                     handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo);
8109                 }
8110             });
8111             return false;
8112         }
8113 
8114         final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag,
8115                 crashInfo);
8116 
8117         final boolean isFatal = Build.IS_ENG || Settings.Global
8118                 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0;
8119         final boolean isSystem = (r == null) || r.isPersistent();
8120 
8121         if (isFatal && !isSystem) {
8122             mAppErrors.crashApplication(r, crashInfo);
8123             return true;
8124         } else {
8125             return false;
8126         }
8127     }
8128 
handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app, @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo)8129     ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, @Nullable IBinder app,
8130             @Nullable String tag, @Nullable final ApplicationErrorReport.CrashInfo crashInfo) {
8131         final ProcessRecord r = findAppProcess(app, "WTF");
8132         final String processName = app == null ? "system_server"
8133                 : (r == null ? "unknown" : r.processName);
8134 
8135         EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid,
8136                 processName, r == null ? -1 : r.info.flags, tag,
8137                 crashInfo == null ? "unknown" : crashInfo.exceptionMessage);
8138 
8139         FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName,
8140                 callingPid, (r != null) ? r.getProcessClassEnum() : 0);
8141 
8142         addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo,
8143                 null, null, null);
8144 
8145         return r;
8146     }
8147 
8148     /**
8149      * Schedule to handle any pending system_server WTFs.
8150      */
schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)8151     public void schedulePendingSystemServerWtfs(
8152             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
8153         mHandler.post(() -> handlePendingSystemServerWtfs(list));
8154     }
8155 
8156     /**
8157      * Handle any pending system_server WTFs, add into the dropbox
8158      */
handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)8159     private void handlePendingSystemServerWtfs(
8160             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
8161         ProcessRecord proc;
8162         synchronized (mPidsSelfLocked) {
8163             proc = mPidsSelfLocked.get(MY_PID);
8164         }
8165         for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll();
8166                 p != null; p = list.poll()) {
8167             addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null,
8168                     p.second, null, null, null);
8169         }
8170     }
8171 
8172     /**
8173      * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8174      * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8175      */
findAppProcess(IBinder app, String reason)8176     private ProcessRecord findAppProcess(IBinder app, String reason) {
8177         if (app == null) {
8178             return null;
8179         }
8180 
8181         synchronized (mProcLock) {
8182             return mProcessList.findAppProcessLOSP(app, reason);
8183         }
8184     }
8185 
8186     /**
8187      * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8188      * to append various headers to the dropbox log text.
8189      */
appendDropBoxProcessHeaders(ProcessRecord process, String processName, final StringBuilder sb)8190     void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8191             final StringBuilder sb) {
8192         // Watchdog thread ends up invoking this function (with
8193         // a null ProcessRecord) to add the stack file to dropbox.
8194         // Do not acquire a lock on this (am) in such cases, as it
8195         // could cause a potential deadlock, if and when watchdog
8196         // is invoked due to unavailability of lock on am and it
8197         // would prevent watchdog from killing system_server.
8198         if (process == null) {
8199             sb.append("Process: ").append(processName).append("\n");
8200             return;
8201         }
8202         // Note: ProcessRecord 'process' is guarded by the service
8203         // instance.  (notably process.pkgList, which could otherwise change
8204         // concurrently during execution of this method)
8205         synchronized (mProcLock) {
8206             sb.append("Process: ").append(processName).append("\n");
8207             sb.append("PID: ").append(process.getPid()).append("\n");
8208             sb.append("UID: ").append(process.uid).append("\n");
8209             int flags = process.info.flags;
8210             final IPackageManager pm = AppGlobals.getPackageManager();
8211             sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n");
8212             final int callingUserId = UserHandle.getCallingUserId();
8213             process.getPkgList().forEachPackage(pkg -> {
8214                 sb.append("Package: ").append(pkg);
8215                 try {
8216                     final PackageInfo pi = pm.getPackageInfo(pkg, 0, callingUserId);
8217                     if (pi != null) {
8218                         sb.append(" v").append(pi.getLongVersionCode());
8219                         if (pi.versionName != null) {
8220                             sb.append(" (").append(pi.versionName).append(")");
8221                         }
8222                     }
8223                 } catch (RemoteException e) {
8224                     Slog.e(TAG, "Error getting package info: " + pkg, e);
8225                 }
8226                 sb.append("\n");
8227             });
8228             if (process.info.isInstantApp()) {
8229                 sb.append("Instant-App: true\n");
8230             }
8231         }
8232     }
8233 
processClass(ProcessRecord process)8234     private static String processClass(ProcessRecord process) {
8235         if (process == null || process.getPid() == MY_PID) {
8236             return "system_server";
8237         } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8238             return "system_app";
8239         } else {
8240             return "data_app";
8241         }
8242     }
8243 
8244     private final ArrayMap<String, long[]> mErrorClusterRecords = new ArrayMap<>();
8245 
8246     /**
8247      * Write a description of an error (crash, WTF, ANR) to the drop box.
8248      * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8249      * @param process which caused the error, null means the system server
8250      * @param activityShortComponentName which triggered the error, null if unknown
8251      * @param parentShortComponentName activity related to the error, null if unknown
8252      * @param parentProcess parent process
8253      * @param subject line related to the error, null if absent
8254      * @param report in long form describing the error, null if absent
8255      * @param dataFile text file to include in the report, null if none
8256      * @param crashInfo giving an application stack trace, null if absent
8257      * @param loadingProgress the loading progress of an installed package, range in [0, 1].
8258      * @param incrementalMetrics metrics for apps installed on Incremental.
8259      * @param errorId a unique id to append to the dropbox headers.
8260      */
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)8261     public void addErrorToDropBox(String eventType,
8262             ProcessRecord process, String processName, String activityShortComponentName,
8263             String parentShortComponentName, ProcessRecord parentProcess,
8264             String subject, final String report, final File dataFile,
8265             final ApplicationErrorReport.CrashInfo crashInfo,
8266             @Nullable Float loadingProgress, @Nullable IncrementalMetrics incrementalMetrics,
8267             @Nullable UUID errorId) {
8268         // NOTE -- this must never acquire the ActivityManagerService lock,
8269         // otherwise the watchdog may be prevented from resetting the system.
8270 
8271         // Bail early if not published yet
8272         if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return;
8273         final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class);
8274 
8275         // Exit early if the dropbox isn't configured to accept this report type.
8276         final String dropboxTag = processClass(process) + "_" + eventType;
8277         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8278 
8279         // Rate-limit how often we're willing to do the heavy lifting below to
8280         // collect and record logs; currently 5 logs per 10 second period per eventType.
8281         final long now = SystemClock.elapsedRealtime();
8282         synchronized (mErrorClusterRecords) {
8283             long[] errRecord = mErrorClusterRecords.get(eventType);
8284             if (errRecord == null) {
8285                 errRecord = new long[2]; // [0]: startTime, [1]: count
8286                 mErrorClusterRecords.put(eventType, errRecord);
8287             }
8288             if (now - errRecord[0] > 10 * DateUtils.SECOND_IN_MILLIS) {
8289                 errRecord[0] = now;
8290                 errRecord[1] = 1L;
8291             } else {
8292                 if (errRecord[1]++ >= 5) return;
8293             }
8294         }
8295 
8296         final StringBuilder sb = new StringBuilder(1024);
8297         appendDropBoxProcessHeaders(process, processName, sb);
8298         if (process != null) {
8299             sb.append("Foreground: ")
8300                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
8301                     .append("\n");
8302             if (process.getStartTime() > 0) {
8303                 long runtimeMillis = SystemClock.elapsedRealtime() - process.getStartTime();
8304                 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n");
8305             }
8306         }
8307         if (activityShortComponentName != null) {
8308             sb.append("Activity: ").append(activityShortComponentName).append("\n");
8309         }
8310         if (parentShortComponentName != null) {
8311             if (parentProcess != null && parentProcess.getPid() != process.getPid()) {
8312                 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n");
8313             }
8314             if (!parentShortComponentName.equals(activityShortComponentName)) {
8315                 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n");
8316             }
8317         }
8318         if (subject != null) {
8319             sb.append("Subject: ").append(subject).append("\n");
8320         }
8321         if (errorId != null) {
8322             sb.append("ErrorId: ").append(errorId.toString()).append("\n");
8323         }
8324         sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8325         if (Debug.isDebuggerConnected()) {
8326             sb.append("Debugger: Connected\n");
8327         }
8328         if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) {
8329             sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n");
8330         }
8331         if (loadingProgress != null) {
8332             sb.append("Loading-Progress: ").append(loadingProgress.floatValue()).append("\n");
8333         }
8334         if (incrementalMetrics != null) {
8335             sb.append("Incremental: Yes").append("\n");
8336             final long millisSinceOldestPendingRead =
8337                     incrementalMetrics.getMillisSinceOldestPendingRead();
8338             if (millisSinceOldestPendingRead > 0) {
8339                 sb.append("Millis-Since-Oldest-Pending-Read: ").append(
8340                         millisSinceOldestPendingRead).append("\n");
8341             }
8342         }
8343         sb.append("\n");
8344 
8345         // Do the rest in a worker thread to avoid blocking the caller on I/O
8346         // (After this point, we shouldn't access AMS internal data structures.)
8347         Thread worker = new Thread("Error dump: " + dropboxTag) {
8348             @Override
8349             public void run() {
8350                 if (report != null) {
8351                     sb.append(report);
8352                 }
8353 
8354                 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8355                 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag;
8356                 int lines = Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0);
8357                 int dropboxMaxSize = Settings.Global.getInt(
8358                         mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE);
8359                 int maxDataFileSize = dropboxMaxSize - sb.length()
8360                         - lines * RESERVED_BYTES_PER_LOGCAT_LINE;
8361 
8362                 if (dataFile != null && maxDataFileSize > 0) {
8363                     try {
8364                         sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize,
8365                                     "\n\n[[TRUNCATED]]"));
8366                     } catch (IOException e) {
8367                         Slog.e(TAG, "Error reading " + dataFile, e);
8368                     }
8369                 }
8370                 if (crashInfo != null && crashInfo.stackTrace != null) {
8371                     sb.append(crashInfo.stackTrace);
8372                 }
8373 
8374                 if (lines > 0) {
8375                     sb.append("\n");
8376 
8377                     // Merge several logcat streams, and take the last N lines
8378                     InputStreamReader input = null;
8379                     try {
8380                         java.lang.Process logcat = new ProcessBuilder(
8381                                 "/system/bin/timeout", "-k", "15s", "10s",
8382                                 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system",
8383                                 "-b", "main", "-b", "crash", "-t", String.valueOf(lines))
8384                                         .redirectErrorStream(true).start();
8385 
8386                         try { logcat.getOutputStream().close(); } catch (IOException e) {}
8387                         try { logcat.getErrorStream().close(); } catch (IOException e) {}
8388                         input = new InputStreamReader(logcat.getInputStream());
8389 
8390                         int num;
8391                         char[] buf = new char[8192];
8392                         while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8393                     } catch (IOException e) {
8394                         Slog.e(TAG, "Error running logcat", e);
8395                     } finally {
8396                         if (input != null) try { input.close(); } catch (IOException e) {}
8397                     }
8398                 }
8399 
8400                 dbox.addText(dropboxTag, sb.toString());
8401             }
8402         };
8403 
8404         if (process == null) {
8405             // If process is null, we are being called from some internal code
8406             // and may be about to die -- run this synchronously.
8407             final int oldMask = StrictMode.allowThreadDiskWritesMask();
8408             try {
8409                 worker.run();
8410             } finally {
8411                 StrictMode.setThreadPolicyMask(oldMask);
8412             }
8413         } else {
8414             worker.start();
8415         }
8416     }
8417 
8418     @Override
getProcessesInErrorState()8419     public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
8420         enforceNotIsolatedCaller("getProcessesInErrorState");
8421         // assume our apps are happy - lazy create the list
8422         final List<ActivityManager.ProcessErrorStateInfo>[] errList = new List[1];
8423 
8424         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
8425                 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8426         int userId = UserHandle.getUserId(Binder.getCallingUid());
8427 
8428         synchronized (mProcLock) {
8429             // iterate across all processes
8430             mProcessList.forEachLruProcessesLOSP(false, app -> {
8431                 if (!allUsers && app.userId != userId) {
8432                     return;
8433                 }
8434                 final ProcessErrorStateRecord errState = app.mErrorState;
8435                 final boolean crashing = errState.isCrashing();
8436                 final boolean notResponding = errState.isNotResponding();
8437                 if ((app.getThread() != null) && (crashing || notResponding)) {
8438                     // This one's in trouble, so we'll generate a report for it
8439                     // crashes are higher priority (in case there's a crash *and* an anr)
8440                     ActivityManager.ProcessErrorStateInfo report = null;
8441                     if (crashing) {
8442                         report = errState.getCrashingReport();
8443                     } else if (notResponding) {
8444                         report = errState.getNotRespondingReport();
8445                     }
8446 
8447                     if (report != null) {
8448                         if (errList[0] == null) {
8449                             errList[0] = new ArrayList<>(1);
8450                         }
8451                         errList[0].add(report);
8452                     } else {
8453                         Slog.w(TAG, "Missing app error report, app = " + app.processName +
8454                                 " crashing = " + crashing +
8455                                 " notResponding = " + notResponding);
8456                     }
8457                 }
8458             });
8459         }
8460 
8461         return errList[0];
8462     }
8463 
8464     @Override
getRunningAppProcesses()8465     public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
8466         enforceNotIsolatedCaller("getRunningAppProcesses");
8467 
8468         final int callingUid = Binder.getCallingUid();
8469         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
8470 
8471         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
8472                 callingUid) == PackageManager.PERMISSION_GRANTED;
8473         final int userId = UserHandle.getUserId(callingUid);
8474         final boolean allUids = mAtmInternal.isGetTasksAllowed(
8475                 "getRunningAppProcesses", Binder.getCallingPid(), callingUid);
8476 
8477         synchronized (mProcLock) {
8478             // Iterate across all processes
8479             return mProcessList.getRunningAppProcessesLOSP(allUsers, userId, allUids,
8480                     callingUid, clientTargetSdk);
8481         }
8482     }
8483 
8484     @Override
getRunningExternalApplications()8485     public List<ApplicationInfo> getRunningExternalApplications() {
8486         enforceNotIsolatedCaller("getRunningExternalApplications");
8487         List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8488         List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8489         if (runningApps != null && runningApps.size() > 0) {
8490             Set<String> extList = new HashSet<String>();
8491             for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8492                 if (app.pkgList != null) {
8493                     for (String pkg : app.pkgList) {
8494                         extList.add(pkg);
8495                     }
8496                 }
8497             }
8498             IPackageManager pm = AppGlobals.getPackageManager();
8499             for (String pkg : extList) {
8500                 try {
8501                     ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
8502                     if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8503                         retList.add(info);
8504                     }
8505                 } catch (RemoteException e) {
8506                 }
8507             }
8508         }
8509         return retList;
8510     }
8511 
8512     @Override
getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)8513     public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons(
8514             String packageName, int pid, int maxNum, int userId) {
8515         enforceNotIsolatedCaller("getHistoricalProcessExitReasons");
8516 
8517         // For the simplification, we don't support USER_ALL nor USER_CURRENT here.
8518         if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) {
8519             throw new IllegalArgumentException("Unsupported userId");
8520         }
8521 
8522         final int callingPid = Binder.getCallingPid();
8523         final int callingUid = Binder.getCallingUid();
8524         final int callingUserId = UserHandle.getCallingUserId();
8525         mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL,
8526                 "getHistoricalProcessExitReasons", null);
8527 
8528         NativeTombstoneManager tombstoneService = LocalServices.getService(
8529                 NativeTombstoneManager.class);
8530 
8531         final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>();
8532         if (!TextUtils.isEmpty(packageName)) {
8533             final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid,
8534                       "getHistoricalProcessExitReasons");
8535             if (uid != INVALID_UID) {
8536                 mProcessList.mAppExitInfoTracker.getExitInfo(
8537                         packageName, uid, pid, maxNum, results);
8538                 tombstoneService.collectTombstones(results, uid, pid, maxNum);
8539             }
8540         } else {
8541             // If no package name is given, use the caller's uid as the filter uid.
8542             mProcessList.mAppExitInfoTracker.getExitInfo(
8543                     packageName, callingUid, pid, maxNum, results);
8544             tombstoneService.collectTombstones(results, callingUid, pid, maxNum);
8545         }
8546 
8547         return new ParceledListSlice<ApplicationExitInfo>(results);
8548     }
8549 
8550     @Override
setProcessStateSummary(@ullable byte[] state)8551     public void setProcessStateSummary(@Nullable byte[] state) {
8552         if (state != null && state.length > MAX_STATE_DATA_SIZE) {
8553             throw new IllegalArgumentException("Data size is too large");
8554         }
8555         mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(),
8556                 Binder.getCallingPid(), state);
8557     }
8558 
8559     /**
8560      * Check if the calling process has the permission to dump given package,
8561      * throw SecurityException if it doesn't have the permission.
8562      *
8563      * @return The UID of the given package, or {@link android.os.Process#INVALID_UID}
8564      *         if the package is not found.
8565      */
enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)8566     int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid,
8567             String function) {
8568         final long identity = Binder.clearCallingIdentity();
8569         int uid = INVALID_UID;
8570         try {
8571             uid = mPackageManagerInt.getPackageUid(packageName,
8572                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
8573         } finally {
8574             Binder.restoreCallingIdentity(identity);
8575         }
8576         // If the uid is Process.INVALID_UID, the below 'if' check will be always true
8577         if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) {
8578             // Requires the DUMP permission if the target package doesn't belong
8579             // to the caller or it doesn't exist.
8580             enforceCallingPermission(android.Manifest.permission.DUMP, function);
8581         }
8582         return uid;
8583     }
8584 
8585     @Override
getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)8586     public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) {
8587         if (outState == null) {
8588             throw new IllegalArgumentException("outState is null");
8589         }
8590         enforceNotIsolatedCaller("getMyMemoryState");
8591 
8592         final int callingUid = Binder.getCallingUid();
8593         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
8594 
8595         synchronized (mProcLock) {
8596             ProcessRecord proc;
8597             synchronized (mPidsSelfLocked) {
8598                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8599             }
8600             if (proc != null) {
8601                 mProcessList.fillInProcMemInfoLOSP(proc, outState, clientTargetSdk);
8602             }
8603         }
8604     }
8605 
8606     @Override
getMemoryTrimLevel()8607     public @MemFactor int getMemoryTrimLevel() {
8608         enforceNotIsolatedCaller("getMyMemoryState");
8609         synchronized (this) {
8610             return mAppProfiler.getLastMemoryLevelLocked();
8611         }
8612     }
8613 
setMemFactorOverride(@emFactor int level)8614     void setMemFactorOverride(@MemFactor int level) {
8615         synchronized (this) {
8616             if (level == mAppProfiler.getLastMemoryLevelLocked()) {
8617                 return;
8618             }
8619 
8620             mAppProfiler.setMemFactorOverrideLocked(level);
8621             // Kick off an oom adj update since we forced a mem factor update.
8622             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
8623         }
8624     }
8625 
8626     /**
8627      * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}.
8628      */
setServiceRestartBackoffEnabled(@onNull String packageName, boolean enable, @NonNull String reason)8629     void setServiceRestartBackoffEnabled(@NonNull String packageName, boolean enable,
8630             @NonNull String reason) {
8631         synchronized (this) {
8632             mServices.setServiceRestartBackoffEnabledLocked(packageName, enable, reason);
8633         }
8634     }
8635 
8636     /**
8637      * @return {@code false} if the given package has been disable from enforcing the service
8638      * restart backoff policy, used by {@link ActivityManagerShellCommand}.
8639      */
isServiceRestartBackoffEnabled(@onNull String packageName)8640     boolean isServiceRestartBackoffEnabled(@NonNull String packageName) {
8641         synchronized (this) {
8642             return mServices.isServiceRestartBackoffEnabledLocked(packageName);
8643         }
8644     }
8645 
8646     @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)8647     public void onShellCommand(FileDescriptor in, FileDescriptor out,
8648             FileDescriptor err, String[] args, ShellCallback callback,
8649             ResultReceiver resultReceiver) {
8650         (new ActivityManagerShellCommand(this, false)).exec(
8651                 this, in, out, err, args, callback, resultReceiver);
8652     }
8653 
8654     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)8655     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8656         PriorityDump.dump(mPriorityDumper, fd, pw, args);
8657     }
8658 
dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)8659     private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti,
8660             boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority,
8661             int dumpAppId, boolean dumpProxies) {
8662 
8663         ActiveServices.ServiceDumper sdumper;
8664 
8665         synchronized(this) {
8666             mConstants.dump(pw);
8667             synchronized (mProcLock) {
8668                 mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
8669             }
8670             mOomAdjuster.dumpCacheOomRankerSettings(pw);
8671             pw.println();
8672             if (dumpAll) {
8673                 pw.println("-------------------------------------------------------------------------------");
8674 
8675             }
8676             dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
8677             pw.println();
8678             if (dumpAll) {
8679                 pw.println("-------------------------------------------------------------------------------");
8680 
8681             }
8682             mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage);
8683             pw.println();
8684             if (dumpAll) {
8685                 pw.println("-------------------------------------------------------------------------------");
8686             }
8687             dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
8688             pw.println();
8689             if (dumpAll) {
8690                 pw.println("-------------------------------------------------------------------------------");
8691             }
8692             if (dumpAll || dumpPackage != null) {
8693                 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
8694                 pw.println();
8695                 if (dumpAll) {
8696                     pw.println("-------------------------------------------------------------------------------");
8697                 }
8698             }
8699             mCpHelper.dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
8700             pw.println();
8701             if (dumpAll) {
8702                 pw.println("-------------------------------------------------------------------------------");
8703             }
8704             dumpPermissions(fd, pw, args, opti, dumpAll, dumpPackage);
8705             pw.println();
8706             sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage);
8707             if (!dumpClient) {
8708                 if (dumpAll) {
8709                     pw.println("-------------------------------------------------------------------------------");
8710                 }
8711                 sdumper.dumpLocked();
8712             }
8713         }
8714         // We drop the lock here because we can't call dumpWithClient() with the lock held;
8715         // if the caller wants a consistent state for the !dumpClient case, it can call this
8716         // method with the lock held.
8717         if (dumpClient) {
8718             if (dumpAll) {
8719                 pw.println("-------------------------------------------------------------------------------");
8720             }
8721             sdumper.dumpWithClient();
8722         }
8723         if (dumpPackage == null && dumpProxies) {
8724             // Intentionally dropping the lock for this, because dumpBinderProxies() will make many
8725             // outgoing binder calls to retrieve interface descriptors; while that is system code,
8726             // there is nothing preventing an app from overriding this implementation by talking to
8727             // the binder driver directly, and hang up system_server in the process. So, dump
8728             // without locks held, and even then only when there is an unreasonably large number of
8729             // proxies in the first place.
8730             pw.println();
8731             if (dumpAll) {
8732                 pw.println("-------------------------------------------------------------------------------");
8733             }
8734             dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */);
8735         }
8736         synchronized(this) {
8737             pw.println();
8738             if (dumpAll) {
8739                 pw.println("-------------------------------------------------------------------------------");
8740             }
8741             mAtmInternal.dump(
8742                     DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
8743             pw.println();
8744             if (dumpAll) {
8745                 pw.println("-------------------------------------------------------------------------------");
8746             }
8747             mAtmInternal.dump(
8748                     DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
8749             pw.println();
8750             if (dumpAll) {
8751                 pw.println("-------------------------------------------------------------------------------");
8752             }
8753             mAtmInternal.dump(
8754                     DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
8755             if (dumpPackage == null) {
8756                 pw.println();
8757                 if (dumpAll) {
8758                     pw.println("-------------------------------------------------------------------------------");
8759                 }
8760                 mAtmInternal.dump(
8761                         DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
8762             }
8763             // Activities section is dumped as part of the Critical priority dump. Exclude the
8764             // section if priority is Normal.
8765             if (!dumpNormalPriority) {
8766                 pw.println();
8767                 if (dumpAll) {
8768                     pw.println("-------------------------------------------------------------------------------");
8769                 }
8770                 mAtmInternal.dump(
8771                         DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
8772             }
8773             if (mAssociations.size() > 0) {
8774                 pw.println();
8775                 if (dumpAll) {
8776                     pw.println("-------------------------------------------------------------------------------");
8777                 }
8778                 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
8779             }
8780             pw.println();
8781             if (dumpAll) {
8782                 pw.println("-------------------------------------------------------------------------------");
8783             }
8784             mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
8785             if (dumpPackage == null) {
8786                 pw.println();
8787                 if (dumpAll) {
8788                     pw.println("-------------------------------------------------------------------------------");
8789                 }
8790                 mOomAdjProfiler.dump(pw);
8791                 pw.println();
8792                 if (dumpAll) {
8793                     pw.println("-------------------------------------------------------------------------------");
8794                 }
8795                 dumpLmkLocked(pw);
8796             }
8797             pw.println();
8798             if (dumpAll) {
8799                 pw.println("-------------------------------------------------------------------------------");
8800             }
8801             synchronized (mProcLock) {
8802                 mProcessList.dumpProcessesLSP(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId);
8803             }
8804             pw.println();
8805             if (dumpAll) {
8806                 pw.println("-------------------------------------------------------------------------------");
8807             }
8808             dumpUsers(pw);
8809         }
8810     }
8811 
8812     /**
8813      * Wrapper function to print out debug data filtered by specified arguments.
8814     */
doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)8815     private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
8816         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
8817 
8818         boolean dumpAll = false;
8819         boolean dumpClient = false;
8820         boolean dumpCheckin = false;
8821         boolean dumpCheckinFormat = false;
8822         boolean dumpNormalPriority = false;
8823         boolean dumpVisibleStacksOnly = false;
8824         boolean dumpFocusedStackOnly = false;
8825         String dumpPackage = null;
8826 
8827         int opti = 0;
8828         while (opti < args.length) {
8829             String opt = args[opti];
8830             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8831                 break;
8832             }
8833             opti++;
8834             if ("-a".equals(opt)) {
8835                 dumpAll = true;
8836             } else if ("-c".equals(opt)) {
8837                 dumpClient = true;
8838             } else if ("-v".equals(opt)) {
8839                 dumpVisibleStacksOnly = true;
8840             } else if ("-f".equals(opt)) {
8841                 dumpFocusedStackOnly = true;
8842             } else if ("-p".equals(opt)) {
8843                 if (opti < args.length) {
8844                     dumpPackage = args[opti];
8845                     opti++;
8846                 } else {
8847                     pw.println("Error: -p option requires package argument");
8848                     return;
8849                 }
8850                 dumpClient = true;
8851             } else if ("--checkin".equals(opt)) {
8852                 dumpCheckin = dumpCheckinFormat = true;
8853             } else if ("-C".equals(opt)) {
8854                 dumpCheckinFormat = true;
8855             } else if ("--normal-priority".equals(opt)) {
8856                 dumpNormalPriority = true;
8857             } else if ("-h".equals(opt)) {
8858                 ActivityManagerShellCommand.dumpHelp(pw, true);
8859                 return;
8860             } else {
8861                 pw.println("Unknown argument: " + opt + "; use -h for help");
8862             }
8863         }
8864 
8865         final long origId = Binder.clearCallingIdentity();
8866 
8867         if (useProto) {
8868             final ProtoOutputStream proto = new ProtoOutputStream(fd);
8869             String cmd = opti < args.length ? args[opti] : "";
8870             opti++;
8871 
8872             if ("activities".equals(cmd) || "a".equals(cmd)) {
8873                 // output proto is ActivityManagerServiceDumpActivitiesProto
8874                 mAtmInternal.writeActivitiesToProto(proto);
8875             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
8876                 // output proto is ActivityManagerServiceDumpBroadcastsProto
8877                 synchronized (this) {
8878                     writeBroadcastsToProtoLocked(proto);
8879                 }
8880             } else if ("provider".equals(cmd)) {
8881                 String[] newArgs;
8882                 String name;
8883                 if (opti >= args.length) {
8884                     name = null;
8885                     newArgs = EMPTY_STRING_ARRAY;
8886                 } else {
8887                     name = args[opti];
8888                     opti++;
8889                     newArgs = new String[args.length - opti];
8890                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8891                             args.length - opti);
8892                 }
8893                 if (!mCpHelper.dumpProviderProto(fd, pw, name, newArgs)) {
8894                     pw.println("No providers match: " + name);
8895                     pw.println("Use -h for help.");
8896                 }
8897             } else if ("service".equals(cmd)) {
8898                 // output proto is ActivityManagerServiceDumpServicesProto
8899                 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
8900             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
8901                 if (opti < args.length) {
8902                     dumpPackage = args[opti];
8903                     opti++;
8904                 }
8905                 // output proto is ProcessProto
8906                 synchronized (this) {
8907                     synchronized (mProcLock) {
8908                         mProcessList.writeProcessesToProtoLSP(proto, dumpPackage);
8909                     }
8910                 }
8911             } else {
8912                 // default option, dump everything, output is ActivityManagerServiceProto
8913                 synchronized (this) {
8914                     long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES);
8915                     mAtmInternal.writeActivitiesToProto(proto);
8916                     proto.end(activityToken);
8917 
8918                     long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS);
8919                     writeBroadcastsToProtoLocked(proto);
8920                     proto.end(broadcastToken);
8921 
8922                     long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES);
8923                     mServices.dumpDebug(proto,
8924                             ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
8925                     proto.end(serviceToken);
8926 
8927                     long processToken = proto.start(ActivityManagerServiceProto.PROCESSES);
8928                     synchronized (mProcLock) {
8929                         mProcessList.writeProcessesToProtoLSP(proto, dumpPackage);
8930                     }
8931                     proto.end(processToken);
8932                 }
8933             }
8934             proto.flush();
8935             Binder.restoreCallingIdentity(origId);
8936             return;
8937         }
8938 
8939         int dumpAppId = getAppId(dumpPackage);
8940         boolean more = false;
8941         // Is the caller requesting to dump a particular piece of data?
8942         if (opti < args.length) {
8943             String cmd = args[opti];
8944             opti++;
8945             if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
8946                     || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
8947                     || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
8948                     || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)
8949                     || DUMP_TOP_RESUMED_ACTIVITY.equals(cmd)) {
8950                 mAtmInternal.dump(
8951                         cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage);
8952             } else if ("binder-proxies".equals(cmd)) {
8953                 if (opti >= args.length) {
8954                     dumpBinderProxies(pw, 0 /* minToDump */);
8955                 } else {
8956                     String uid = args[opti];
8957                     opti++;
8958                     // Ensure Binder Proxy Count is as up to date as possible
8959                     System.gc();
8960                     System.runFinalization();
8961                     System.gc();
8962                     pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid)));
8963                 }
8964             } else if ("allowed-associations".equals(cmd)) {
8965                 if (opti < args.length) {
8966                     dumpPackage = args[opti];
8967                     opti++;
8968                 }
8969                 synchronized (this) {
8970                     dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage);
8971                 }
8972             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
8973                 if (opti < args.length) {
8974                     dumpPackage = args[opti];
8975                     opti++;
8976                 }
8977                 synchronized (this) {
8978                     dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage);
8979                 }
8980             } else if ("broadcast-stats".equals(cmd)) {
8981                 if (opti < args.length) {
8982                     dumpPackage = args[opti];
8983                     opti++;
8984                 }
8985                 synchronized (this) {
8986                     if (dumpCheckinFormat) {
8987                         dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
8988                                 dumpPackage);
8989                     } else {
8990                         dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
8991                     }
8992                 }
8993             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
8994                 if (opti < args.length) {
8995                     dumpPackage = args[opti];
8996                     opti++;
8997                 }
8998                 mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage);
8999             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
9000                 if (opti < args.length) {
9001                     dumpPackage = args[opti];
9002                     opti++;
9003                 }
9004                 synchronized (this) {
9005                     synchronized (mProcLock) {
9006                         mProcessList.dumpProcessesLSP(
9007                                 fd, pw, args, opti, true, dumpPackage, dumpAppId);
9008                     }
9009                 }
9010             } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9011                 synchronized (this) {
9012                     mProcessList.dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true);
9013                 }
9014             } else if ("lmk".equals(cmd)) {
9015                 synchronized (this) {
9016                     dumpLmkLocked(pw);
9017                 }
9018             } else if ("lru".equals(cmd)) {
9019                 synchronized (this) {
9020                     mProcessList.dumpLruLocked(pw, dumpPackage, null);
9021                 }
9022             } else if ("permissions".equals(cmd) || "perm".equals(cmd)) {
9023                 dumpPermissions(fd, pw, args, opti, true, dumpPackage);
9024             } else if ("provider".equals(cmd)) {
9025                 String[] newArgs;
9026                 String name;
9027                 if (opti >= args.length) {
9028                     name = null;
9029                     newArgs = EMPTY_STRING_ARRAY;
9030                 } else {
9031                     name = args[opti];
9032                     opti++;
9033                     newArgs = new String[args.length - opti];
9034                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9035                 }
9036                 if (!mCpHelper.dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9037                     pw.println("No providers match: " + name);
9038                     pw.println("Use -h for help.");
9039                 }
9040             } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9041                 synchronized (this) {
9042                     mCpHelper.dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage);
9043                 }
9044             } else if ("service".equals(cmd)) {
9045                 String[] newArgs;
9046                 String name;
9047                 int[] users = null;
9048                 if (opti >= args.length) {
9049                     name = null;
9050                     newArgs = EMPTY_STRING_ARRAY;
9051                 } else {
9052                     name = args[opti];
9053                     opti++;
9054                     if ("--user".equals(name) && opti < args.length) {
9055                         int userId = UserHandle.parseUserArg(args[opti]);
9056                         opti++;
9057                         if (userId != UserHandle.USER_ALL) {
9058                             if (userId == UserHandle.USER_CURRENT) {
9059                                 userId = getCurrentUser().id;
9060                             }
9061                             users = new int[] { userId };
9062                         }
9063                         name = args[opti];
9064                         opti++;
9065                     }
9066                     newArgs = new String[args.length - opti];
9067                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9068                             args.length - opti);
9069                 }
9070                 if (!mServices.dumpService(fd, pw, name, users, newArgs, 0, dumpAll)) {
9071                     pw.println("No services match: " + name);
9072                     pw.println("Use -h for help.");
9073                 }
9074             } else if ("package".equals(cmd)) {
9075                 String[] newArgs;
9076                 if (opti >= args.length) {
9077                     pw.println("package: no package name specified");
9078                     pw.println("Use -h for help.");
9079                 } else {
9080                     dumpPackage = args[opti];
9081                     opti++;
9082                     newArgs = new String[args.length - opti];
9083                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9084                             args.length - opti);
9085                     args = newArgs;
9086                     opti = 0;
9087                     more = true;
9088                 }
9089             } else if ("associations".equals(cmd) || "as".equals(cmd)) {
9090                 synchronized (this) {
9091                     dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage);
9092                 }
9093             } else if ("settings".equals(cmd)) {
9094                 synchronized (this) {
9095                     mConstants.dump(pw);
9096                 }
9097                 synchronized (mProcLock) {
9098                     mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
9099                     mOomAdjuster.dumpCacheOomRankerSettings(pw);
9100                 }
9101             } else if ("services".equals(cmd) || "s".equals(cmd)) {
9102                 if (dumpClient) {
9103                     ActiveServices.ServiceDumper dumper;
9104                     synchronized (this) {
9105                         dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true,
9106                                 dumpPackage);
9107                     }
9108                     dumper.dumpWithClient();
9109                 } else {
9110                     synchronized (this) {
9111                         mServices.newServiceDumperLocked(fd, pw, args, opti, true,
9112                                 dumpPackage).dumpLocked();
9113                     }
9114                 }
9115             } else if ("locks".equals(cmd)) {
9116                 LockGuard.dump(fd, pw, args);
9117             } else if ("users".equals(cmd)) {
9118                 dumpUsers(pw);
9119             } else if ("exit-info".equals(cmd)) {
9120                 if (opti < args.length) {
9121                     dumpPackage = args[opti];
9122                     opti++;
9123                 }
9124                 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
9125             } else {
9126                 // Dumping a single activity?
9127                 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll,
9128                         dumpVisibleStacksOnly, dumpFocusedStackOnly)) {
9129                     ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true);
9130                     int res = shell.exec(this, null, fd, null, args, null,
9131                             new ResultReceiver(null));
9132                     if (res < 0) {
9133                         pw.println("Bad activity command, or no activities match: " + cmd);
9134                         pw.println("Use -h for help.");
9135                     }
9136                 }
9137             }
9138             if (!more) {
9139                 Binder.restoreCallingIdentity(origId);
9140                 return;
9141             }
9142         }
9143 
9144         // No piece of data specified, dump everything.
9145         if (dumpCheckinFormat) {
9146             dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage);
9147         } else {
9148             if (dumpClient) {
9149                 // dumpEverything() will take the lock when needed, and momentarily drop
9150                 // it for dumping client state.
9151                 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
9152                         dumpNormalPriority, dumpAppId, true /* dumpProxies */);
9153             } else {
9154                 // Take the lock here, so we get a consistent state for the entire dump;
9155                 // dumpEverything() will take the lock as well, which is fine for everything
9156                 // except dumping proxies, which can take a long time; exclude them.
9157                 synchronized(this) {
9158                     dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
9159                             dumpNormalPriority, dumpAppId, false /* dumpProxies */);
9160                 }
9161             }
9162         }
9163         Binder.restoreCallingIdentity(origId);
9164     }
9165 
dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)9166     void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9167             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
9168         pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)");
9169 
9170         int dumpUid = 0;
9171         if (dumpPackage != null) {
9172             IPackageManager pm = AppGlobals.getPackageManager();
9173             try {
9174                 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0);
9175             } catch (RemoteException e) {
9176             }
9177         }
9178 
9179         boolean printedAnything = false;
9180 
9181         final long now = SystemClock.uptimeMillis();
9182 
9183         for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
9184             ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
9185                     = mAssociations.valueAt(i1);
9186             for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
9187                 SparseArray<ArrayMap<String, Association>> sourceUids
9188                         = targetComponents.valueAt(i2);
9189                 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) {
9190                     ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3);
9191                     for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
9192                         Association ass = sourceProcesses.valueAt(i4);
9193                         if (dumpPackage != null) {
9194                             if (!ass.mTargetComponent.getPackageName().equals(dumpPackage)
9195                                     && UserHandle.getAppId(ass.mSourceUid) != dumpUid) {
9196                                 continue;
9197                             }
9198                         }
9199                         printedAnything = true;
9200                         pw.print("  ");
9201                         pw.print(ass.mTargetProcess);
9202                         pw.print("/");
9203                         UserHandle.formatUid(pw, ass.mTargetUid);
9204                         pw.print(" <- ");
9205                         pw.print(ass.mSourceProcess);
9206                         pw.print("/");
9207                         UserHandle.formatUid(pw, ass.mSourceUid);
9208                         pw.println();
9209                         pw.print("    via ");
9210                         pw.print(ass.mTargetComponent.flattenToShortString());
9211                         pw.println();
9212                         pw.print("    ");
9213                         long dur = ass.mTime;
9214                         if (ass.mNesting > 0) {
9215                             dur += now - ass.mStartTime;
9216                         }
9217                         TimeUtils.formatDuration(dur, pw);
9218                         pw.print(" (");
9219                         pw.print(ass.mCount);
9220                         pw.print(" times)");
9221                         pw.print("  ");
9222                         for (int i=0; i<ass.mStateTimes.length; i++) {
9223                             long amt = ass.mStateTimes[i];
9224                             if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
9225                                 amt += now - ass.mLastStateUptime;
9226                             }
9227                             if (amt != 0) {
9228                                 pw.print(" ");
9229                                 pw.print(ProcessList.makeProcStateString(
9230                                             i + ActivityManager.MIN_PROCESS_STATE));
9231                                 pw.print("=");
9232                                 TimeUtils.formatDuration(amt, pw);
9233                                 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
9234                                     pw.print("*");
9235                                 }
9236                             }
9237                         }
9238                         pw.println();
9239                         if (ass.mNesting > 0) {
9240                             pw.print("    Currently active: ");
9241                             TimeUtils.formatDuration(now - ass.mStartTime, pw);
9242                             pw.println();
9243                         }
9244                     }
9245                 }
9246             }
9247 
9248         }
9249 
9250         if (!printedAnything) {
9251             pw.println("  (nothing)");
9252         }
9253     }
9254 
getAppId(String dumpPackage)9255     int getAppId(String dumpPackage) {
9256         if (dumpPackage != null) {
9257             try {
9258                 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
9259                         dumpPackage, 0);
9260                 return UserHandle.getAppId(info.uid);
9261             } catch (NameNotFoundException e) {
9262                 e.printStackTrace();
9263             }
9264         }
9265         return -1;
9266     }
9267 
dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)9268     void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) {
9269         final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50);
9270 
9271         pw.println(header);
9272         for (int i = 0; i < proxyCounts.length; i++) {
9273             pw.println("    #" + (i + 1) + ": " + proxyCounts[i]);
9274         }
9275     }
9276 
dumpBinderProxiesCounts(PrintWriter pw, String header)9277     boolean dumpBinderProxiesCounts(PrintWriter pw, String header) {
9278         SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
9279         if(counts != null) {
9280             pw.println(header);
9281             for (int i = 0; i < counts.size(); i++) {
9282                 final int uid = counts.keyAt(i);
9283                 final int binderCount = counts.valueAt(i);
9284                 pw.print("    UID ");
9285                 pw.print(uid);
9286                 pw.print(", binder count = ");
9287                 pw.print(binderCount);
9288                 pw.print(", package(s)= ");
9289                 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid);
9290                 if (pkgNames != null) {
9291                     for (int j = 0; j < pkgNames.length; j++) {
9292                         pw.print(pkgNames[j]);
9293                         pw.print("; ");
9294                     }
9295                 } else {
9296                     pw.print("NO PACKAGE NAME FOUND");
9297                 }
9298                 pw.println();
9299             }
9300             return true;
9301         }
9302         return false;
9303     }
9304 
dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)9305     void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) {
9306         pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)");
9307         final int proxyCount = BinderProxy.getProxyCount();
9308         if (proxyCount >= minCountToDumpInterfaces) {
9309             dumpBinderProxyInterfaceCounts(pw,
9310                     "Top proxy interface names held by SYSTEM");
9311         } else {
9312             pw.print("Not dumping proxy interface counts because size ("
9313                     + Integer.toString(proxyCount) + ") looks reasonable");
9314             pw.println();
9315         }
9316         dumpBinderProxiesCounts(pw,
9317                 "  Counts of Binder Proxies held by SYSTEM");
9318     }
9319 
9320     @GuardedBy("this")
dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep)9321     boolean dumpActiveInstruments(PrintWriter pw, String dumpPackage, boolean needSep) {
9322         final int size = mActiveInstrumentation.size();
9323         if (size > 0) {
9324             boolean printed = false;
9325             for (int i = 0; i < size; i++) {
9326                 ActiveInstrumentation ai = mActiveInstrumentation.get(i);
9327                 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
9328                         && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
9329                     continue;
9330                 }
9331                 if (!printed) {
9332                     if (needSep) {
9333                         pw.println();
9334                     }
9335                     pw.println("  Active instrumentation:");
9336                     printed = true;
9337                     needSep = true;
9338                 }
9339                 pw.print("    Instrumentation #"); pw.print(i); pw.print(": ");
9340                 pw.println(ai);
9341                 ai.dump(pw, "      ");
9342             }
9343         }
9344         return needSep;
9345     }
9346 
9347     @GuardedBy({"this", "mProcLock"})
dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw, boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep)9348     void dumpOtherProcessesInfoLSP(FileDescriptor fd, PrintWriter pw,
9349             boolean dumpAll, String dumpPackage, int dumpAppId, int numPers, boolean needSep) {
9350         if (dumpAll || dumpPackage != null) {
9351             final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>();
9352             synchronized (mPidsSelfLocked) {
9353                 boolean printed = false;
9354                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
9355                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
9356                     pidToProcess.put(r.getPid(), r);
9357                     if (dumpPackage != null && !r.getPkgList().containsKey(dumpPackage)) {
9358                         continue;
9359                     }
9360                     if (!printed) {
9361                         if (needSep) pw.println();
9362                         needSep = true;
9363                         pw.println("  PID mappings:");
9364                         printed = true;
9365                     }
9366                     pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9367                     pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
9368                 }
9369             }
9370 
9371             synchronized (sActiveProcessInfoSelfLocked) {
9372                 boolean printed = false;
9373                 for (int i = 0, size = sActiveProcessInfoSelfLocked.size(); i < size; i++) {
9374                     ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i);
9375                     ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i));
9376                     if (r != null && dumpPackage != null
9377                             && !r.getPkgList().containsKey(dumpPackage)) {
9378                         continue;
9379                     }
9380                     if (!printed) {
9381                         if (needSep) pw.println();
9382                         needSep = true;
9383                         pw.println("  Active process infos:");
9384                         printed = true;
9385                     }
9386                     pw.print("    Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i));
9387                     pw.println(":");
9388                     pw.print("      name="); pw.println(info.name);
9389                     if (info.deniedPermissions != null) {
9390                         for (int j = 0; j < info.deniedPermissions.size(); j++) {
9391                             pw.print("      deny: ");
9392                             pw.println(info.deniedPermissions.valueAt(i));
9393                         }
9394                     }
9395                 }
9396             }
9397         }
9398 
9399         if (dumpAll) {
9400             mPhantomProcessList.dump(pw, "  ");
9401         }
9402 
9403         if (mImportantProcesses.size() > 0) {
9404             synchronized (mPidsSelfLocked) {
9405                 boolean printed = false;
9406                 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) {
9407                     ProcessRecord r = mPidsSelfLocked.get(mImportantProcesses.valueAt(i).pid);
9408                     if (dumpPackage != null && (r == null
9409                             || !r.getPkgList().containsKey(dumpPackage))) {
9410                         continue;
9411                     }
9412                     if (!printed) {
9413                         if (needSep) pw.println();
9414                         needSep = true;
9415                         pw.println("  Foreground Processes:");
9416                         printed = true;
9417                     }
9418                     pw.print("    PID #"); pw.print(mImportantProcesses.keyAt(i));
9419                             pw.print(": "); pw.println(mImportantProcesses.valueAt(i));
9420                 }
9421             }
9422         }
9423 
9424         if (mPersistentStartingProcesses.size() > 0) {
9425             if (needSep) pw.println();
9426             needSep = true;
9427             pw.println("  Persisent processes that are starting:");
9428             dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
9429                     "Starting Norm", "Restarting PERS", dumpPackage);
9430         }
9431 
9432         if (mProcessList.mRemovedProcesses.size() > 0) {
9433             if (needSep) pw.println();
9434             needSep = true;
9435             pw.println("  Processes that are being removed:");
9436             dumpProcessList(pw, this, mProcessList.mRemovedProcesses, "    ",
9437                     "Removed Norm", "Removed PERS", dumpPackage);
9438         }
9439 
9440         if (mProcessesOnHold.size() > 0) {
9441             if (needSep) pw.println();
9442             needSep = true;
9443             pw.println("  Processes that are on old until the system is ready:");
9444             dumpProcessList(pw, this, mProcessesOnHold, "    ",
9445                     "OnHold Norm", "OnHold PERS", dumpPackage);
9446         }
9447 
9448         needSep = mAppErrors.dumpLPr(fd, pw, needSep, dumpPackage);
9449 
9450         needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep,
9451                 mAppProfiler.getTestPssMode(), mWakefulness.get());
9452 
9453         if (dumpAll && mProcessList.mPendingStarts.size() > 0) {
9454             if (needSep) pw.println();
9455             needSep = true;
9456             pw.println("  mPendingStarts: ");
9457             for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) {
9458                 pw.println("    " + mProcessList.mPendingStarts.keyAt(i) + ": "
9459                         + mProcessList.mPendingStarts.valueAt(i));
9460             }
9461         }
9462         if (dumpAll) {
9463             mUidObserverController.dump(pw, dumpPackage);
9464 
9465             pw.println("  mDeviceIdleAllowlist=" + Arrays.toString(mDeviceIdleAllowlist));
9466             pw.println("  mDeviceIdleExceptIdleAllowlist="
9467                     + Arrays.toString(mDeviceIdleExceptIdleAllowlist));
9468             pw.println("  mDeviceIdleTempAllowlist=" + Arrays.toString(mDeviceIdleTempAllowlist));
9469             if (mPendingTempAllowlist.size() > 0) {
9470                 pw.println("  mPendingTempAllowlist:");
9471                 for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) {
9472                     PendingTempAllowlist ptw = mPendingTempAllowlist.valueAt(i);
9473                     pw.print("    ");
9474                     UserHandle.formatUid(pw, ptw.targetUid);
9475                     pw.print(": ");
9476                     TimeUtils.formatDuration(ptw.duration, pw);
9477                     pw.print(" ");
9478                     pw.println(ptw.tag);
9479                     pw.print(" ");
9480                     pw.print(ptw.type);
9481                     pw.print(" ");
9482                     pw.print(ptw.reasonCode);
9483                     pw.print(" ");
9484                     pw.print(ptw.callingUid);
9485                 }
9486             }
9487             pw.println("  mFgsStartTempAllowList:");
9488             final long currentTimeNow = System.currentTimeMillis();
9489             final long elapsedRealtimeNow = SystemClock.elapsedRealtime();
9490             mFgsStartTempAllowList.forEach((uid, entry) -> {
9491                 pw.print("    " + UserHandle.formatUid(uid) + ": ");
9492                 entry.second.dump(pw);
9493                 pw.print(" expiration=");
9494                 // Convert entry.mExpirationTime, which is an elapsed time since boot,
9495                 // to a time since epoch (i.e. System.currentTimeMillis()-based time.)
9496                 final long expirationInCurrentTime =
9497                         currentTimeNow - elapsedRealtimeNow + entry.first;
9498                 TimeUtils.dumpTimeWithDelta(pw, expirationInCurrentTime, currentTimeNow);
9499                 pw.println();
9500             });
9501         }
9502         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9503                 || mOrigWaitForDebugger) {
9504             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
9505                     || dumpPackage.equals(mOrigDebugApp)) {
9506                 if (needSep) {
9507                     pw.println();
9508                     needSep = false;
9509                 }
9510                 pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9511                         + " mDebugTransient=" + mDebugTransient
9512                         + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9513             }
9514         }
9515         synchronized (mAppProfiler.mProfilerLock) {
9516             needSep = mAppProfiler.dumpMemWatchProcessesLPf(pw, needSep);
9517         }
9518         if (mTrackAllocationApp != null) {
9519             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
9520                 if (needSep) {
9521                     pw.println();
9522                     needSep = false;
9523                 }
9524                 pw.println("  mTrackAllocationApp=" + mTrackAllocationApp);
9525             }
9526         }
9527         needSep = mAppProfiler.dumpProfileDataLocked(pw, dumpPackage, needSep);
9528         if (mNativeDebuggingApp != null) {
9529             if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
9530                 if (needSep) {
9531                     pw.println();
9532                     needSep = false;
9533                 }
9534                 pw.println("  mNativeDebuggingApp=" + mNativeDebuggingApp);
9535             }
9536         }
9537         if (dumpPackage == null) {
9538             if (mAlwaysFinishActivities) {
9539                 pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities);
9540             }
9541             if (dumpAll) {
9542                 pw.println("  Total persistent processes: " + numPers);
9543                 pw.println("  mProcessesReady=" + mProcessesReady
9544                         + " mSystemReady=" + mSystemReady
9545                         + " mBooted=" + mBooted
9546                         + " mFactoryTest=" + mFactoryTest);
9547                 pw.println("  mBooting=" + mBooting
9548                         + " mCallFinishBooting=" + mCallFinishBooting
9549                         + " mBootAnimationComplete=" + mBootAnimationComplete);
9550                 pw.print("  mLastPowerCheckUptime=");
9551                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9552                         pw.println("");
9553                 mOomAdjuster.dumpSequenceNumbersLocked(pw);
9554                 mOomAdjuster.dumpProcCountsLocked(pw);
9555                 mAppProfiler.dumpMemoryLevelsLocked(pw);
9556                 long now = SystemClock.uptimeMillis();
9557                 pw.print("  mLastIdleTime=");
9558                         TimeUtils.formatDuration(now, mLastIdleTime, pw);
9559                         pw.print(" mLowRamSinceLastIdle=");
9560                         TimeUtils.formatDuration(
9561                                 mAppProfiler.getLowRamTimeSinceIdleLPr(now), pw);
9562                         pw.println();
9563 
9564                 pw.println();
9565                 pw.println("  ServiceManager statistics:");
9566                 ServiceManager.sStatLogger.dump(pw, "    ");
9567                 pw.println();
9568             }
9569         }
9570         pw.println("  mForceBackgroundCheck=" + mForceBackgroundCheck);
9571     }
9572 
dumpUsers(PrintWriter pw)9573     private void dumpUsers(PrintWriter pw) {
9574         pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)");
9575         mUserController.dump(pw);
9576     }
9577 
9578     @GuardedBy({"this", "mProcLock"})
writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage, int dumpAppId, int numPers)9579     void writeOtherProcessesInfoToProtoLSP(ProtoOutputStream proto, String dumpPackage,
9580             int dumpAppId, int numPers) {
9581         for (int i = 0, size = mActiveInstrumentation.size(); i < size; i++) {
9582             ActiveInstrumentation ai = mActiveInstrumentation.get(i);
9583             if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
9584                     && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
9585                 continue;
9586             }
9587             ai.dumpDebug(proto,
9588                     ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS);
9589         }
9590 
9591         mUidObserverController.dumpValidateUidsProto(proto, dumpPackage, dumpAppId,
9592                 ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS);
9593 
9594         if (dumpPackage != null) {
9595             synchronized (mPidsSelfLocked) {
9596                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
9597                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
9598                     if (!r.getPkgList().containsKey(dumpPackage)) {
9599                         continue;
9600                     }
9601                     r.dumpDebug(proto,
9602                             ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED);
9603                 }
9604             }
9605         }
9606 
9607         if (mImportantProcesses.size() > 0) {
9608             synchronized (mPidsSelfLocked) {
9609                 for (int i = 0, size = mImportantProcesses.size(); i < size; i++) {
9610                     ImportanceToken it = mImportantProcesses.valueAt(i);
9611                     ProcessRecord r = mPidsSelfLocked.get(it.pid);
9612                     if (dumpPackage != null && (r == null
9613                             || !r.getPkgList().containsKey(dumpPackage))) {
9614                         continue;
9615                     }
9616                     it.dumpDebug(proto,
9617                             ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS);
9618                 }
9619             }
9620         }
9621 
9622         for (int i = 0, size = mPersistentStartingProcesses.size(); i < size; i++) {
9623             ProcessRecord r = mPersistentStartingProcesses.get(i);
9624             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9625                 continue;
9626             }
9627             r.dumpDebug(proto,
9628                     ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS);
9629         }
9630 
9631         for (int i = 0, size = mProcessList.mRemovedProcesses.size(); i < size; i++) {
9632             ProcessRecord r = mProcessList.mRemovedProcesses.get(i);
9633             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9634                 continue;
9635             }
9636             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS);
9637         }
9638 
9639         for (int i = 0, size = mProcessesOnHold.size(); i < size; i++) {
9640             ProcessRecord r = mProcessesOnHold.get(i);
9641             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9642                 continue;
9643             }
9644             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS);
9645         }
9646 
9647         synchronized (mAppProfiler.mProfilerLock) {
9648             mAppProfiler.writeProcessesToGcToProto(proto,
9649                     ActivityManagerServiceDumpProcessesProto.GC_PROCS,
9650                     dumpPackage);
9651         }
9652         mAppErrors.dumpDebugLPr(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS,
9653                 dumpPackage);
9654         mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness.get(),
9655                 mAppProfiler.getTestPssMode());
9656 
9657         if (dumpPackage == null) {
9658             mUserController.dumpDebug(proto,
9659             ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER);
9660         }
9661 
9662         mUidObserverController.dumpDebug(proto, dumpPackage);
9663 
9664         for (int v : mDeviceIdleAllowlist) {
9665             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v);
9666         }
9667 
9668         for (int v : mDeviceIdleTempAllowlist) {
9669             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v);
9670         }
9671 
9672         if (mPendingTempAllowlist.size() > 0) {
9673             for (int i = 0, size = mPendingTempAllowlist.size(); i < size; i++) {
9674                 mPendingTempAllowlist.valueAt(i).dumpDebug(proto,
9675                         ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST);
9676             }
9677         }
9678 
9679         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9680                 || mOrigWaitForDebugger) {
9681             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
9682                     || dumpPackage.equals(mOrigDebugApp)) {
9683                 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG);
9684                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp);
9685                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp);
9686                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient);
9687                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger);
9688                 proto.end(debugAppToken);
9689             }
9690         }
9691 
9692         synchronized (mAppProfiler.mProfilerLock) {
9693             mAppProfiler.writeMemWatchProcessToProtoLPf(proto);
9694         }
9695 
9696         if (mTrackAllocationApp != null) {
9697             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
9698                 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP,
9699                         mTrackAllocationApp);
9700             }
9701         }
9702 
9703         mAppProfiler.writeProfileDataToProtoLocked(proto, dumpPackage);
9704 
9705         if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
9706             proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp);
9707         }
9708 
9709         if (dumpPackage == null) {
9710             proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities);
9711             proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers);
9712             proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady);
9713             proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady);
9714             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted);
9715             proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest);
9716             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting);
9717             proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting);
9718             proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete);
9719             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime);
9720             mOomAdjuster.dumpProcessListVariablesLocked(proto);
9721             mAppProfiler.writeMemoryLevelsToProtoLocked(proto);
9722             long now = SystemClock.uptimeMillis();
9723             ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now);
9724             proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS,
9725                     mAppProfiler.getLowRamTimeSinceIdleLPr(now));
9726         }
9727     }
9728 
reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)9729     private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) {
9730         Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj);
9731         if (cnt != null) {
9732             pw.println("    kills at or below oom_adj " + oom_adj + ": " + cnt);
9733             return true;
9734         }
9735         return false;
9736     }
9737 
dumpLmkLocked(PrintWriter pw)9738     boolean dumpLmkLocked(PrintWriter pw) {
9739         pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)");
9740         Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ,
9741                 ProcessList.UNKNOWN_ADJ);
9742         if (cnt == null) {
9743             return false;
9744         }
9745         pw.println("  Total number of kills: " + cnt);
9746 
9747         return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) &&
9748                 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) &&
9749                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) &&
9750                 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) &&
9751                 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) &&
9752                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) &&
9753                 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) &&
9754                 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) &&
9755                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) &&
9756                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) &&
9757                 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) &&
9758                 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ);
9759     }
9760 
9761     public static class ItemMatcher {
9762         ArrayList<ComponentName> components;
9763         ArrayList<String> strings;
9764         ArrayList<Integer> objects;
9765         boolean all;
9766 
ItemMatcher()9767         public ItemMatcher() {
9768             all = true;
9769         }
9770 
build(String name)9771         public void build(String name) {
9772             ComponentName componentName = ComponentName.unflattenFromString(name);
9773             if (componentName != null) {
9774                 if (components == null) {
9775                     components = new ArrayList<ComponentName>();
9776                 }
9777                 components.add(componentName);
9778                 all = false;
9779             } else {
9780                 int objectId = 0;
9781                 // Not a '/' separated full component name; maybe an object ID?
9782                 try {
9783                     objectId = Integer.parseInt(name, 16);
9784                     if (objects == null) {
9785                         objects = new ArrayList<Integer>();
9786                     }
9787                     objects.add(objectId);
9788                     all = false;
9789                 } catch (RuntimeException e) {
9790                     // Not an integer; just do string match.
9791                     if (strings == null) {
9792                         strings = new ArrayList<String>();
9793                     }
9794                     strings.add(name);
9795                     all = false;
9796                 }
9797             }
9798         }
9799 
build(String[] args, int opti)9800         public int build(String[] args, int opti) {
9801             for (; opti<args.length; opti++) {
9802                 String name = args[opti];
9803                 if ("--".equals(name)) {
9804                     return opti+1;
9805                 }
9806                 build(name);
9807             }
9808             return opti;
9809         }
9810 
match(Object object, ComponentName comp)9811         public boolean match(Object object, ComponentName comp) {
9812             if (all) {
9813                 return true;
9814             }
9815             if (components != null) {
9816                 for (int i=0; i<components.size(); i++) {
9817                     if (components.get(i).equals(comp)) {
9818                         return true;
9819                     }
9820                 }
9821             }
9822             if (objects != null) {
9823                 for (int i=0; i<objects.size(); i++) {
9824                     if (System.identityHashCode(object) == objects.get(i)) {
9825                         return true;
9826                     }
9827                 }
9828             }
9829             if (strings != null) {
9830                 String flat = comp.flattenToString();
9831                 for (int i=0; i<strings.size(); i++) {
9832                     if (flat.contains(strings.get(i))) {
9833                         return true;
9834                     }
9835                 }
9836             }
9837             return false;
9838         }
9839     }
9840 
writeBroadcastsToProtoLocked(ProtoOutputStream proto)9841     void writeBroadcastsToProtoLocked(ProtoOutputStream proto) {
9842         if (mRegisteredReceivers.size() > 0) {
9843             Iterator it = mRegisteredReceivers.values().iterator();
9844             while (it.hasNext()) {
9845                 ReceiverList r = (ReceiverList)it.next();
9846                 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST);
9847             }
9848         }
9849         mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER);
9850         for (BroadcastQueue q : mBroadcastQueues) {
9851             q.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE);
9852         }
9853         for (int user=0; user<mStickyBroadcasts.size(); user++) {
9854             long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS);
9855             proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user));
9856             for (Map.Entry<String, ArrayList<Intent>> ent
9857                     : mStickyBroadcasts.valueAt(user).entrySet()) {
9858                 long actionToken = proto.start(StickyBroadcastProto.ACTIONS);
9859                 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey());
9860                 for (Intent intent : ent.getValue()) {
9861                     intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS,
9862                             false, true, true, false);
9863                 }
9864                 proto.end(actionToken);
9865             }
9866             proto.end(token);
9867         }
9868 
9869         long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER);
9870         proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString());
9871         mHandler.getLooper().dumpDebug(proto,
9872             ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER);
9873         proto.end(handlerToken);
9874     }
9875 
dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)9876     void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9877             int opti, boolean dumpAll, String dumpPackage) {
9878         pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)");
9879         boolean printed = false;
9880         if (mAllowedAssociations != null) {
9881             for (int i = 0; i < mAllowedAssociations.size(); i++) {
9882                 final String pkg = mAllowedAssociations.keyAt(i);
9883                 final ArraySet<String> asc =
9884                         mAllowedAssociations.valueAt(i).getAllowedPackageAssociations();
9885                 if (!printed) {
9886                     pw.println("  Allowed associations (by restricted package):");
9887                     printed = true;
9888                 }
9889                 pw.print("  * ");
9890                 pw.print(pkg);
9891                 pw.println(":");
9892                 for (int j = 0; j < asc.size(); j++) {
9893                     if (dumpPackage == null || pkg.equals(dumpPackage)
9894                             || asc.valueAt(j).equals(dumpPackage)) {
9895                         pw.print("      Allow: ");
9896                         pw.println(asc.valueAt(j));
9897                     }
9898                 }
9899                 if (mAllowedAssociations.valueAt(i).isDebuggable()) {
9900                     pw.println("      (debuggable)");
9901                 }
9902             }
9903         }
9904         if (!printed) {
9905             pw.println("  (No association restrictions)");
9906         }
9907     }
9908 
dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)9909     void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9910             int opti, boolean dumpAll, String dumpPackage) {
9911         boolean needSep = false;
9912         boolean onlyHistory = false;
9913         boolean printedAnything = false;
9914 
9915         if ("history".equals(dumpPackage)) {
9916             if (opti < args.length && "-s".equals(args[opti])) {
9917                 dumpAll = false;
9918             }
9919             onlyHistory = true;
9920             dumpPackage = null;
9921         }
9922 
9923         pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
9924         if (!onlyHistory && dumpAll) {
9925             if (mRegisteredReceivers.size() > 0) {
9926                 boolean printed = false;
9927                 Iterator it = mRegisteredReceivers.values().iterator();
9928                 while (it.hasNext()) {
9929                     ReceiverList r = (ReceiverList)it.next();
9930                     if (dumpPackage != null && (r.app == null ||
9931                             !dumpPackage.equals(r.app.info.packageName))) {
9932                         continue;
9933                     }
9934                     if (!printed) {
9935                         pw.println("  Registered Receivers:");
9936                         needSep = true;
9937                         printed = true;
9938                         printedAnything = true;
9939                     }
9940                     pw.print("  * "); pw.println(r);
9941                     r.dump(pw, "    ");
9942                 }
9943             }
9944 
9945             if (mReceiverResolver.dump(pw, needSep ?
9946                     "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
9947                     "    ", dumpPackage, false, false)) {
9948                 needSep = true;
9949                 printedAnything = true;
9950             }
9951         }
9952 
9953         for (BroadcastQueue q : mBroadcastQueues) {
9954             needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
9955             printedAnything |= needSep;
9956         }
9957 
9958         needSep = true;
9959 
9960         if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
9961             for (int user=0; user<mStickyBroadcasts.size(); user++) {
9962                 if (needSep) {
9963                     pw.println();
9964                 }
9965                 needSep = true;
9966                 printedAnything = true;
9967                 pw.print("  Sticky broadcasts for user ");
9968                         pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9969                 StringBuilder sb = new StringBuilder(128);
9970                 for (Map.Entry<String, ArrayList<Intent>> ent
9971                         : mStickyBroadcasts.valueAt(user).entrySet()) {
9972                     pw.print("  * Sticky action "); pw.print(ent.getKey());
9973                     if (dumpAll) {
9974                         pw.println(":");
9975                         ArrayList<Intent> intents = ent.getValue();
9976                         final int N = intents.size();
9977                         for (int i=0; i<N; i++) {
9978                             sb.setLength(0);
9979                             sb.append("    Intent: ");
9980                             intents.get(i).toShortString(sb, false, true, false, false);
9981                             pw.println(sb.toString());
9982                             Bundle bundle = intents.get(i).getExtras();
9983                             if (bundle != null) {
9984                                 pw.print("      ");
9985                                 pw.println(bundle.toString());
9986                             }
9987                         }
9988                     } else {
9989                         pw.println("");
9990                     }
9991                 }
9992             }
9993         }
9994 
9995         if (!onlyHistory && dumpAll) {
9996             pw.println();
9997             for (BroadcastQueue queue : mBroadcastQueues) {
9998                 pw.println("  mBroadcastsScheduled [" + queue.mQueueName + "]="
9999                         + queue.mBroadcastsScheduled);
10000             }
10001             pw.println("  mHandler:");
10002             mHandler.dump(new PrintWriterPrinter(pw), "    ");
10003             needSep = true;
10004             printedAnything = true;
10005         }
10006 
10007         if (!printedAnything) {
10008             pw.println("  (nothing)");
10009         }
10010     }
10011 
dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10012     void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10013             int opti, boolean dumpAll, String dumpPackage) {
10014         if (mCurBroadcastStats == null) {
10015             return;
10016         }
10017 
10018         pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)");
10019         final long now = SystemClock.elapsedRealtime();
10020         if (mLastBroadcastStats != null) {
10021             pw.print("  Last stats (from ");
10022             TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw);
10023             pw.print(" to ");
10024             TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw);
10025             pw.print(", ");
10026             TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime
10027                     - mLastBroadcastStats.mStartUptime, pw);
10028             pw.println(" uptime):");
10029             if (!mLastBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
10030                 pw.println("    (nothing)");
10031             }
10032             pw.println();
10033         }
10034         pw.print("  Current stats (from ");
10035         TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw);
10036         pw.print(" to now, ");
10037         TimeUtils.formatDuration(SystemClock.uptimeMillis()
10038                 - mCurBroadcastStats.mStartUptime, pw);
10039         pw.println(" uptime):");
10040         if (!mCurBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
10041             pw.println("    (nothing)");
10042         }
10043     }
10044 
dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)10045     void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10046             int opti, boolean fullCheckin, String dumpPackage) {
10047         if (mCurBroadcastStats == null) {
10048             return;
10049         }
10050 
10051         if (mLastBroadcastStats != null) {
10052             mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage);
10053             if (fullCheckin) {
10054                 mLastBroadcastStats = null;
10055                 return;
10056             }
10057         }
10058         mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage);
10059         if (fullCheckin) {
10060             mCurBroadcastStats = null;
10061         }
10062     }
10063 
dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)10064     void dumpPermissions(FileDescriptor fd, PrintWriter pw, String[] args,
10065             int opti, boolean dumpAll, String dumpPackage) {
10066 
10067         pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)");
10068 
10069         mUgmInternal.dump(pw, dumpAll, dumpPackage);
10070     }
10071 
dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)10072     private static int dumpProcessList(PrintWriter pw,
10073             ActivityManagerService service, List list,
10074             String prefix, String normalLabel, String persistentLabel,
10075             String dumpPackage) {
10076         int numPers = 0;
10077         for (int i = list.size() - 1; i >= 0; i--) {
10078             ProcessRecord r = (ProcessRecord) list.get(i);
10079             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10080                 continue;
10081             }
10082             pw.println(String.format("%s%s #%2d: %s",
10083                     prefix, (r.isPersistent() ? persistentLabel : normalLabel),
10084                     i, r.toString()));
10085             if (r.isPersistent()) {
10086                 numPers++;
10087             }
10088         }
10089         return numPers;
10090     }
10091 
collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)10092     ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs,
10093             String[] args) {
10094         synchronized (mProcLock) {
10095             return mProcessList.collectProcessesLOSP(start, allPkgs, args);
10096         }
10097     }
10098 
dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)10099     final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10100             PrintWriter pw, String[] args) {
10101         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
10102         if (procs == null) {
10103             pw.println("No process found for: " + args[0]);
10104             return;
10105         }
10106 
10107         long uptime = SystemClock.uptimeMillis();
10108         long realtime = SystemClock.elapsedRealtime();
10109         pw.println("Applications Graphics Acceleration Info:");
10110         pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10111 
10112         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10113             ProcessRecord r = procs.get(i);
10114             final int pid = r.getPid();
10115             final IApplicationThread thread = r.getThread();
10116             if (thread != null) {
10117                 pw.println("\n** Graphics info for pid " + pid + " [" + r.processName + "] **");
10118                 pw.flush();
10119                 try {
10120                     TransferPipe tp = new TransferPipe();
10121                     try {
10122                         thread.dumpGfxInfo(tp.getWriteFd(), args);
10123                         tp.go(fd);
10124                     } finally {
10125                         tp.kill();
10126                     }
10127                 } catch (IOException e) {
10128                     pw.println("Failure while dumping the app: " + r);
10129                     pw.flush();
10130                 } catch (RemoteException e) {
10131                     pw.println("Got a RemoteException while dumping the app " + r);
10132                     pw.flush();
10133                 }
10134             }
10135         }
10136     }
10137 
dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)10138     final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) {
10139         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
10140         if (procs == null) {
10141             pw.println("No process found for: " + args[0]);
10142             return;
10143         }
10144 
10145         pw.println("Per-process Binder Cache Contents");
10146 
10147         for (int i = procs.size() - 1; i >= 0; i--) {
10148             ProcessRecord r = procs.get(i);
10149             final int pid = r.getPid();
10150             final IApplicationThread thread = r.getThread();
10151             if (thread != null) {
10152                 pw.println("\n\n** Cache info for pid " + pid + " [" + r.processName + "] **");
10153                 pw.flush();
10154                 if (pid == MY_PID) {
10155                     PropertyInvalidatedCache.dumpCacheInfo(fd, args);
10156                     continue;
10157                 }
10158                 try {
10159                     TransferPipe tp = new TransferPipe();
10160                     try {
10161                         thread.dumpCacheInfo(tp.getWriteFd(), args);
10162                         tp.go(fd);
10163                     } finally {
10164                         tp.kill();
10165                     }
10166                 } catch (IOException e) {
10167                     pw.println("Failure while dumping the app " + r);
10168                     pw.flush();
10169                 } catch (RemoteException e) {
10170                     pw.println("Got a RemoteException while dumping the app " + r);
10171                     pw.flush();
10172                 }
10173             }
10174         }
10175     }
10176 
dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)10177     final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10178         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
10179         if (procs == null) {
10180             pw.println("No process found for: " + args[0]);
10181             return;
10182         }
10183 
10184         pw.println("Applications Database Info:");
10185 
10186         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10187             ProcessRecord r = procs.get(i);
10188             final int pid = r.getPid();
10189             final IApplicationThread thread = r.getThread();
10190             if (thread != null) {
10191                 pw.println("\n** Database info for pid " + pid + " [" + r.processName + "] **");
10192                 pw.flush();
10193                 try {
10194                     TransferPipe tp = new TransferPipe();
10195                     try {
10196                         thread.dumpDbInfo(tp.getWriteFd(), args);
10197                         tp.go(fd);
10198                     } finally {
10199                         tp.kill();
10200                     }
10201                 } catch (IOException e) {
10202                     pw.println("Failure while dumping the app: " + r);
10203                     pw.flush();
10204                 } catch (RemoteException e) {
10205                     pw.println("Got a RemoteException while dumping the app " + r);
10206                     pw.flush();
10207                 }
10208             }
10209         }
10210     }
10211 
10212     final static class MemItem {
10213         final boolean isProc;
10214         final String label;
10215         final String shortLabel;
10216         final long pss;
10217         final long swapPss;
10218         final long mRss;
10219         final int id;
10220         final boolean hasActivities;
10221         ArrayList<MemItem> subitems;
10222 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, boolean hasActivities)10223         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id,
10224                 boolean hasActivities) {
10225             this.isProc = true;
10226             this.label = label;
10227             this.shortLabel = shortLabel;
10228             this.pss = pss;
10229             this.swapPss = swapPss;
10230             this.mRss = rss;
10231             this.id = id;
10232             this.hasActivities = hasActivities;
10233         }
10234 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id)10235         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id) {
10236             this.isProc = false;
10237             this.label = label;
10238             this.shortLabel = shortLabel;
10239             this.pss = pss;
10240             this.swapPss = swapPss;
10241             this.mRss = rss;
10242             this.id = id;
10243             this.hasActivities = false;
10244         }
10245     }
10246 
sortMemItems(List<MemItem> items, final boolean pss)10247     private static void sortMemItems(List<MemItem> items, final boolean pss) {
10248         Collections.sort(items, new Comparator<MemItem>() {
10249             @Override
10250             public int compare(MemItem lhs, MemItem rhs) {
10251                 long lss = pss ? lhs.pss : lhs.mRss;
10252                 long rss = pss ? rhs.pss : rhs.mRss;
10253                 if (lss < rss) {
10254                     return 1;
10255                 } else if (lss > rss) {
10256                     return -1;
10257                 }
10258                 return 0;
10259             }
10260         });
10261     }
10262 
dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss)10263     static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
10264             ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss,
10265             boolean dumpSwapPss) {
10266         if (sort && !isCompact) {
10267             sortMemItems(items, dumpPss);
10268         }
10269 
10270         for (int i=0; i<items.size(); i++) {
10271             MemItem mi = items.get(i);
10272             if (!isCompact) {
10273                 if (dumpPss && dumpSwapPss) {
10274                     pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss),
10275                             mi.label, stringifyKBSize(mi.swapPss));
10276                 } else {
10277                     pw.printf("%s%s: %s\n", prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss),
10278                             mi.label);
10279                 }
10280             } else if (mi.isProc) {
10281                 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
10282                 pw.print(","); pw.print(mi.id); pw.print(",");
10283                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
10284                 pw.print(dumpSwapPss ? mi.swapPss : "N/A");
10285                 pw.println(mi.hasActivities ? ",a" : ",e");
10286             } else {
10287                 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
10288                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
10289                 pw.println(dumpSwapPss ? mi.swapPss : "N/A");
10290             }
10291             if (mi.subitems != null) {
10292                 dumpMemItems(pw, prefix + "    ", mi.shortLabel, mi.subitems,
10293                         true, isCompact, dumpPss, dumpSwapPss);
10294             }
10295         }
10296     }
10297 
dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)10298     static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag,
10299             ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) {
10300         if (sort) {
10301             sortMemItems(items, dumpPss);
10302         }
10303 
10304         for (int i=0; i<items.size(); i++) {
10305             MemItem mi = items.get(i);
10306             final long token = proto.start(fieldId);
10307 
10308             proto.write(MemInfoDumpProto.MemItem.TAG, tag);
10309             proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel);
10310             proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc);
10311             proto.write(MemInfoDumpProto.MemItem.ID, mi.id);
10312             proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities);
10313             proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss);
10314             proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss);
10315             if (dumpSwapPss) {
10316                 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss);
10317             }
10318             if (mi.subitems != null) {
10319                 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems,
10320                         true, dumpPss, dumpSwapPss);
10321             }
10322             proto.end(token);
10323         }
10324     }
10325 
10326     // These are in KB.
10327     static final long[] DUMP_MEM_BUCKETS = new long[] {
10328         5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10329         120*1024, 160*1024, 200*1024,
10330         250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10331         1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10332     };
10333 
appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)10334     static final void appendMemBucket(StringBuilder out, long memKB, String label,
10335             boolean stackLike) {
10336         int start = label.lastIndexOf('.');
10337         if (start >= 0) start++;
10338         else start = 0;
10339         int end = label.length();
10340         for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10341             if (DUMP_MEM_BUCKETS[i] >= memKB) {
10342                 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10343                 out.append(bucket);
10344                 out.append(stackLike ? "MB." : "MB ");
10345                 out.append(label, start, end);
10346                 return;
10347             }
10348         }
10349         out.append(memKB/1024);
10350         out.append(stackLike ? "MB." : "MB ");
10351         out.append(label, start, end);
10352     }
10353 
10354     static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10355             ProcessList.NATIVE_ADJ,
10356             ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ,
10357             ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10358             ProcessList.VISIBLE_APP_ADJ,
10359             ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ,
10360             ProcessList.PERCEPTIBLE_MEDIUM_APP_ADJ,
10361             ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10362             ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10363             ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ
10364     };
10365     static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10366             "Native",
10367             "System", "Persistent", "Persistent Service", "Foreground",
10368             "Visible", "Perceptible", "Perceptible Low", "Perceptible Medium",
10369             "Heavy Weight", "Backup",
10370             "A Services", "Home",
10371             "Previous", "B Services", "Cached"
10372     };
10373     static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
10374             "native",
10375             "sys", "pers", "persvc", "fore",
10376             "vis", "percept", "perceptl", "perceptm",
10377             "heavy", "backup",
10378             "servicea", "home",
10379             "prev", "serviceb", "cached"
10380     };
10381 
dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)10382     private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
10383             long realtime, boolean isCheckinRequest, boolean isCompact) {
10384         if (isCompact) {
10385             pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION);
10386         }
10387         if (isCheckinRequest || isCompact) {
10388             // short checkin version
10389             pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
10390         } else {
10391             pw.println("Applications Memory Usage (in Kilobytes):");
10392             pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10393         }
10394     }
10395 
10396     static final int KSM_SHARED = 0;
10397     static final int KSM_SHARING = 1;
10398     static final int KSM_UNSHARED = 2;
10399     static final int KSM_VOLATILE = 3;
10400 
getKsmInfo()10401     static final long[] getKsmInfo() {
10402         long[] longOut = new long[4];
10403         final int[] SINGLE_LONG_FORMAT = new int[] {
10404             PROC_SPACE_TERM| PROC_OUT_LONG
10405         };
10406         long[] longTmp = new long[1];
10407         readProcFile("/sys/kernel/mm/ksm/pages_shared",
10408                 SINGLE_LONG_FORMAT, null, longTmp, null);
10409         longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
10410         longTmp[0] = 0;
10411         readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10412                 SINGLE_LONG_FORMAT, null, longTmp, null);
10413         longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
10414         longTmp[0] = 0;
10415         readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10416                 SINGLE_LONG_FORMAT, null, longTmp, null);
10417         longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
10418         longTmp[0] = 0;
10419         readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10420                 SINGLE_LONG_FORMAT, null, longTmp, null);
10421         longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
10422         return longOut;
10423     }
10424 
stringifySize(long size, int order)10425     static String stringifySize(long size, int order) {
10426         Locale locale = Locale.US;
10427         switch (order) {
10428             case 1:
10429                 return String.format(locale, "%,13d", size);
10430             case 1024:
10431                 return String.format(locale, "%,9dK", size / 1024);
10432             case 1024 * 1024:
10433                 return String.format(locale, "%,5dM", size / 1024 / 1024);
10434             case 1024 * 1024 * 1024:
10435                 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024);
10436             default:
10437                 throw new IllegalArgumentException("Invalid size order");
10438         }
10439     }
10440 
stringifyKBSize(long size)10441     static String stringifyKBSize(long size) {
10442         return stringifySize(size * 1024, 1024);
10443     }
10444 
10445     // Update this version number if you change the 'compact' format.
10446     private static final int MEMINFO_COMPACT_VERSION = 1;
10447 
10448     private static class MemoryUsageDumpOptions {
10449         boolean dumpDetails;
10450         boolean dumpFullDetails;
10451         boolean dumpDalvik;
10452         boolean dumpSummaryOnly;
10453         boolean dumpUnreachable;
10454         boolean oomOnly;
10455         boolean isCompact;
10456         boolean localOnly;
10457         boolean packages;
10458         boolean isCheckinRequest;
10459         boolean dumpSwapPss;
10460         boolean dumpProto;
10461     }
10462 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)10463     final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
10464             String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) {
10465         MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions();
10466         opts.dumpDetails = false;
10467         opts.dumpFullDetails = false;
10468         opts.dumpDalvik = false;
10469         opts.dumpSummaryOnly = false;
10470         opts.dumpUnreachable = false;
10471         opts.oomOnly = false;
10472         opts.isCompact = false;
10473         opts.localOnly = false;
10474         opts.packages = false;
10475         opts.isCheckinRequest = false;
10476         opts.dumpSwapPss = false;
10477         opts.dumpProto = asProto;
10478 
10479         int opti = 0;
10480         while (opti < args.length) {
10481             String opt = args[opti];
10482             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10483                 break;
10484             }
10485             opti++;
10486             if ("-a".equals(opt)) {
10487                 opts.dumpDetails = true;
10488                 opts.dumpFullDetails = true;
10489                 opts.dumpDalvik = true;
10490                 opts.dumpSwapPss = true;
10491             } else if ("-d".equals(opt)) {
10492                 opts.dumpDalvik = true;
10493             } else if ("-c".equals(opt)) {
10494                 opts.isCompact = true;
10495             } else if ("-s".equals(opt)) {
10496                 opts.dumpDetails = true;
10497                 opts.dumpSummaryOnly = true;
10498             } else if ("-S".equals(opt)) {
10499                 opts.dumpSwapPss = true;
10500             } else if ("--unreachable".equals(opt)) {
10501                 opts.dumpUnreachable = true;
10502             } else if ("--oom".equals(opt)) {
10503                 opts.oomOnly = true;
10504             } else if ("--local".equals(opt)) {
10505                 opts.localOnly = true;
10506             } else if ("--package".equals(opt)) {
10507                 opts.packages = true;
10508             } else if ("--checkin".equals(opt)) {
10509                 opts.isCheckinRequest = true;
10510             } else if ("--proto".equals(opt)) {
10511                 opts.dumpProto = true;
10512 
10513             } else if ("-h".equals(opt)) {
10514                 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
10515                 pw.println("  -a: include all available information for each process.");
10516                 pw.println("  -d: include dalvik details.");
10517                 pw.println("  -c: dump in a compact machine-parseable representation.");
10518                 pw.println("  -s: dump only summary of application memory usage.");
10519                 pw.println("  -S: dump also SwapPss.");
10520                 pw.println("  --oom: only show processes organized by oom adj.");
10521                 pw.println("  --local: only collect details locally, don't call process.");
10522                 pw.println("  --package: interpret process arg as package, dumping all");
10523                 pw.println("             processes that have loaded that package.");
10524                 pw.println("  --checkin: dump data for a checkin");
10525                 pw.println("  --proto: dump data to proto");
10526                 pw.println("If [process] is specified it can be the name or ");
10527                 pw.println("pid of a specific process to dump.");
10528                 return;
10529             } else {
10530                 pw.println("Unknown argument: " + opt + "; use -h for help");
10531             }
10532         }
10533 
10534         String[] innerArgs = new String[args.length-opti];
10535         System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10536 
10537         ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args);
10538         if (opts.dumpProto) {
10539             dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs);
10540         } else {
10541             dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw);
10542         }
10543     }
10544 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)10545     private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
10546             MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief,
10547             ArrayList<ProcessRecord> procs, PrintWriter categoryPw) {
10548         long uptime = SystemClock.uptimeMillis();
10549         long realtime = SystemClock.elapsedRealtime();
10550         final long[] tmpLong = new long[3];
10551 
10552         if (procs == null) {
10553             // No Java processes.  Maybe they want to print a native process.
10554             String proc = "N/A";
10555             if (innerArgs.length > 0) {
10556                 proc = innerArgs[0];
10557                 if (proc.charAt(0) != '-') {
10558                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
10559                             = new ArrayList<ProcessCpuTracker.Stats>();
10560                     updateCpuStatsNow();
10561                     int findPid = -1;
10562                     try {
10563                         findPid = Integer.parseInt(innerArgs[0]);
10564                     } catch (NumberFormatException e) {
10565                     }
10566                     final int fFindPid = findPid;
10567                     mAppProfiler.forAllCpuStats((st) -> {
10568                         if (st.pid == fFindPid || (st.baseName != null
10569                                 && st.baseName.equals(innerArgs[0]))) {
10570                             nativeProcs.add(st);
10571                         }
10572                     });
10573                     if (nativeProcs.size() > 0) {
10574                         dumpApplicationMemoryUsageHeader(pw, uptime, realtime,
10575                                 opts.isCheckinRequest, opts.isCompact);
10576                         Debug.MemoryInfo mi = null;
10577                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
10578                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
10579                             final int pid = r.pid;
10580                             if (mi == null) {
10581                                 mi = new Debug.MemoryInfo();
10582                             }
10583                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
10584                                 if (!Debug.getMemoryInfo(pid, mi)) {
10585                                     continue;
10586                                 }
10587                             } else {
10588                                 long pss = Debug.getPss(pid, tmpLong, null);
10589                                 if (pss == 0) {
10590                                     continue;
10591                                 }
10592                                 mi.nativePss = (int) pss;
10593                                 mi.nativePrivateDirty = (int) tmpLong[0];
10594                                 mi.nativeRss = (int) tmpLong[2];
10595                             }
10596                             if (!opts.isCheckinRequest && opts.dumpDetails) {
10597                                 pw.println("\n** MEMINFO in pid " + pid + " ["
10598                                         + r.baseName + "] **");
10599                             }
10600                             ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest,
10601                                     opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
10602                                     pid, r.baseName, 0, 0, 0, 0, 0, 0);
10603                             if (opts.isCheckinRequest) {
10604                                 pw.println();
10605                             }
10606                         }
10607                         return;
10608                     }
10609                 }
10610             }
10611             pw.println("No process found for: " + proc);
10612             return;
10613         }
10614 
10615         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
10616             opts.dumpDetails = true;
10617         }
10618         final int numProcs = procs.size();
10619         final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages;
10620         if (collectNative) {
10621             // If we are showing aggregations, also look for native processes to
10622             // include so that our aggregations are more accurate.
10623             updateCpuStatsNow();
10624         }
10625 
10626         dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact);
10627 
10628         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10629         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
10630         final long[] ss = new long[INDEX_LAST];
10631         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
10632                 EmptyArray.LONG;
10633         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
10634                 EmptyArray.LONG;
10635         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
10636                 EmptyArray.LONG;
10637         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10638         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10639         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10640         long[] memtrackTmp = new long[4];
10641 
10642         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10643         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10644         long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
10645         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10646                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
10647 
10648         long totalSwapPss = 0;
10649         long totalRss = 0;
10650         long cachedPss = 0;
10651         long cachedSwapPss = 0;
10652         boolean hasSwapPss = false;
10653 
10654         Debug.MemoryInfo mi = null;
10655         for (int i = numProcs - 1; i >= 0; i--) {
10656             final ProcessRecord r = procs.get(i);
10657             final IApplicationThread thread;
10658             final int pid;
10659             final int oomAdj;
10660             final boolean hasActivities;
10661             synchronized (mProcLock) {
10662                 thread = r.getThread();
10663                 pid = r.getPid();
10664                 oomAdj = r.mState.getSetAdjWithServices();
10665                 hasActivities = r.hasActivities();
10666             }
10667             if (thread != null) {
10668                 if (mi == null) {
10669                     mi = new Debug.MemoryInfo();
10670                 }
10671                 final int reportType;
10672                 final long startTime;
10673                 final long endTime;
10674                 long memtrackGraphics = 0;
10675                 long memtrackGl = 0;
10676                 if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
10677                     reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
10678                     startTime = SystemClock.currentThreadTimeMillis();
10679                     if (!Debug.getMemoryInfo(pid, mi)) {
10680                         continue;
10681                     }
10682                     endTime = SystemClock.currentThreadTimeMillis();
10683                     hasSwapPss = mi.hasSwappedOutPss;
10684                     memtrackGraphics = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS);
10685                     memtrackGl = mi.getOtherPrivate(Debug.MemoryInfo.OTHER_GL);
10686                 } else {
10687                     reportType = ProcessStats.ADD_PSS_EXTERNAL;
10688                     startTime = SystemClock.currentThreadTimeMillis();
10689                     long pss = Debug.getPss(pid, tmpLong, memtrackTmp);
10690                     if (pss == 0) {
10691                         continue;
10692                     }
10693                     mi.dalvikPss = (int) pss;
10694                     endTime = SystemClock.currentThreadTimeMillis();
10695                     mi.dalvikPrivateDirty = (int) tmpLong[0];
10696                     mi.dalvikRss = (int) tmpLong[2];
10697                     memtrackGraphics = memtrackTmp[1];
10698                     memtrackGl = memtrackTmp[2];
10699                 }
10700                 if (!opts.isCheckinRequest && opts.dumpDetails) {
10701                     pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
10702                 }
10703                 if (opts.dumpDetails) {
10704                     if (opts.localOnly) {
10705                         ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails,
10706                                 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
10707                         if (opts.isCheckinRequest) {
10708                             pw.println();
10709                         }
10710                     } else {
10711                         pw.flush();
10712                         try {
10713                             TransferPipe tp = new TransferPipe();
10714                             try {
10715                                 thread.dumpMemInfo(tp.getWriteFd(),
10716                                         mi, opts.isCheckinRequest, opts.dumpFullDetails,
10717                                         opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs);
10718                                 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000);
10719                             } finally {
10720                                 tp.kill();
10721                             }
10722                         } catch (IOException e) {
10723                             if (!opts.isCheckinRequest) {
10724                                 pw.println("Got IoException! " + e);
10725                                 pw.flush();
10726                             }
10727                         } catch (RemoteException e) {
10728                             if (!opts.isCheckinRequest) {
10729                                 pw.println("Got RemoteException! " + e);
10730                                 pw.flush();
10731                             }
10732                         }
10733                     }
10734                 }
10735 
10736                 final long myTotalPss = mi.getTotalPss();
10737                 final long myTotalUss = mi.getTotalUss();
10738                 final long myTotalRss = mi.getTotalRss();
10739                 final long myTotalSwapPss = mi.getTotalSwappedOutPss();
10740 
10741                 synchronized (mProcLock) {
10742                     if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) {
10743                         // Record this for posterity if the process has been stable.
10744                         r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
10745                                 reportType, endTime - startTime);
10746                         r.getPkgList().forEachPackageProcessStats(holder -> {
10747                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
10748                                     r.info.uid,
10749                                     holder.state.getName(),
10750                                     holder.state.getPackage(),
10751                                     myTotalPss, myTotalUss, myTotalRss, reportType,
10752                                     endTime-startTime,
10753                                     holder.appVersion);
10754                         });
10755                     }
10756                 }
10757 
10758                 if (!opts.isCheckinRequest && mi != null) {
10759                     ss[INDEX_TOTAL_PSS] += myTotalPss;
10760                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
10761                     ss[INDEX_TOTAL_RSS] += myTotalRss;
10762                     ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics;
10763                     ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl;
10764                     MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
10765                             (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
10766                             myTotalSwapPss, myTotalRss, pid, hasActivities);
10767                     procMems.add(pssItem);
10768                     procMemsMap.put(pid, pssItem);
10769 
10770                     ss[INDEX_NATIVE_PSS] += mi.nativePss;
10771                     ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss;
10772                     ss[INDEX_NATIVE_RSS] += mi.nativeRss;
10773                     ss[INDEX_DALVIK_PSS] += mi.dalvikPss;
10774                     ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss;
10775                     ss[INDEX_DALVIK_RSS] += mi.dalvikRss;
10776                     for (int j=0; j<dalvikSubitemPss.length; j++) {
10777                         dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
10778                         dalvikSubitemSwapPss[j] +=
10779                                 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
10780                         dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
10781                     }
10782                     ss[INDEX_OTHER_PSS] += mi.otherPss;
10783                     ss[INDEX_OTHER_RSS] += mi.otherRss;
10784                     ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss;
10785                     for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10786                         long mem = mi.getOtherPss(j);
10787                         miscPss[j] += mem;
10788                         ss[INDEX_OTHER_PSS] -= mem;
10789                         mem = mi.getOtherSwappedOutPss(j);
10790                         miscSwapPss[j] += mem;
10791                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
10792                         mem = mi.getOtherRss(j);
10793                         miscRss[j] += mem;
10794                         ss[INDEX_OTHER_RSS] -= mem;
10795                     }
10796 
10797                     if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
10798                         cachedPss += myTotalPss;
10799                         cachedSwapPss += myTotalSwapPss;
10800                     }
10801 
10802                     for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
10803                         if (oomIndex == (oomPss.length - 1)
10804                                 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
10805                                         && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
10806                             oomPss[oomIndex] += myTotalPss;
10807                             oomSwapPss[oomIndex] += myTotalSwapPss;
10808                             if (oomProcs[oomIndex] == null) {
10809                                 oomProcs[oomIndex] = new ArrayList<MemItem>();
10810                             }
10811                             oomProcs[oomIndex].add(pssItem);
10812                             oomRss[oomIndex] += myTotalRss;
10813                             break;
10814                         }
10815                     }
10816                 }
10817             }
10818         }
10819 
10820         long nativeProcTotalPss = 0;
10821 
10822         if (collectNative) {
10823             mi = null;
10824             final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1];
10825             mAppProfiler.forAllCpuStats((st) -> {
10826                 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
10827                     long memtrackGraphics = 0;
10828                     long memtrackGl = 0;
10829                     if (memInfos[0] == null) {
10830                         memInfos[0] = new Debug.MemoryInfo();
10831                     }
10832                     final Debug.MemoryInfo info = memInfos[0];
10833                     if (!brief && !opts.oomOnly) {
10834                         if (!Debug.getMemoryInfo(st.pid, info)) {
10835                             return;
10836                         }
10837                         memtrackGraphics = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GRAPHICS);
10838                         memtrackGl = info.getOtherPrivate(Debug.MemoryInfo.OTHER_GL);
10839                     } else {
10840                         long pss = Debug.getPss(st.pid, tmpLong, memtrackTmp);
10841                         if (pss == 0) {
10842                             return;
10843                         }
10844                         info.nativePss = (int) pss;
10845                         info.nativePrivateDirty = (int) tmpLong[0];
10846                         info.nativeRss = (int) tmpLong[2];
10847                         memtrackGraphics = memtrackTmp[1];
10848                         memtrackGl = memtrackTmp[2];
10849                     }
10850 
10851                     final long myTotalPss = info.getTotalPss();
10852                     final long myTotalSwapPss = info.getTotalSwappedOutPss();
10853                     final long myTotalRss = info.getTotalRss();
10854                     ss[INDEX_TOTAL_PSS] += myTotalPss;
10855                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
10856                     ss[INDEX_TOTAL_RSS] += myTotalRss;
10857                     ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss;
10858                     ss[INDEX_TOTAL_MEMTRACK_GRAPHICS] += memtrackGraphics;
10859                     ss[INDEX_TOTAL_MEMTRACK_GL] += memtrackGl;
10860 
10861                     MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
10862                             st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss,
10863                             st.pid, false);
10864                     procMems.add(pssItem);
10865 
10866                     ss[INDEX_NATIVE_PSS] += info.nativePss;
10867                     ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss;
10868                     ss[INDEX_NATIVE_RSS] += info.nativeRss;
10869                     ss[INDEX_DALVIK_PSS] += info.dalvikPss;
10870                     ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss;
10871                     ss[INDEX_DALVIK_RSS] += info.dalvikRss;
10872                     for (int j = 0; j < dalvikSubitemPss.length; j++) {
10873                         dalvikSubitemPss[j] += info.getOtherPss(
10874                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
10875                         dalvikSubitemSwapPss[j] +=
10876                                 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
10877                         dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
10878                                 + j);
10879                     }
10880                     ss[INDEX_OTHER_PSS] += info.otherPss;
10881                     ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss;
10882                     ss[INDEX_OTHER_RSS] += info.otherRss;
10883                     for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10884                         long mem = info.getOtherPss(j);
10885                         miscPss[j] += mem;
10886                         ss[INDEX_OTHER_PSS] -= mem;
10887                         mem = info.getOtherSwappedOutPss(j);
10888                         miscSwapPss[j] += mem;
10889                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
10890                         mem = info.getOtherRss(j);
10891                         miscRss[j] += mem;
10892                         ss[INDEX_OTHER_RSS] -= mem;
10893                     }
10894                     oomPss[0] += myTotalPss;
10895                     oomSwapPss[0] += myTotalSwapPss;
10896                     if (oomProcs[0] == null) {
10897                         oomProcs[0] = new ArrayList<MemItem>();
10898                     }
10899                     oomProcs[0].add(pssItem);
10900                     oomRss[0] += myTotalRss;
10901                 }
10902             });
10903 
10904             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10905 
10906             catMems.add(new MemItem("Native", "Native",
10907                     ss[INDEX_NATIVE_PSS], ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1));
10908             final int dalvikId = -2;
10909             catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS],
10910                     ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId));
10911             catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS],
10912                     ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3));
10913             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10914                 String label = Debug.MemoryInfo.getOtherLabel(j);
10915                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j],  j));
10916             }
10917             if (dalvikSubitemPss.length > 0) {
10918                 // Add dalvik subitems.
10919                 for (MemItem memItem : catMems) {
10920                     int memItemStart = 0, memItemEnd = 0;
10921                     if (memItem.id == dalvikId) {
10922                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
10923                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
10924                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
10925                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
10926                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
10927                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
10928                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
10929                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
10930                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
10931                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
10932                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
10933                     } else {
10934                         continue;  // No subitems, continue.
10935                     }
10936                     memItem.subitems = new ArrayList<MemItem>();
10937                     for (int j=memItemStart; j<=memItemEnd; j++) {
10938                         final String name = Debug.MemoryInfo.getOtherLabel(
10939                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
10940                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
10941                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
10942                     }
10943                 }
10944             }
10945 
10946             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10947             for (int j=0; j<oomPss.length; j++) {
10948                 if (oomPss[j] != 0) {
10949                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
10950                             : DUMP_MEM_OOM_LABEL[j];
10951                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
10952                             DUMP_MEM_OOM_ADJ[j]);
10953                     item.subitems = oomProcs[j];
10954                     oomMems.add(item);
10955                 }
10956             }
10957             if (!opts.isCompact) {
10958                 pw.println();
10959             }
10960             if (!brief && !opts.oomOnly && !opts.isCompact) {
10961                 pw.println();
10962                 pw.println("Total RSS by process:");
10963                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, false, false);
10964                 pw.println();
10965             }
10966             if (!opts.isCompact) {
10967                 pw.println("Total RSS by OOM adjustment:");
10968             }
10969             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, false, false);
10970             if (!brief && !opts.oomOnly) {
10971                 PrintWriter out = categoryPw != null ? categoryPw : pw;
10972                 if (!opts.isCompact) {
10973                     out.println();
10974                     out.println("Total RSS by category:");
10975                 }
10976                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, false, false);
10977             }
10978             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0;
10979             if (!brief && !opts.oomOnly && !opts.isCompact) {
10980                 pw.println();
10981                 pw.println("Total PSS by process:");
10982                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, true,
10983                         opts.dumpSwapPss);
10984                 pw.println();
10985             }
10986             if (!opts.isCompact) {
10987                 pw.println("Total PSS by OOM adjustment:");
10988             }
10989             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss);
10990             if (!brief && !opts.oomOnly) {
10991                 PrintWriter out = categoryPw != null ? categoryPw : pw;
10992                 if (!opts.isCompact) {
10993                     out.println();
10994                     out.println("Total PSS by category:");
10995                 }
10996                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, true,
10997                         opts.dumpSwapPss);
10998             }
10999             if (!opts.isCompact) {
11000                 pw.println();
11001             }
11002             MemInfoReader memInfo = new MemInfoReader();
11003             memInfo.readMemInfo();
11004             if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) {
11005                 synchronized (mProcessStats.mLock) {
11006                     final long cachedKb = memInfo.getCachedSizeKb();
11007                     final long freeKb = memInfo.getFreeSizeKb();
11008                     final long zramKb = memInfo.getZramTotalSizeKb();
11009                     final long kernelKb = memInfo.getKernelUsedSizeKb();
11010                     EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
11011                             kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024);
11012                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
11013                             ss[INDEX_TOTAL_NATIVE_PSS]);
11014                 }
11015             }
11016             if (!brief) {
11017                 if (!opts.isCompact) {
11018                     pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
11019                     pw.print(" (status ");
11020                     mAppProfiler.dumpLastMemoryLevelLocked(pw);
11021                     pw.print(" Free RAM: ");
11022                     pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
11023                             + memInfo.getFreeSizeKb()));
11024                     pw.print(" (");
11025                     pw.print(stringifyKBSize(cachedPss));
11026                     pw.print(" cached pss + ");
11027                     pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
11028                     pw.print(" cached kernel + ");
11029                     pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
11030                     pw.println(" free)");
11031                 } else {
11032                     pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
11033                     pw.print(cachedPss + memInfo.getCachedSizeKb()
11034                             + memInfo.getFreeSizeKb()); pw.print(",");
11035                     pw.println(ss[INDEX_TOTAL_PSS] - cachedPss);
11036                 }
11037             }
11038             long kernelUsed = memInfo.getKernelUsedSizeKb();
11039             final long ionHeap = Debug.getIonHeapsSizeKb();
11040             final long ionPool = Debug.getIonPoolsSizeKb();
11041             final long dmabufMapped = Debug.getDmabufMappedSizeKb();
11042             if (ionHeap >= 0 && ionPool >= 0) {
11043                 final long ionUnmapped = ionHeap - dmabufMapped;
11044                 pw.print("      ION: ");
11045                         pw.print(stringifyKBSize(ionHeap + ionPool));
11046                         pw.print(" (");
11047                         pw.print(stringifyKBSize(dmabufMapped));
11048                         pw.print(" mapped + ");
11049                         pw.print(stringifyKBSize(ionUnmapped));
11050                         pw.print(" unmapped + ");
11051                         pw.print(stringifyKBSize(ionPool));
11052                         pw.println(" pools)");
11053                 kernelUsed += ionUnmapped;
11054                 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
11055                 // set on ION VMAs, however it might be included by the memtrack HAL.
11056                 // Replace memtrack HAL reported Graphics category with mapped dmabufs
11057                 ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS];
11058                 ss[INDEX_TOTAL_PSS] += dmabufMapped;
11059             } else {
11060                 final long totalExportedDmabuf = Debug.getDmabufTotalExportedKb();
11061                 if (totalExportedDmabuf >= 0) {
11062                     final long dmabufUnmapped = totalExportedDmabuf - dmabufMapped;
11063                     pw.print("DMA-BUF: ");
11064                     pw.print(stringifyKBSize(totalExportedDmabuf));
11065                     pw.print(" (");
11066                     pw.print(stringifyKBSize(dmabufMapped));
11067                     pw.print(" mapped + ");
11068                     pw.print(stringifyKBSize(dmabufUnmapped));
11069                     pw.println(" unmapped)");
11070                     // Account unmapped dmabufs as part of kernel memory allocations
11071                     kernelUsed += dmabufUnmapped;
11072                     // Replace memtrack HAL reported Graphics category with mapped dmabufs
11073                     ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GRAPHICS];
11074                     ss[INDEX_TOTAL_PSS] += dmabufMapped;
11075                 }
11076 
11077                 // totalDmabufHeapExported is included in totalExportedDmabuf above and hence do not
11078                 // need to be added to kernelUsed.
11079                 final long totalDmabufHeapExported = Debug.getDmabufHeapTotalExportedKb();
11080                 if (totalDmabufHeapExported >= 0) {
11081                     pw.print("DMA-BUF Heaps: ");
11082                     pw.println(stringifyKBSize(totalDmabufHeapExported));
11083                 }
11084 
11085                 final long totalDmabufHeapPool = Debug.getDmabufHeapPoolsSizeKb();
11086                 if (totalDmabufHeapPool >= 0) {
11087                     pw.print("DMA-BUF Heaps pool: ");
11088                     pw.println(stringifyKBSize(totalDmabufHeapPool));
11089                 }
11090             }
11091             final long gpuUsage = Debug.getGpuTotalUsageKb();
11092             if (gpuUsage >= 0) {
11093                 final long gpuPrivateUsage = Debug.getGpuPrivateMemoryKb();
11094                 if (gpuPrivateUsage >= 0) {
11095                     final long gpuDmaBufUsage = gpuUsage - gpuPrivateUsage;
11096                     pw.print("      GPU: ");
11097                     pw.print(stringifyKBSize(gpuUsage));
11098                     pw.print(" (");
11099                     pw.print(stringifyKBSize(gpuDmaBufUsage));
11100                     pw.print(" dmabuf + ");
11101                     pw.print(stringifyKBSize(gpuPrivateUsage));
11102                     pw.println(" private)");
11103                     // Replace memtrack HAL reported GL category with private GPU allocations and
11104                     // account it as part of kernel memory allocations
11105                     ss[INDEX_TOTAL_PSS] -= ss[INDEX_TOTAL_MEMTRACK_GL];
11106                     kernelUsed += gpuPrivateUsage;
11107                 } else {
11108                     pw.print("      GPU: "); pw.println(stringifyKBSize(gpuUsage));
11109                 }
11110             }
11111 
11112              // Note: ION/DMA-BUF heap pools are reclaimable and hence, they are included as part of
11113              // memInfo.getCachedSizeKb().
11114             final long lostRAM = memInfo.getTotalSizeKb()
11115                     - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS])
11116                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
11117                     - kernelUsed - memInfo.getZramTotalSizeKb();
11118             if (!opts.isCompact) {
11119                 pw.print(" Used RAM: "); pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss
11120                         + kernelUsed)); pw.print(" (");
11121                 pw.print(stringifyKBSize(ss[INDEX_TOTAL_PSS] - cachedPss)); pw.print(" used pss + ");
11122                 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n");
11123                 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM));
11124             } else {
11125                 pw.print("lostram,"); pw.println(lostRAM);
11126             }
11127             if (!brief) {
11128                 if (memInfo.getZramTotalSizeKb() != 0) {
11129                     if (!opts.isCompact) {
11130                         pw.print("     ZRAM: ");
11131                         pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
11132                                 pw.print(" physical used for ");
11133                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()
11134                                         - memInfo.getSwapFreeSizeKb()));
11135                                 pw.print(" in swap (");
11136                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
11137                                 pw.println(" total swap)");
11138                     } else {
11139                         pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
11140                                 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
11141                                 pw.println(memInfo.getSwapFreeSizeKb());
11142                     }
11143                 }
11144                 final long[] ksm = getKsmInfo();
11145                 if (!opts.isCompact) {
11146                     if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
11147                             || ksm[KSM_VOLATILE] != 0) {
11148                         pw.print("      KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING]));
11149                                 pw.print(" saved from shared ");
11150                                 pw.print(stringifyKBSize(ksm[KSM_SHARED]));
11151                         pw.print("           "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
11152                                 pw.print(" unshared; ");
11153                                 pw.print(stringifyKBSize(
11154                                              ksm[KSM_VOLATILE])); pw.println(" volatile");
11155                     }
11156                     pw.print("   Tuning: ");
11157                     pw.print(ActivityManager.staticGetMemoryClass());
11158                     pw.print(" (large ");
11159                     pw.print(ActivityManager.staticGetLargeMemoryClass());
11160                     pw.print("), oom ");
11161                     pw.print(stringifySize(
11162                                 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
11163                     pw.print(", restore limit ");
11164                     pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
11165                     if (ActivityManager.isLowRamDeviceStatic()) {
11166                         pw.print(" (low-ram)");
11167                     }
11168                     if (ActivityManager.isHighEndGfx()) {
11169                         pw.print(" (high-end-gfx)");
11170                     }
11171                     pw.println();
11172                 } else {
11173                     pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(",");
11174                     pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]);
11175                     pw.print(","); pw.println(ksm[KSM_VOLATILE]);
11176                     pw.print("tuning,");
11177                     pw.print(ActivityManager.staticGetMemoryClass());
11178                     pw.print(',');
11179                     pw.print(ActivityManager.staticGetLargeMemoryClass());
11180                     pw.print(',');
11181                     pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
11182                     if (ActivityManager.isLowRamDeviceStatic()) {
11183                         pw.print(",low-ram");
11184                     }
11185                     if (ActivityManager.isHighEndGfx()) {
11186                         pw.print(",high-end-gfx");
11187                     }
11188                     pw.println();
11189                 }
11190             }
11191         }
11192     }
11193 
dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)11194     private final void dumpApplicationMemoryUsage(FileDescriptor fd,
11195             MemoryUsageDumpOptions opts, final String[] innerArgs, boolean brief,
11196             ArrayList<ProcessRecord> procs) {
11197         final long uptimeMs = SystemClock.uptimeMillis();
11198         final long realtimeMs = SystemClock.elapsedRealtime();
11199         final long[] tmpLong = new long[3];
11200 
11201         if (procs == null) {
11202             // No Java processes.  Maybe they want to print a native process.
11203             String proc = "N/A";
11204             if (innerArgs.length > 0) {
11205                 proc = innerArgs[0];
11206                 if (proc.charAt(0) != '-') {
11207                     final ArrayList<ProcessCpuTracker.Stats> nativeProcs
11208                             = new ArrayList<ProcessCpuTracker.Stats>();
11209                     updateCpuStatsNow();
11210                     int findPid = -1;
11211                     try {
11212                         findPid = Integer.parseInt(innerArgs[0]);
11213                     } catch (NumberFormatException e) {
11214                     }
11215                     final int fFindPid = findPid;
11216                     mAppProfiler.forAllCpuStats((st) -> {
11217                         if (st.pid == fFindPid || (st.baseName != null
11218                                 && st.baseName.equals(innerArgs[0]))) {
11219                             nativeProcs.add(st);
11220                         }
11221                     });
11222                     if (nativeProcs.size() > 0) {
11223                         ProtoOutputStream proto = new ProtoOutputStream(fd);
11224 
11225                         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
11226                         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
11227                         Debug.MemoryInfo mi = null;
11228                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
11229                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
11230                             final int pid = r.pid;
11231 
11232                             if (mi == null) {
11233                                 mi = new Debug.MemoryInfo();
11234                             }
11235                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
11236                                 if (!Debug.getMemoryInfo(pid, mi)) {
11237                                     continue;
11238                                 }
11239                             } else {
11240                                 long pss = Debug.getPss(pid, tmpLong, null);
11241                                 if (pss == 0) {
11242                                     continue;
11243                                 }
11244                                 mi.nativePss = (int) pss;
11245                                 mi.nativePrivateDirty = (int) tmpLong[0];
11246                                 mi.nativeRss = (int) tmpLong[2];
11247                             }
11248 
11249                             final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES);
11250 
11251                             proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
11252                             proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName);
11253 
11254                             ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
11255                                     opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
11256 
11257                             proto.end(nToken);
11258                         }
11259 
11260                         proto.flush();
11261                         return;
11262                     }
11263                 }
11264             }
11265             Log.d(TAG, "No process found for: " + innerArgs[0]);
11266             return;
11267         }
11268 
11269         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
11270             opts.dumpDetails = true;
11271         }
11272         final int numProcs = procs.size();
11273         final boolean collectNative = numProcs > 1 && !opts.packages;
11274         if (collectNative) {
11275             // If we are showing aggregations, also look for native processes to
11276             // include so that our aggregations are more accurate.
11277             updateCpuStatsNow();
11278         }
11279 
11280         ProtoOutputStream proto = new ProtoOutputStream(fd);
11281 
11282         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
11283         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
11284 
11285         final ArrayList<MemItem> procMems = new ArrayList<MemItem>();
11286         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
11287         final long[] ss = new long[INDEX_LAST];
11288         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11289                 EmptyArray.LONG;
11290         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11291                 EmptyArray.LONG;
11292         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
11293                 EmptyArray.LONG;
11294         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11295         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11296         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
11297 
11298         final long[] oomPss = new long[DUMP_MEM_OOM_LABEL.length];
11299         final long[] oomSwapPss = new long[DUMP_MEM_OOM_LABEL.length];
11300         final long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
11301         final ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
11302                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
11303 
11304         long cachedPss = 0;
11305         long cachedSwapPss = 0;
11306         boolean hasSwapPss = false;
11307 
11308         Debug.MemoryInfo mi = null;
11309         for (int i = numProcs - 1; i >= 0; i--) {
11310             final ProcessRecord r = procs.get(i);
11311             final IApplicationThread thread;
11312             final int pid;
11313             final int oomAdj;
11314             final boolean hasActivities;
11315             synchronized (mProcLock) {
11316                 thread = r.getThread();
11317                 pid = r.getPid();
11318                 oomAdj = r.mState.getSetAdjWithServices();
11319                 hasActivities = r.hasActivities();
11320             }
11321             if (thread == null) {
11322                 continue;
11323             }
11324             if (mi == null) {
11325                 mi = new Debug.MemoryInfo();
11326             }
11327             final int reportType;
11328             final long startTime;
11329             final long endTime;
11330             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
11331                 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
11332                 startTime = SystemClock.currentThreadTimeMillis();
11333                 if (!Debug.getMemoryInfo(pid, mi)) {
11334                     continue;
11335                 }
11336                 endTime = SystemClock.currentThreadTimeMillis();
11337                 hasSwapPss = mi.hasSwappedOutPss;
11338             } else {
11339                 reportType = ProcessStats.ADD_PSS_EXTERNAL;
11340                 startTime = SystemClock.currentThreadTimeMillis();
11341                 long pss = Debug.getPss(pid, tmpLong, null);
11342                 if (pss == 0) {
11343                     continue;
11344                 }
11345                 mi.dalvikPss = (int) pss;
11346                 endTime = SystemClock.currentThreadTimeMillis();
11347                 mi.dalvikPrivateDirty = (int) tmpLong[0];
11348                 mi.dalvikRss = (int) tmpLong[2];
11349             }
11350             if (opts.dumpDetails) {
11351                 if (opts.localOnly) {
11352                     final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES);
11353                     final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
11354                     proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
11355                     proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName);
11356                     ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
11357                             opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
11358                     proto.end(mToken);
11359                     proto.end(aToken);
11360                 } else {
11361                     try {
11362                         ByteTransferPipe tp = new ByteTransferPipe();
11363                         try {
11364                             thread.dumpMemInfoProto(tp.getWriteFd(),
11365                                 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
11366                                 opts.dumpUnreachable, innerArgs);
11367                             proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get());
11368                         } finally {
11369                             tp.kill();
11370                         }
11371                     } catch (IOException e) {
11372                         Log.e(TAG, "Got IOException!", e);
11373                     } catch (RemoteException e) {
11374                         Log.e(TAG, "Got RemoteException!", e);
11375                     }
11376                 }
11377             }
11378 
11379             final long myTotalPss = mi.getTotalPss();
11380             final long myTotalUss = mi.getTotalUss();
11381             final long myTotalRss = mi.getTotalRss();
11382             final long myTotalSwapPss = mi.getTotalSwappedOutPss();
11383 
11384             synchronized (mProcLock) {
11385                 if (r.getThread() != null && oomAdj == r.mState.getSetAdjWithServices()) {
11386                     // Record this for posterity if the process has been stable.
11387                     r.mProfile.addPss(myTotalPss, myTotalUss, myTotalRss, true,
11388                                 reportType, endTime - startTime);
11389                     r.getPkgList().forEachPackageProcessStats(holder -> {
11390                         FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
11391                                 r.info.uid,
11392                                 holder.state.getName(),
11393                                 holder.state.getPackage(),
11394                                 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
11395                                 holder.appVersion);
11396                     });
11397                 }
11398             }
11399 
11400             if (!opts.isCheckinRequest && mi != null) {
11401                 ss[INDEX_TOTAL_PSS] += myTotalPss;
11402                 ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
11403                 ss[INDEX_TOTAL_RSS] += myTotalRss;
11404                 MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
11405                         (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
11406                         myTotalSwapPss, myTotalRss, pid, hasActivities);
11407                 procMems.add(pssItem);
11408                 procMemsMap.put(pid, pssItem);
11409 
11410                 ss[INDEX_NATIVE_PSS] += mi.nativePss;
11411                 ss[INDEX_NATIVE_SWAP_PSS] += mi.nativeSwappedOutPss;
11412                 ss[INDEX_NATIVE_RSS] += mi.nativeRss;
11413                 ss[INDEX_DALVIK_PSS] += mi.dalvikPss;
11414                 ss[INDEX_DALVIK_SWAP_PSS] += mi.dalvikSwappedOutPss;
11415                 ss[INDEX_DALVIK_RSS] += mi.dalvikRss;
11416                 for (int j=0; j<dalvikSubitemPss.length; j++) {
11417                     dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
11418                     dalvikSubitemSwapPss[j] +=
11419                             mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
11420                     dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
11421                 }
11422                 ss[INDEX_OTHER_PSS] += mi.otherPss;
11423                 ss[INDEX_OTHER_RSS] += mi.otherRss;
11424                 ss[INDEX_OTHER_SWAP_PSS] += mi.otherSwappedOutPss;
11425                 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
11426                     long mem = mi.getOtherPss(j);
11427                     miscPss[j] += mem;
11428                     ss[INDEX_OTHER_PSS] -= mem;
11429                     mem = mi.getOtherSwappedOutPss(j);
11430                     miscSwapPss[j] += mem;
11431                     ss[INDEX_OTHER_SWAP_PSS] -= mem;
11432                     mem = mi.getOtherRss(j);
11433                     miscRss[j] += mem;
11434                     ss[INDEX_OTHER_RSS] -= mem;
11435                 }
11436 
11437                 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
11438                     cachedPss += myTotalPss;
11439                     cachedSwapPss += myTotalSwapPss;
11440                 }
11441 
11442                 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
11443                     if (oomIndex == (oomPss.length - 1)
11444                             || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
11445                                     && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
11446                         oomPss[oomIndex] += myTotalPss;
11447                         oomSwapPss[oomIndex] += myTotalSwapPss;
11448                         if (oomProcs[oomIndex] == null) {
11449                             oomProcs[oomIndex] = new ArrayList<MemItem>();
11450                         }
11451                         oomProcs[oomIndex].add(pssItem);
11452                         oomRss[oomIndex] += myTotalRss;
11453                         break;
11454                     }
11455                 }
11456             }
11457         }
11458 
11459         long nativeProcTotalPss = 0;
11460 
11461         if (collectNative) {
11462             mi = null;
11463             final Debug.MemoryInfo[] memInfos = new Debug.MemoryInfo[1];
11464             mAppProfiler.forAllCpuStats((st) -> {
11465                 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
11466                     if (memInfos[0] == null) {
11467                         memInfos[0] = new Debug.MemoryInfo();
11468                     }
11469                     final Debug.MemoryInfo info = memInfos[0];
11470                     if (!brief && !opts.oomOnly) {
11471                         if (!Debug.getMemoryInfo(st.pid, info)) {
11472                             return;
11473                         }
11474                     } else {
11475                         long pss = Debug.getPss(st.pid, tmpLong, null);
11476                         if (pss == 0) {
11477                             return;
11478                         }
11479                         info.nativePss = (int) pss;
11480                         info.nativePrivateDirty = (int) tmpLong[0];
11481                         info.nativeRss = (int) tmpLong[2];
11482                     }
11483 
11484                     final long myTotalPss = info.getTotalPss();
11485                     final long myTotalSwapPss = info.getTotalSwappedOutPss();
11486                     final long myTotalRss = info.getTotalRss();
11487                     ss[INDEX_TOTAL_PSS] += myTotalPss;
11488                     ss[INDEX_TOTAL_SWAP_PSS] += myTotalSwapPss;
11489                     ss[INDEX_TOTAL_RSS] += myTotalRss;
11490                     ss[INDEX_TOTAL_NATIVE_PSS] += myTotalPss;
11491 
11492                     MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
11493                             st.name, myTotalPss, info.getSummaryTotalSwapPss(), myTotalRss,
11494                             st.pid, false);
11495                     procMems.add(pssItem);
11496 
11497                     ss[INDEX_NATIVE_PSS] += info.nativePss;
11498                     ss[INDEX_NATIVE_SWAP_PSS] += info.nativeSwappedOutPss;
11499                     ss[INDEX_NATIVE_RSS] += info.nativeRss;
11500                     ss[INDEX_DALVIK_PSS] += info.dalvikPss;
11501                     ss[INDEX_DALVIK_SWAP_PSS] += info.dalvikSwappedOutPss;
11502                     ss[INDEX_DALVIK_RSS] += info.dalvikRss;
11503                     for (int j = 0; j < dalvikSubitemPss.length; j++) {
11504                         dalvikSubitemPss[j] += info.getOtherPss(
11505                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
11506                         dalvikSubitemSwapPss[j] +=
11507                                 info.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
11508                         dalvikSubitemRss[j] += info.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
11509                                 + j);
11510                     }
11511                     ss[INDEX_OTHER_PSS] += info.otherPss;
11512                     ss[INDEX_OTHER_SWAP_PSS] += info.otherSwappedOutPss;
11513                     ss[INDEX_OTHER_RSS] += info.otherRss;
11514                     for (int j = 0; j < Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
11515                         long mem = info.getOtherPss(j);
11516                         miscPss[j] += mem;
11517                         ss[INDEX_OTHER_PSS] -= mem;
11518                         mem = info.getOtherSwappedOutPss(j);
11519                         miscSwapPss[j] += mem;
11520                         ss[INDEX_OTHER_SWAP_PSS] -= mem;
11521                         mem = info.getOtherRss(j);
11522                         miscRss[j] += mem;
11523                         ss[INDEX_OTHER_RSS] -= mem;
11524                     }
11525                     oomPss[0] += myTotalPss;
11526                     oomSwapPss[0] += myTotalSwapPss;
11527                     if (oomProcs[0] == null) {
11528                         oomProcs[0] = new ArrayList<MemItem>();
11529                     }
11530                     oomProcs[0].add(pssItem);
11531                     oomRss[0] += myTotalRss;
11532                 }
11533             });
11534 
11535             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
11536 
11537             catMems.add(new MemItem("Native", "Native", ss[INDEX_NATIVE_PSS],
11538                     ss[INDEX_NATIVE_SWAP_PSS], ss[INDEX_NATIVE_RSS], -1));
11539             final int dalvikId = -2;
11540             catMems.add(new MemItem("Dalvik", "Dalvik", ss[INDEX_DALVIK_PSS],
11541                     ss[INDEX_DALVIK_SWAP_PSS], ss[INDEX_DALVIK_RSS], dalvikId));
11542             catMems.add(new MemItem("Unknown", "Unknown", ss[INDEX_OTHER_PSS],
11543                     ss[INDEX_OTHER_SWAP_PSS], ss[INDEX_OTHER_RSS], -3));
11544             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
11545                 String label = Debug.MemoryInfo.getOtherLabel(j);
11546                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j));
11547             }
11548             if (dalvikSubitemPss.length > 0) {
11549                 // Add dalvik subitems.
11550                 for (MemItem memItem : catMems) {
11551                     int memItemStart = 0, memItemEnd = 0;
11552                     if (memItem.id == dalvikId) {
11553                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
11554                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
11555                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
11556                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
11557                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
11558                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
11559                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
11560                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
11561                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
11562                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
11563                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
11564                     } else {
11565                         continue;  // No subitems, continue.
11566                     }
11567                     memItem.subitems = new ArrayList<MemItem>();
11568                     for (int j=memItemStart; j<=memItemEnd; j++) {
11569                         final String name = Debug.MemoryInfo.getOtherLabel(
11570                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
11571                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
11572                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
11573                     }
11574                 }
11575             }
11576 
11577             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
11578             for (int j=0; j<oomPss.length; j++) {
11579                 if (oomPss[j] != 0) {
11580                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
11581                             : DUMP_MEM_OOM_LABEL[j];
11582                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
11583                             DUMP_MEM_OOM_ADJ[j]);
11584                     item.subitems = oomProcs[j];
11585                     oomMems.add(item);
11586                 }
11587             }
11588 
11589             if (!opts.oomOnly) {
11590                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc",
11591                         procMems, true, false, false);
11592             }
11593             dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom",
11594                     oomMems, false, false, false);
11595             if (!brief && !opts.oomOnly) {
11596                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat",
11597                         catMems, true, false, false);
11598             }
11599 
11600             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && ss[INDEX_TOTAL_SWAP_PSS] != 0;
11601             if (!opts.oomOnly) {
11602                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc",
11603                         procMems, true, true, opts.dumpSwapPss);
11604             }
11605             dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom",
11606                     oomMems, false, true, opts.dumpSwapPss);
11607             if (!brief && !opts.oomOnly) {
11608                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat",
11609                         catMems, true, true, opts.dumpSwapPss);
11610             }
11611             MemInfoReader memInfo = new MemInfoReader();
11612             memInfo.readMemInfo();
11613             if (ss[INDEX_TOTAL_NATIVE_PSS] > 0) {
11614                 synchronized (mProcessStats.mLock) {
11615                     final long cachedKb = memInfo.getCachedSizeKb();
11616                     final long freeKb = memInfo.getFreeSizeKb();
11617                     final long zramKb = memInfo.getZramTotalSizeKb();
11618                     final long kernelKb = memInfo.getKernelUsedSizeKb();
11619                     EventLogTags.writeAmMeminfo(cachedKb * 1024, freeKb * 1024, zramKb * 1024,
11620                             kernelKb * 1024, ss[INDEX_TOTAL_NATIVE_PSS] * 1024);
11621                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
11622                             ss[INDEX_TOTAL_NATIVE_PSS]);
11623                 }
11624             }
11625             if (!brief) {
11626                 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb());
11627                 proto.write(MemInfoDumpProto.STATUS, mAppProfiler.getLastMemoryLevelLocked());
11628                 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss);
11629                 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb());
11630                 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb());
11631             }
11632             long lostRAM = memInfo.getTotalSizeKb()
11633                     - (ss[INDEX_TOTAL_PSS] - ss[INDEX_TOTAL_SWAP_PSS])
11634                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
11635                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
11636             proto.write(MemInfoDumpProto.USED_PSS_KB, ss[INDEX_TOTAL_PSS] - cachedPss);
11637             proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb());
11638             proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM);
11639             if (!brief) {
11640                 if (memInfo.getZramTotalSizeKb() != 0) {
11641                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb());
11642                     proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB,
11643                             memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb());
11644                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb());
11645                 }
11646                 final long[] ksm = getKsmInfo();
11647                 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]);
11648                 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]);
11649                 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]);
11650                 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]);
11651 
11652                 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass());
11653                 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass());
11654                 proto.write(MemInfoDumpProto.OOM_KB,
11655                         mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
11656                 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB,
11657                         mProcessList.getCachedRestoreThresholdKb());
11658 
11659                 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic());
11660                 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx());
11661             }
11662         }
11663 
11664         proto.flush();
11665     }
11666 
appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)11667     static void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss,
11668             long memtrack, String name) {
11669         sb.append("  ");
11670         sb.append(ProcessList.makeOomAdjString(oomAdj, false));
11671         sb.append(' ');
11672         sb.append(ProcessList.makeProcStateString(procState));
11673         sb.append(' ');
11674         ProcessList.appendRamKb(sb, pss);
11675         sb.append(": ");
11676         sb.append(name);
11677         if (memtrack > 0) {
11678             sb.append(" (");
11679             sb.append(stringifyKBSize(memtrack));
11680             sb.append(" memtrack)");
11681         }
11682     }
11683 
appendMemInfo(StringBuilder sb, ProcessMemInfo mi)11684     static void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) {
11685         appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name);
11686         sb.append(" (pid ");
11687         sb.append(mi.pid);
11688         sb.append(") ");
11689         sb.append(mi.adjType);
11690         sb.append('\n');
11691         if (mi.adjReason != null) {
11692             sb.append("                      ");
11693             sb.append(mi.adjReason);
11694             sb.append('\n');
11695         }
11696     }
11697 
11698     /**
11699      * Searches array of arguments for the specified string
11700      * @param args array of argument strings
11701      * @param value value to search for
11702      * @return true if the value is contained in the array
11703      */
scanArgs(String[] args, String value)11704     private static boolean scanArgs(String[] args, String value) {
11705         if (args != null) {
11706             for (String arg : args) {
11707                 if (value.equals(arg)) {
11708                     return true;
11709                 }
11710             }
11711         }
11712         return false;
11713     }
11714 
11715     /**
11716      * Main code for cleaning up a process when it has gone away.  This is
11717      * called both as a result of the process dying, or directly when stopping
11718      * a process when running in single process mode.
11719      *
11720      * @return Returns true if the given process has been restarted, so the
11721      * app that was passed in must remain on the process lists.
11722      */
11723     @GuardedBy("this")
cleanUpApplicationRecordLocked(ProcessRecord app, int pid, boolean restarting, boolean allowRestart, int index, boolean replacingPid, boolean fromBinderDied)11724     final boolean cleanUpApplicationRecordLocked(ProcessRecord app, int pid,
11725             boolean restarting, boolean allowRestart, int index, boolean replacingPid,
11726             boolean fromBinderDied) {
11727         boolean restart;
11728         synchronized (mProcLock) {
11729             if (index >= 0) {
11730                 removeLruProcessLocked(app);
11731                 ProcessList.remove(pid);
11732             }
11733 
11734             // We don't want to unlinkDeathRecipient immediately, if it's not called from binder
11735             // and it's not isolated, as we'd need the signal to bookkeeping the dying process list.
11736             restart = app.onCleanupApplicationRecordLSP(mProcessStats, allowRestart,
11737                     fromBinderDied || app.isolated /* unlinkDeath */);
11738 
11739             // Cancel pending frozen task if there is any.
11740             mOomAdjuster.mCachedAppOptimizer.unscheduleFreezeAppLSP(app);
11741         }
11742         mAppProfiler.onCleanupApplicationRecordLocked(app);
11743         skipCurrentReceiverLocked(app);
11744         updateProcessForegroundLocked(app, false, 0, false);
11745         mServices.killServicesLocked(app, allowRestart);
11746         mPhantomProcessList.onAppDied(pid);
11747 
11748         // If the app is undergoing backup, tell the backup manager about it
11749         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
11750         if (backupTarget != null && pid == backupTarget.app.getPid()) {
11751             if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App "
11752                     + backupTarget.appInfo + " died during backup");
11753             mHandler.post(new Runnable() {
11754                 @Override
11755                 public void run(){
11756                     try {
11757                         IBackupManager bm = IBackupManager.Stub.asInterface(
11758                                 ServiceManager.getService(Context.BACKUP_SERVICE));
11759                         bm.agentDisconnectedForUser(app.userId, app.info.packageName);
11760                     } catch (RemoteException e) {
11761                         // can't happen; backup manager is local
11762                     }
11763                 }
11764             });
11765         }
11766 
11767         mProcessList.scheduleDispatchProcessDiedLocked(pid, app.info.uid);
11768 
11769         // If this is a preceding instance of another process instance
11770         allowRestart = mProcessList.handlePrecedingAppDiedLocked(app);
11771 
11772         // If the caller is restarting this app, then leave it in its
11773         // current lists and let the caller take care of it.
11774         if (restarting) {
11775             return false;
11776         }
11777 
11778         if (!app.isPersistent() || app.isolated) {
11779             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
11780                     "Removing non-persistent process during cleanup: " + app);
11781             if (!replacingPid) {
11782                 mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
11783             }
11784             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
11785         } else if (!app.isRemoved()) {
11786             // This app is persistent, so we need to keep its record around.
11787             // If it is not already on the pending app list, add it there
11788             // and start a new process for it.
11789             if (mPersistentStartingProcesses.indexOf(app) < 0) {
11790                 mPersistentStartingProcesses.add(app);
11791                 restart = true;
11792             }
11793         }
11794         if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(
11795                 TAG_CLEANUP, "Clean-up removing on hold: " + app);
11796         mProcessesOnHold.remove(app);
11797 
11798         mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController());
11799         mProcessList.noteProcessDiedLocked(app);
11800 
11801         if (restart && allowRestart && !app.isolated) {
11802             // We have components that still need to be running in the
11803             // process, so re-launch it.
11804             if (index < 0) {
11805                 ProcessList.remove(pid);
11806             }
11807 
11808             // Remove provider publish timeout because we will start a new timeout when the
11809             // restarted process is attaching (if the process contains launching providers).
11810             mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app);
11811 
11812             mProcessList.addProcessNameLocked(app);
11813             app.setPendingStart(false);
11814             mProcessList.startProcessLocked(app, new HostingRecord("restart", app.processName),
11815                     ZYGOTE_POLICY_FLAG_EMPTY);
11816             return true;
11817         } else if (pid > 0 && pid != MY_PID) {
11818             // Goodbye!
11819             removePidLocked(pid, app);
11820             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
11821             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
11822             if (app.isolated) {
11823                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
11824             }
11825             app.setPid(0);
11826         }
11827         return false;
11828     }
11829 
11830     // =========================================================
11831     // SERVICES
11832     // =========================================================
11833 
11834     @Override
getServices(int maxNum, int flags)11835     public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) {
11836         enforceNotIsolatedCaller("getServices");
11837 
11838         final int callingUid = Binder.getCallingUid();
11839         final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission(
11840             INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED);
11841         final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices",
11842                 Binder.getCallingPid(), callingUid);
11843         synchronized (this) {
11844             return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid,
11845                 allowed, canInteractAcrossUsers);
11846         }
11847     }
11848 
11849     @Override
getRunningServiceControlPanel(ComponentName name)11850     public PendingIntent getRunningServiceControlPanel(ComponentName name) {
11851         enforceNotIsolatedCaller("getRunningServiceControlPanel");
11852         synchronized (this) {
11853             return mServices.getRunningServiceControlPanelLocked(name);
11854         }
11855     }
11856 
11857     @Override
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)11858     public ComponentName startService(IApplicationThread caller, Intent service,
11859             String resolvedType, boolean requireForeground, String callingPackage,
11860             String callingFeatureId, int userId)
11861             throws TransactionTooLargeException {
11862         enforceNotIsolatedCaller("startService");
11863         // Refuse possible leaked file descriptors
11864         if (service != null && service.hasFileDescriptors() == true) {
11865             throw new IllegalArgumentException("File descriptors passed in Intent");
11866         }
11867 
11868         if (callingPackage == null) {
11869             throw new IllegalArgumentException("callingPackage cannot be null");
11870         }
11871 
11872         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
11873                 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
11874         synchronized(this) {
11875             final int callingPid = Binder.getCallingPid();
11876             final int callingUid = Binder.getCallingUid();
11877             final long origId = Binder.clearCallingIdentity();
11878             ComponentName res;
11879             try {
11880                 res = mServices.startServiceLocked(caller, service,
11881                         resolvedType, callingPid, callingUid,
11882                         requireForeground, callingPackage, callingFeatureId, userId);
11883             } finally {
11884                 Binder.restoreCallingIdentity(origId);
11885             }
11886             return res;
11887         }
11888     }
11889 
11890     @Override
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)11891     public int stopService(IApplicationThread caller, Intent service,
11892             String resolvedType, int userId) {
11893         enforceNotIsolatedCaller("stopService");
11894         // Refuse possible leaked file descriptors
11895         if (service != null && service.hasFileDescriptors() == true) {
11896             throw new IllegalArgumentException("File descriptors passed in Intent");
11897         }
11898 
11899         synchronized(this) {
11900             return mServices.stopServiceLocked(caller, service, resolvedType, userId);
11901         }
11902     }
11903 
11904     @Override
peekService(Intent service, String resolvedType, String callingPackage)11905     public IBinder peekService(Intent service, String resolvedType, String callingPackage) {
11906         enforceNotIsolatedCaller("peekService");
11907         // Refuse possible leaked file descriptors
11908         if (service != null && service.hasFileDescriptors() == true) {
11909             throw new IllegalArgumentException("File descriptors passed in Intent");
11910         }
11911 
11912         if (callingPackage == null) {
11913             throw new IllegalArgumentException("callingPackage cannot be null");
11914         }
11915 
11916         synchronized(this) {
11917             return mServices.peekServiceLocked(service, resolvedType, callingPackage);
11918         }
11919     }
11920 
11921     @Override
stopServiceToken(ComponentName className, IBinder token, int startId)11922     public boolean stopServiceToken(ComponentName className, IBinder token,
11923             int startId) {
11924         synchronized(this) {
11925             return mServices.stopServiceTokenLocked(className, token, startId);
11926         }
11927     }
11928 
11929     @Override
setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)11930     public void setServiceForeground(ComponentName className, IBinder token,
11931             int id, Notification notification, int flags, int foregroundServiceType) {
11932         synchronized(this) {
11933             mServices.setServiceForegroundLocked(className, token, id, notification, flags,
11934                     foregroundServiceType);
11935         }
11936     }
11937 
11938     @Override
getForegroundServiceType(ComponentName className, IBinder token)11939     public int getForegroundServiceType(ComponentName className, IBinder token) {
11940         synchronized (this) {
11941             return mServices.getForegroundServiceTypeLocked(className, token);
11942         }
11943     }
11944 
11945     @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)11946     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11947             boolean requireFull, String name, String callerPackage) {
11948         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
11949                 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
11950     }
11951 
isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)11952     boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11953             String className, int flags) {
11954         boolean result = false;
11955         // For apps that don't have pre-defined UIDs, check for permission
11956         if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) {
11957             if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
11958                 if (ActivityManager.checkUidPermission(
11959                         INTERACT_ACROSS_USERS,
11960                         aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11961                     ComponentName comp = new ComponentName(aInfo.packageName, className);
11962                     String msg = "Permission Denial: Component " + comp.flattenToShortString()
11963                             + " requests FLAG_SINGLE_USER, but app does not hold "
11964                             + INTERACT_ACROSS_USERS;
11965                     Slog.w(TAG, msg);
11966                     throw new SecurityException(msg);
11967                 }
11968                 // Permission passed
11969                 result = true;
11970             }
11971         } else if ("system".equals(componentProcessName)) {
11972             result = true;
11973         } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
11974             // Phone app and persistent apps are allowed to export singleuser providers.
11975             result = UserHandle.isSameApp(aInfo.uid, PHONE_UID)
11976                     || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11977         }
11978         if (DEBUG_MU) Slog.v(TAG_MU,
11979                 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x"
11980                 + Integer.toHexString(flags) + ") = " + result);
11981         return result;
11982     }
11983 
11984     /**
11985      * Checks to see if the caller is in the same app as the singleton
11986      * component, or the component is in a special app. It allows special apps
11987      * to export singleton components but prevents exporting singleton
11988      * components for regular apps.
11989      */
isValidSingletonCall(int callingUid, int componentUid)11990     boolean isValidSingletonCall(int callingUid, int componentUid) {
11991         int componentAppId = UserHandle.getAppId(componentUid);
11992         return UserHandle.isSameApp(callingUid, componentUid)
11993                 || componentAppId == SYSTEM_UID
11994                 || componentAppId == PHONE_UID
11995                 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
11996                         == PackageManager.PERMISSION_GRANTED;
11997     }
11998 
bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)11999     public int bindService(IApplicationThread caller, IBinder token, Intent service,
12000             String resolvedType, IServiceConnection connection, int flags,
12001             String callingPackage, int userId) throws TransactionTooLargeException {
12002         return bindIsolatedService(caller, token, service, resolvedType, connection, flags,
12003                 null, callingPackage, userId);
12004     }
12005 
bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)12006     public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
12007             String resolvedType, IServiceConnection connection, int flags, String instanceName,
12008             String callingPackage, int userId) throws TransactionTooLargeException {
12009         enforceNotIsolatedCaller("bindService");
12010 
12011         // Refuse possible leaked file descriptors
12012         if (service != null && service.hasFileDescriptors() == true) {
12013             throw new IllegalArgumentException("File descriptors passed in Intent");
12014         }
12015 
12016         if (callingPackage == null) {
12017             throw new IllegalArgumentException("callingPackage cannot be null");
12018         }
12019 
12020         // Ensure that instanceName, which is caller provided, does not contain
12021         // unusual characters.
12022         if (instanceName != null) {
12023             for (int i = 0; i < instanceName.length(); ++i) {
12024                 char c = instanceName.charAt(i);
12025                 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
12026                             || (c >= '0' && c <= '9') || c == '_' || c == '.')) {
12027                     throw new IllegalArgumentException("Illegal instanceName");
12028                 }
12029             }
12030         }
12031 
12032         synchronized(this) {
12033             return mServices.bindServiceLocked(caller, token, service,
12034                     resolvedType, connection, flags, instanceName, callingPackage, userId);
12035         }
12036     }
12037 
updateServiceGroup(IServiceConnection connection, int group, int importance)12038     public void updateServiceGroup(IServiceConnection connection, int group, int importance) {
12039         synchronized (this) {
12040             mServices.updateServiceGroupLocked(connection, group, importance);
12041         }
12042     }
12043 
unbindService(IServiceConnection connection)12044     public boolean unbindService(IServiceConnection connection) {
12045         synchronized (this) {
12046             return mServices.unbindServiceLocked(connection);
12047         }
12048     }
12049 
publishService(IBinder token, Intent intent, IBinder service)12050     public void publishService(IBinder token, Intent intent, IBinder service) {
12051         // Refuse possible leaked file descriptors
12052         if (intent != null && intent.hasFileDescriptors() == true) {
12053             throw new IllegalArgumentException("File descriptors passed in Intent");
12054         }
12055 
12056         synchronized(this) {
12057             if (!(token instanceof ServiceRecord)) {
12058                 throw new IllegalArgumentException("Invalid service token");
12059             }
12060             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
12061         }
12062     }
12063 
unbindFinished(IBinder token, Intent intent, boolean doRebind)12064     public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12065         // Refuse possible leaked file descriptors
12066         if (intent != null && intent.hasFileDescriptors() == true) {
12067             throw new IllegalArgumentException("File descriptors passed in Intent");
12068         }
12069 
12070         synchronized(this) {
12071             mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
12072         }
12073     }
12074 
serviceDoneExecuting(IBinder token, int type, int startId, int res)12075     public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
12076         synchronized(this) {
12077             if (!(token instanceof ServiceRecord)) {
12078                 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
12079                 throw new IllegalArgumentException("Invalid service token");
12080             }
12081             mServices.serviceDoneExecutingLocked((ServiceRecord) token, type, startId, res, false);
12082         }
12083     }
12084 
12085     // =========================================================
12086     // BACKUP AND RESTORE
12087     // =========================================================
12088 
12089     // Cause the target app to be launched if necessary and its backup agent
12090     // instantiated.  The backup agent will invoke backupAgentCreated() on the
12091     // activity manager to announce its creation.
bindBackupAgent(String packageName, int backupMode, int targetUserId, @OperationType int operationType)12092     public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId,
12093             @OperationType int operationType) {
12094         if (DEBUG_BACKUP) {
12095             Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
12096                     + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
12097                     + " uid = " + Process.myUid());
12098         }
12099         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
12100 
12101         // The instantiatedUserId is the user of the process the backup agent is started in. This is
12102         // different from the targetUserId which is the user whose data is to be backed up or
12103         // restored. This distinction is important for system-process packages that live in the
12104         // system user's process but backup/restore data for non-system users.
12105         // TODO (b/123688746): Handle all system-process packages with singleton check.
12106         final int instantiatedUserId =
12107                 PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId;
12108 
12109         IPackageManager pm = AppGlobals.getPackageManager();
12110         ApplicationInfo app = null;
12111         try {
12112             app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
12113         } catch (RemoteException e) {
12114             // can't happen; package manager is process-local
12115         }
12116         if (app == null) {
12117             Slog.w(TAG, "Unable to bind backup agent for " + packageName);
12118             return false;
12119         }
12120 
12121         int oldBackupUid;
12122         int newBackupUid;
12123 
12124         synchronized(this) {
12125             // !!! TODO: currently no check here that we're already bound
12126             // Backup agent is now in use, its package can't be stopped.
12127             try {
12128                 AppGlobals.getPackageManager().setPackageStoppedState(
12129                         app.packageName, false, UserHandle.getUserId(app.uid));
12130             } catch (RemoteException e) {
12131             } catch (IllegalArgumentException e) {
12132                 Slog.w(TAG, "Failed trying to unstop package "
12133                         + app.packageName + ": " + e);
12134             }
12135 
12136             BackupRecord r = new BackupRecord(app, backupMode, targetUserId, operationType);
12137             ComponentName hostingName =
12138                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL)
12139                             ? new ComponentName(app.packageName, app.backupAgentName)
12140                             : new ComponentName("android", "FullBackupAgent");
12141 
12142             // startProcessLocked() returns existing proc's record if it's already running
12143             ProcessRecord proc = startProcessLocked(app.processName, app,
12144                     false, 0,
12145                     new HostingRecord("backup", hostingName),
12146                     ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false);
12147             if (proc == null) {
12148                 Slog.e(TAG, "Unable to start backup agent process " + r);
12149                 return false;
12150             }
12151 
12152             // If the app is a regular app (uid >= 10000) and not the system server or phone
12153             // process, etc, then mark it as being in full backup so that certain calls to the
12154             // process can be blocked. This is not reset to false anywhere because we kill the
12155             // process after the full backup is done and the ProcessRecord will vaporize anyway.
12156             if (UserHandle.isApp(app.uid) &&
12157                     backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) {
12158                 proc.setInFullBackup(true);
12159             }
12160             r.app = proc;
12161             final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
12162             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
12163             newBackupUid = proc.isInFullBackup() ? r.appInfo.uid : -1;
12164             mBackupTargets.put(targetUserId, r);
12165 
12166             // Try not to kill the process during backup
12167             updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_NONE);
12168 
12169             // If the process is already attached, schedule the creation of the backup agent now.
12170             // If it is not yet live, this will be done when it attaches to the framework.
12171             final IApplicationThread thread = proc.getThread();
12172             if (thread != null) {
12173                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
12174                 try {
12175                     thread.scheduleCreateBackupAgent(app,
12176                             compatibilityInfoForPackage(app), backupMode, targetUserId,
12177                             operationType);
12178                 } catch (RemoteException e) {
12179                     // Will time out on the backup manager side
12180                 }
12181             } else {
12182                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach");
12183             }
12184             // Invariants: at this point, the target app process exists and the application
12185             // is either already running or in the process of coming up.  mBackupTarget and
12186             // mBackupAppName describe the app, so that when it binds back to the AM we
12187             // know that it's scheduled for a backup-agent operation.
12188         }
12189 
12190         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
12191         if (oldBackupUid != -1) {
12192             js.removeBackingUpUid(oldBackupUid);
12193         }
12194         if (newBackupUid != -1) {
12195             js.addBackingUpUid(newBackupUid);
12196         }
12197 
12198         return true;
12199     }
12200 
clearPendingBackup(int userId)12201     private void clearPendingBackup(int userId) {
12202         if (DEBUG_BACKUP) {
12203             Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = "
12204                     + Binder.getCallingUid() + " uid = " + Process.myUid());
12205         }
12206 
12207         synchronized (this) {
12208             mBackupTargets.delete(userId);
12209         }
12210 
12211         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
12212         js.clearAllBackingUpUids();
12213     }
12214 
12215     // A backup agent has just come up
12216     @Override
backupAgentCreated(String agentPackageName, IBinder agent, int userId)12217     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
12218         // Resolve the target user id and enforce permissions.
12219         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
12220                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
12221         if (DEBUG_BACKUP) {
12222             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
12223                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
12224                     + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid());
12225         }
12226 
12227         synchronized(this) {
12228             final BackupRecord backupTarget = mBackupTargets.get(userId);
12229             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
12230             if (!agentPackageName.equals(backupAppName)) {
12231                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
12232                 return;
12233             }
12234         }
12235 
12236         final long oldIdent = Binder.clearCallingIdentity();
12237         try {
12238             IBackupManager bm = IBackupManager.Stub.asInterface(
12239                     ServiceManager.getService(Context.BACKUP_SERVICE));
12240             bm.agentConnectedForUser(userId, agentPackageName, agent);
12241         } catch (RemoteException e) {
12242             // can't happen; the backup manager service is local
12243         } catch (Exception e) {
12244             Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12245             e.printStackTrace();
12246         } finally {
12247             Binder.restoreCallingIdentity(oldIdent);
12248         }
12249     }
12250 
12251     // done with this agent
unbindBackupAgent(ApplicationInfo appInfo)12252     public void unbindBackupAgent(ApplicationInfo appInfo) {
12253         if (DEBUG_BACKUP) {
12254             Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = "
12255                     + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = "
12256                     + Process.myUid());
12257         }
12258 
12259         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent");
12260         if (appInfo == null) {
12261             Slog.w(TAG, "unbind backup agent for null app");
12262             return;
12263         }
12264 
12265         int oldBackupUid;
12266 
12267         final int userId = UserHandle.getUserId(appInfo.uid);
12268         synchronized(this) {
12269             final BackupRecord backupTarget = mBackupTargets.get(userId);
12270             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
12271             try {
12272                 if (backupAppName == null) {
12273                     Slog.w(TAG, "Unbinding backup agent with no active backup");
12274                     return;
12275                 }
12276 
12277                 if (!backupAppName.equals(appInfo.packageName)) {
12278                     Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
12279                     return;
12280                 }
12281 
12282                 // Not backing this app up any more; reset its OOM adjustment
12283                 final ProcessRecord proc = backupTarget.app;
12284                 updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_NONE);
12285                 proc.setInFullBackup(false);
12286 
12287                 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
12288 
12289                 // If the app crashed during backup, 'thread' will be null here
12290                 final IApplicationThread thread = proc.getThread();
12291                 if (thread != null) {
12292                     try {
12293                         thread.scheduleDestroyBackupAgent(appInfo,
12294                                 compatibilityInfoForPackage(appInfo), userId);
12295                     } catch (Exception e) {
12296                         Slog.e(TAG, "Exception when unbinding backup agent:");
12297                         e.printStackTrace();
12298                     }
12299                 }
12300             } finally {
12301                 mBackupTargets.delete(userId);
12302             }
12303         }
12304 
12305         if (oldBackupUid != -1) {
12306             JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
12307             js.removeBackingUpUid(oldBackupUid);
12308         }
12309     }
12310 
12311     // =========================================================
12312     // BROADCASTS
12313     // =========================================================
12314 
isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)12315     private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) {
12316         if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) {
12317             return false;
12318         }
12319         // Easy case -- we have the app's ProcessRecord.
12320         if (record != null) {
12321             return record.info.isInstantApp();
12322         }
12323         // Otherwise check with PackageManager.
12324         IPackageManager pm = AppGlobals.getPackageManager();
12325         try {
12326             if (callerPackage == null) {
12327                 final String[] packageNames = pm.getPackagesForUid(uid);
12328                 if (packageNames == null || packageNames.length == 0) {
12329                     throw new IllegalArgumentException("Unable to determine caller package name");
12330                 }
12331                 // Instant Apps can't use shared uids, so its safe to only check the first package.
12332                 callerPackage = packageNames[0];
12333             }
12334             mAppOpsService.checkPackage(uid, callerPackage);
12335             return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid));
12336         } catch (RemoteException e) {
12337             Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e);
12338             return true;
12339         }
12340     }
12341 
isPendingBroadcastProcessLocked(int pid)12342     boolean isPendingBroadcastProcessLocked(int pid) {
12343         return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12344                 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12345                 || mOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12346     }
12347 
skipPendingBroadcastLocked(int pid)12348     void skipPendingBroadcastLocked(int pid) {
12349             Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12350             for (BroadcastQueue queue : mBroadcastQueues) {
12351                 queue.skipPendingBroadcastLocked(pid);
12352             }
12353     }
12354 
12355     // The app just attached; send any pending broadcasts that it should receive
sendPendingBroadcastsLocked(ProcessRecord app)12356     boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12357         boolean didSomething = false;
12358         for (BroadcastQueue queue : mBroadcastQueues) {
12359             didSomething |= queue.sendPendingBroadcastsLocked(app);
12360         }
12361         return didSomething;
12362     }
12363 
12364     /**
12365      * @deprecated Use {@link #registerReceiverWithFeature}
12366      */
12367     @Deprecated
registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)12368     public Intent registerReceiver(IApplicationThread caller, String callerPackage,
12369             IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
12370             int flags) {
12371         return registerReceiverWithFeature(caller, callerPackage, null, null,
12372                 receiver, filter, permission, userId, flags);
12373     }
12374 
registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, String receiverId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)12375     public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage,
12376             String callerFeatureId, String receiverId, IIntentReceiver receiver,
12377             IntentFilter filter, String permission, int userId, int flags) {
12378         enforceNotIsolatedCaller("registerReceiver");
12379         ArrayList<Intent> stickyIntents = null;
12380         ProcessRecord callerApp = null;
12381         final boolean visibleToInstantApps
12382                 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
12383         int callingUid;
12384         int callingPid;
12385         boolean instantApp;
12386         synchronized(this) {
12387             if (caller != null) {
12388                 callerApp = getRecordForAppLOSP(caller);
12389                 if (callerApp == null) {
12390                     throw new SecurityException(
12391                             "Unable to find app for caller " + caller
12392                             + " (pid=" + Binder.getCallingPid()
12393                             + ") when registering receiver " + receiver);
12394                 }
12395                 if (callerApp.info.uid != SYSTEM_UID
12396                         && !callerApp.getPkgList().containsKey(callerPackage)
12397                         && !"android".equals(callerPackage)) {
12398                     throw new SecurityException("Given caller package " + callerPackage
12399                             + " is not running in process " + callerApp);
12400                 }
12401                 callingUid = callerApp.info.uid;
12402                 callingPid = callerApp.getPid();
12403             } else {
12404                 callerPackage = null;
12405                 callingUid = Binder.getCallingUid();
12406                 callingPid = Binder.getCallingPid();
12407             }
12408 
12409             instantApp = isInstantApp(callerApp, callerPackage, callingUid);
12410             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
12411                     ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
12412 
12413             Iterator<String> actions = filter.actionsIterator();
12414             if (actions == null) {
12415                 ArrayList<String> noAction = new ArrayList<String>(1);
12416                 noAction.add(null);
12417                 actions = noAction.iterator();
12418             }
12419 
12420             // Collect stickies of users
12421             int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) };
12422             while (actions.hasNext()) {
12423                 String action = actions.next();
12424                 for (int id : userIds) {
12425                     ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id);
12426                     if (stickies != null) {
12427                         ArrayList<Intent> intents = stickies.get(action);
12428                         if (intents != null) {
12429                             if (stickyIntents == null) {
12430                                 stickyIntents = new ArrayList<Intent>();
12431                             }
12432                             stickyIntents.addAll(intents);
12433                         }
12434                     }
12435                 }
12436             }
12437         }
12438 
12439         ArrayList<Intent> allSticky = null;
12440         if (stickyIntents != null) {
12441             final ContentResolver resolver = mContext.getContentResolver();
12442             // Look for any matching sticky broadcasts...
12443             for (int i = 0, N = stickyIntents.size(); i < N; i++) {
12444                 Intent intent = stickyIntents.get(i);
12445                 // Don't provided intents that aren't available to instant apps.
12446                 if (instantApp &&
12447                         (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) {
12448                     continue;
12449                 }
12450                 // If intent has scheme "content", it will need to acccess
12451                 // provider that needs to lock mProviderMap in ActivityThread
12452                 // and also it may need to wait application response, so we
12453                 // cannot lock ActivityManagerService here.
12454                 if (filter.match(resolver, intent, true, TAG) >= 0) {
12455                     if (allSticky == null) {
12456                         allSticky = new ArrayList<Intent>();
12457                     }
12458                     allSticky.add(intent);
12459                 }
12460             }
12461         }
12462 
12463         // The first sticky in the list is returned directly back to the client.
12464         Intent sticky = allSticky != null ? allSticky.get(0) : null;
12465         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky);
12466         if (receiver == null) {
12467             return sticky;
12468         }
12469 
12470         // SafetyNet logging for b/177931370. If any process other than system_server tries to
12471         // listen to this broadcast action, then log it.
12472         if (callingPid != Process.myPid()) {
12473             if (filter.hasAction("com.android.server.net.action.SNOOZE_WARNING")
12474                     || filter.hasAction("com.android.server.net.action.SNOOZE_RAPID")) {
12475                 EventLog.writeEvent(0x534e4554, "177931370", callingUid, "");
12476             }
12477         }
12478 
12479         synchronized (this) {
12480             IApplicationThread thread;
12481             if (callerApp != null && ((thread = callerApp.getThread()) == null
12482                     || thread.asBinder() != caller.asBinder())) {
12483                 // Original caller already died
12484                 return null;
12485             }
12486             ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
12487             if (rl == null) {
12488                 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
12489                         userId, receiver);
12490                 if (rl.app != null) {
12491                     final int totalReceiversForApp = rl.app.mReceivers.numberOfReceivers();
12492                     if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) {
12493                         throw new IllegalStateException("Too many receivers, total of "
12494                                 + totalReceiversForApp + ", registered for pid: "
12495                                 + rl.pid + ", callerPackage: " + callerPackage);
12496                     }
12497                     rl.app.mReceivers.addReceiver(rl);
12498                 } else {
12499                     try {
12500                         receiver.asBinder().linkToDeath(rl, 0);
12501                     } catch (RemoteException e) {
12502                         return sticky;
12503                     }
12504                     rl.linkedToDeath = true;
12505                 }
12506                 mRegisteredReceivers.put(receiver.asBinder(), rl);
12507             } else if (rl.uid != callingUid) {
12508                 throw new IllegalArgumentException(
12509                         "Receiver requested to register for uid " + callingUid
12510                         + " was previously registered for uid " + rl.uid
12511                         + " callerPackage is " + callerPackage);
12512             } else if (rl.pid != callingPid) {
12513                 throw new IllegalArgumentException(
12514                         "Receiver requested to register for pid " + callingPid
12515                         + " was previously registered for pid " + rl.pid
12516                         + " callerPackage is " + callerPackage);
12517             } else if (rl.userId != userId) {
12518                 throw new IllegalArgumentException(
12519                         "Receiver requested to register for user " + userId
12520                         + " was previously registered for user " + rl.userId
12521                         + " callerPackage is " + callerPackage);
12522             }
12523             BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId,
12524                     receiverId, permission, callingUid, userId, instantApp, visibleToInstantApps);
12525             if (rl.containsFilter(filter)) {
12526                 Slog.w(TAG, "Receiver with filter " + filter
12527                         + " already registered for pid " + rl.pid
12528                         + ", callerPackage is " + callerPackage);
12529             } else {
12530                 rl.add(bf);
12531                 if (!bf.debugCheck()) {
12532                     Slog.w(TAG, "==> For Dynamic broadcast");
12533                 }
12534                 mReceiverResolver.addFilter(bf);
12535             }
12536 
12537             // Enqueue broadcasts for all existing stickies that match
12538             // this filter.
12539             if (allSticky != null) {
12540                 ArrayList receivers = new ArrayList();
12541                 receivers.add(bf);
12542 
12543                 final int stickyCount = allSticky.size();
12544                 for (int i = 0; i < stickyCount; i++) {
12545                     Intent intent = allSticky.get(i);
12546                     BroadcastQueue queue = broadcastQueueForIntent(intent);
12547                     BroadcastRecord r = new BroadcastRecord(queue, intent, null,
12548                             null, null, -1, -1, false, null, null, null, OP_NONE, null, receivers,
12549                             null, 0, null, null, false, true, true, -1, false, null,
12550                             false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */);
12551                     queue.enqueueParallelBroadcastLocked(r);
12552                     queue.scheduleBroadcastsLocked();
12553                 }
12554             }
12555 
12556             return sticky;
12557         }
12558     }
12559 
unregisterReceiver(IIntentReceiver receiver)12560     public void unregisterReceiver(IIntentReceiver receiver) {
12561         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver);
12562 
12563         final long origId = Binder.clearCallingIdentity();
12564         try {
12565             boolean doTrim = false;
12566 
12567             synchronized(this) {
12568                 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
12569                 if (rl != null) {
12570                     final BroadcastRecord r = rl.curBroadcast;
12571                     if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) {
12572                         final boolean doNext = r.queue.finishReceiverLocked(
12573                                 r, r.resultCode, r.resultData, r.resultExtras,
12574                                 r.resultAbort, false);
12575                         if (doNext) {
12576                             doTrim = true;
12577                             r.queue.processNextBroadcastLocked(/* frommsg */ false,
12578                                     /* skipOomAdj */ true);
12579                         }
12580                     }
12581 
12582                     if (rl.app != null) {
12583                         rl.app.mReceivers.removeReceiver(rl);
12584                     }
12585                     removeReceiverLocked(rl);
12586                     if (rl.linkedToDeath) {
12587                         rl.linkedToDeath = false;
12588                         rl.receiver.asBinder().unlinkToDeath(rl, 0);
12589                     }
12590                 }
12591 
12592                 // If we actually concluded any broadcasts, we might now be able
12593                 // to trim the recipients' apps from our working set
12594                 if (doTrim) {
12595                     trimApplicationsLocked(false, OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
12596                     return;
12597                 }
12598             }
12599 
12600         } finally {
12601             Binder.restoreCallingIdentity(origId);
12602         }
12603     }
12604 
removeReceiverLocked(ReceiverList rl)12605     void removeReceiverLocked(ReceiverList rl) {
12606         mRegisteredReceivers.remove(rl.receiver.asBinder());
12607         for (int i = rl.size() - 1; i >= 0; i--) {
12608             mReceiverResolver.removeFilter(rl.get(i));
12609         }
12610     }
12611 
sendPackageBroadcastLocked(int cmd, String[] packages, int userId)12612     private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
12613         mProcessList.sendPackageBroadcastLocked(cmd, packages, userId);
12614     }
12615 
collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users, int[] broadcastAllowList)12616     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
12617             int callingUid, int[] users, int[] broadcastAllowList) {
12618         // TODO: come back and remove this assumption to triage all broadcasts
12619         int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
12620 
12621         List<ResolveInfo> receivers = null;
12622         try {
12623             HashSet<ComponentName> singleUserReceivers = null;
12624             boolean scannedFirstReceivers = false;
12625             for (int user : users) {
12626                 // Skip users that have Shell restrictions
12627                 if (callingUid == SHELL_UID
12628                         && mUserController.hasUserRestriction(
12629                                 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) {
12630                     continue;
12631                 }
12632                 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
12633                         .queryIntentReceivers(intent, resolvedType, pmFlags, user).getList();
12634                 if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
12635                     // If this is not the system user, we need to check for
12636                     // any receivers that should be filtered out.
12637                     for (int i=0; i<newReceivers.size(); i++) {
12638                         ResolveInfo ri = newReceivers.get(i);
12639                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
12640                             newReceivers.remove(i);
12641                             i--;
12642                         }
12643                     }
12644                 }
12645                 if (newReceivers != null && newReceivers.size() == 0) {
12646                     newReceivers = null;
12647                 }
12648                 if (receivers == null) {
12649                     receivers = newReceivers;
12650                 } else if (newReceivers != null) {
12651                     // We need to concatenate the additional receivers
12652                     // found with what we have do far.  This would be easy,
12653                     // but we also need to de-dup any receivers that are
12654                     // singleUser.
12655                     if (!scannedFirstReceivers) {
12656                         // Collect any single user receivers we had already retrieved.
12657                         scannedFirstReceivers = true;
12658                         for (int i=0; i<receivers.size(); i++) {
12659                             ResolveInfo ri = receivers.get(i);
12660                             if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
12661                                 ComponentName cn = new ComponentName(
12662                                         ri.activityInfo.packageName, ri.activityInfo.name);
12663                                 if (singleUserReceivers == null) {
12664                                     singleUserReceivers = new HashSet<ComponentName>();
12665                                 }
12666                                 singleUserReceivers.add(cn);
12667                             }
12668                         }
12669                     }
12670                     // Add the new results to the existing results, tracking
12671                     // and de-dupping single user receivers.
12672                     for (int i=0; i<newReceivers.size(); i++) {
12673                         ResolveInfo ri = newReceivers.get(i);
12674                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
12675                             ComponentName cn = new ComponentName(
12676                                     ri.activityInfo.packageName, ri.activityInfo.name);
12677                             if (singleUserReceivers == null) {
12678                                 singleUserReceivers = new HashSet<ComponentName>();
12679                             }
12680                             if (!singleUserReceivers.contains(cn)) {
12681                                 singleUserReceivers.add(cn);
12682                                 receivers.add(ri);
12683                             }
12684                         } else {
12685                             receivers.add(ri);
12686                         }
12687                     }
12688                 }
12689             }
12690         } catch (RemoteException ex) {
12691             // pm is in same process, this will never happen.
12692         }
12693         if (receivers != null && broadcastAllowList != null) {
12694             for (int i = receivers.size() - 1; i >= 0; i--) {
12695                 final int receiverAppId = UserHandle.getAppId(
12696                         receivers.get(i).activityInfo.applicationInfo.uid);
12697                 if (receiverAppId >= Process.FIRST_APPLICATION_UID
12698                         && Arrays.binarySearch(broadcastAllowList, receiverAppId) < 0) {
12699                     receivers.remove(i);
12700                 }
12701             }
12702         }
12703         return receivers;
12704     }
12705 
checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)12706     private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp,
12707             String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) {
12708         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
12709             // Don't yell about broadcasts sent via shell
12710             return;
12711         }
12712 
12713         final String action = intent.getAction();
12714         if (isProtectedBroadcast
12715                 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
12716                 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
12717                 || Intent.ACTION_MEDIA_BUTTON.equals(action)
12718                 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
12719                 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
12720                 || Intent.ACTION_MASTER_CLEAR.equals(action)
12721                 || Intent.ACTION_FACTORY_RESET.equals(action)
12722                 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
12723                 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
12724                 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action)
12725                 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action)
12726                 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action)
12727                 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) {
12728             // Broadcast is either protected, or it's a public action that
12729             // we've relaxed, so it's fine for system internals to send.
12730             return;
12731         }
12732 
12733         // This broadcast may be a problem...  but there are often system components that
12734         // want to send an internal broadcast to themselves, which is annoying to have to
12735         // explicitly list each action as a protected broadcast, so we will check for that
12736         // one safe case and allow it: an explicit broadcast, only being received by something
12737         // that has protected itself.
12738         if (intent.getPackage() != null || intent.getComponent() != null) {
12739             if (receivers == null || receivers.size() == 0) {
12740                 // Intent is explicit and there's no receivers.
12741                 // This happens, e.g. , when a system component sends a broadcast to
12742                 // its own runtime receiver, and there's no manifest receivers for it,
12743                 // because this method is called twice for each broadcast,
12744                 // for runtime receivers and manifest receivers and the later check would find
12745                 // no receivers.
12746                 return;
12747             }
12748             boolean allProtected = true;
12749             for (int i = receivers.size()-1; i >= 0; i--) {
12750                 Object target = receivers.get(i);
12751                 if (target instanceof ResolveInfo) {
12752                     ResolveInfo ri = (ResolveInfo)target;
12753                     if (ri.activityInfo.exported && ri.activityInfo.permission == null) {
12754                         allProtected = false;
12755                         break;
12756                     }
12757                 } else {
12758                     BroadcastFilter bf = (BroadcastFilter)target;
12759                     if (bf.requiredPermission == null) {
12760                         allProtected = false;
12761                         break;
12762                     }
12763                 }
12764             }
12765             if (allProtected) {
12766                 // All safe!
12767                 return;
12768             }
12769         }
12770 
12771         // The vast majority of broadcasts sent from system internals
12772         // should be protected to avoid security holes, so yell loudly
12773         // to ensure we examine these cases.
12774         if (callerApp != null) {
12775             Log.wtf(TAG, "Sending non-protected broadcast " + action
12776                             + " from system " + callerApp.toShortString() + " pkg " + callerPackage,
12777                     new Throwable());
12778         } else {
12779             Log.wtf(TAG, "Sending non-protected broadcast " + action
12780                             + " from system uid " + UserHandle.formatUid(callingUid)
12781                             + " pkg " + callerPackage,
12782                     new Throwable());
12783         }
12784     }
12785 
12786     @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, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)12787     final int broadcastIntentLocked(ProcessRecord callerApp,
12788             String callerPackage, String callerFeatureId, Intent intent, String resolvedType,
12789             IIntentReceiver resultTo, int resultCode, String resultData,
12790             Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions,
12791             int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid,
12792             int callingUid, int realCallingUid, int realCallingPid, int userId) {
12793         return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent,
12794                 resolvedType, resultTo, resultCode, resultData, resultExtras, requiredPermissions,
12795                 excludedPermissions, appOp, bOptions, ordered, sticky, callingPid, callingUid,
12796                 realCallingUid, realCallingPid, userId, false /* allowBackgroundActivityStarts */,
12797                 null /* tokenNeededForBackgroundActivityStarts */, null /* broadcastAllowList */);
12798     }
12799 
12800     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken, @Nullable int[] broadcastAllowList)12801     final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage,
12802             @Nullable String callerFeatureId, Intent intent, String resolvedType,
12803             IIntentReceiver resultTo, int resultCode, String resultData,
12804             Bundle resultExtras, String[] requiredPermissions,
12805             String[] excludedPermissions, int appOp, Bundle bOptions,
12806             boolean ordered, boolean sticky, int callingPid, int callingUid,
12807             int realCallingUid, int realCallingPid, int userId,
12808             boolean allowBackgroundActivityStarts,
12809             @Nullable IBinder backgroundActivityStartsToken,
12810             @Nullable int[] broadcastAllowList) {
12811         intent = new Intent(intent);
12812 
12813         final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
12814         // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
12815         if (callerInstantApp) {
12816             intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
12817         }
12818 
12819         if (userId == UserHandle.USER_ALL && broadcastAllowList != null) {
12820                 Slog.e(TAG, "broadcastAllowList only applies when sending to individual users. "
12821                         + "Assuming restrictive whitelist.");
12822                 broadcastAllowList = new int[]{};
12823         }
12824 
12825         // By default broadcasts do not go to stopped apps.
12826         intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12827 
12828         // If we have not finished booting, don't allow this to launch new processes.
12829         if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
12830             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12831         }
12832 
12833         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
12834                 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12835                 + " ordered=" + ordered + " userid=" + userId);
12836         if ((resultTo != null) && !ordered) {
12837             Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
12838         }
12839 
12840         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
12841                 ALLOW_NON_FULL, "broadcast", callerPackage);
12842 
12843         // Make sure that the user who is receiving this broadcast or its parent is running.
12844         // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
12845         if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
12846             if ((callingUid != SYSTEM_UID
12847                     || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)
12848                     && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
12849                 Slog.w(TAG, "Skipping broadcast of " + intent
12850                         + ": user " + userId + " and its parent (if any) are stopped");
12851                 return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
12852             }
12853         }
12854 
12855         final String action = intent.getAction();
12856         BroadcastOptions brOptions = null;
12857         if (bOptions != null) {
12858             brOptions = new BroadcastOptions(bOptions);
12859             if (brOptions.getTemporaryAppAllowlistDuration() > 0) {
12860                 // See if the caller is allowed to do this.  Note we are checking against
12861                 // the actual real caller (not whoever provided the operation as say a
12862                 // PendingIntent), because that who is actually supplied the arguments.
12863                 if (checkComponentPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
12864                         realCallingPid, realCallingUid, -1, true)
12865                         != PackageManager.PERMISSION_GRANTED
12866                         && checkComponentPermission(START_ACTIVITIES_FROM_BACKGROUND,
12867                         realCallingPid, realCallingUid, -1, true)
12868                         != PackageManager.PERMISSION_GRANTED
12869                         && checkComponentPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND,
12870                         realCallingPid, realCallingUid, -1, true)
12871                         != PackageManager.PERMISSION_GRANTED) {
12872                     String msg = "Permission Denial: " + intent.getAction()
12873                             + " broadcast from " + callerPackage + " (pid=" + callingPid
12874                             + ", uid=" + callingUid + ")"
12875                             + " requires "
12876                             + CHANGE_DEVICE_IDLE_TEMP_WHITELIST + " or "
12877                             + START_ACTIVITIES_FROM_BACKGROUND + " or "
12878                             + START_FOREGROUND_SERVICES_FROM_BACKGROUND;
12879                     Slog.w(TAG, msg);
12880                     throw new SecurityException(msg);
12881                 }
12882             }
12883             if (brOptions.isDontSendToRestrictedApps()
12884                     && !isUidActiveLOSP(callingUid)
12885                     && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
12886                 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
12887                         + " has background restrictions");
12888                 return ActivityManager.START_CANCELED;
12889             }
12890             if (brOptions.allowsBackgroundActivityStarts()) {
12891                 // See if the caller is allowed to do this.  Note we are checking against
12892                 // the actual real caller (not whoever provided the operation as say a
12893                 // PendingIntent), because that who is actually supplied the arguments.
12894                 if (checkComponentPermission(
12895                         android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
12896                         realCallingPid, realCallingUid, -1, true)
12897                         != PackageManager.PERMISSION_GRANTED) {
12898                     String msg = "Permission Denial: " + intent.getAction()
12899                             + " broadcast from " + callerPackage + " (pid=" + callingPid
12900                             + ", uid=" + callingUid + ")"
12901                             + " requires "
12902                             + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
12903                     Slog.w(TAG, msg);
12904                     throw new SecurityException(msg);
12905                 } else {
12906                     allowBackgroundActivityStarts = true;
12907                     // We set the token to null since if it wasn't for it we'd allow anyway here
12908                     backgroundActivityStartsToken = null;
12909                 }
12910             }
12911         }
12912 
12913         // Verify that protected broadcasts are only being sent by system code,
12914         // and that system code is only sending protected broadcasts.
12915         final boolean isProtectedBroadcast;
12916         try {
12917             isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
12918         } catch (RemoteException e) {
12919             Slog.w(TAG, "Remote exception", e);
12920             return ActivityManager.BROADCAST_SUCCESS;
12921         }
12922 
12923         final boolean isCallerSystem;
12924         switch (UserHandle.getAppId(callingUid)) {
12925             case ROOT_UID:
12926             case SYSTEM_UID:
12927             case PHONE_UID:
12928             case BLUETOOTH_UID:
12929             case NFC_UID:
12930             case SE_UID:
12931             case NETWORK_STACK_UID:
12932                 isCallerSystem = true;
12933                 break;
12934             default:
12935                 isCallerSystem = (callerApp != null) && callerApp.isPersistent();
12936                 break;
12937         }
12938 
12939         // First line security check before anything else: stop non-system apps from
12940         // sending protected broadcasts.
12941         if (!isCallerSystem) {
12942             if (isProtectedBroadcast) {
12943                 String msg = "Permission Denial: not allowed to send broadcast "
12944                         + action + " from pid="
12945                         + callingPid + ", uid=" + callingUid;
12946                 Slog.w(TAG, msg);
12947                 throw new SecurityException(msg);
12948 
12949             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
12950                     || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
12951                 // Special case for compatibility: we don't want apps to send this,
12952                 // but historically it has not been protected and apps may be using it
12953                 // to poke their own app widget.  So, instead of making it protected,
12954                 // just limit it to the caller.
12955                 if (callerPackage == null) {
12956                     String msg = "Permission Denial: not allowed to send broadcast "
12957                             + action + " from unknown caller.";
12958                     Slog.w(TAG, msg);
12959                     throw new SecurityException(msg);
12960                 } else if (intent.getComponent() != null) {
12961                     // They are good enough to send to an explicit component...  verify
12962                     // it is being sent to the calling app.
12963                     if (!intent.getComponent().getPackageName().equals(
12964                             callerPackage)) {
12965                         String msg = "Permission Denial: not allowed to send broadcast "
12966                                 + action + " to "
12967                                 + intent.getComponent().getPackageName() + " from "
12968                                 + callerPackage;
12969                         Slog.w(TAG, msg);
12970                         throw new SecurityException(msg);
12971                     }
12972                 } else {
12973                     // Limit broadcast to their own package.
12974                     intent.setPackage(callerPackage);
12975                 }
12976             }
12977         }
12978 
12979         boolean timeoutExempt = false;
12980 
12981         if (action != null) {
12982             if (getBackgroundLaunchBroadcasts().contains(action)) {
12983                 if (DEBUG_BACKGROUND_CHECK) {
12984                     Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
12985                 }
12986                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
12987             }
12988 
12989             switch (action) {
12990                 case Intent.ACTION_UID_REMOVED:
12991                 case Intent.ACTION_PACKAGE_REMOVED:
12992                 case Intent.ACTION_PACKAGE_CHANGED:
12993                 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
12994                 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
12995                 case Intent.ACTION_PACKAGES_SUSPENDED:
12996                 case Intent.ACTION_PACKAGES_UNSUSPENDED:
12997                     // Handle special intents: if this broadcast is from the package
12998                     // manager about a package being removed, we need to remove all of
12999                     // its activities from the history stack.
13000                     if (checkComponentPermission(
13001                             android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
13002                             callingPid, callingUid, -1, true)
13003                             != PackageManager.PERMISSION_GRANTED) {
13004                         String msg = "Permission Denial: " + intent.getAction()
13005                                 + " broadcast from " + callerPackage + " (pid=" + callingPid
13006                                 + ", uid=" + callingUid + ")"
13007                                 + " requires "
13008                                 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
13009                         Slog.w(TAG, msg);
13010                         throw new SecurityException(msg);
13011                     }
13012                     switch (action) {
13013                         case Intent.ACTION_UID_REMOVED:
13014                             final int uid = getUidFromIntent(intent);
13015                             if (uid >= 0) {
13016                                 mBatteryStatsService.removeUid(uid);
13017                                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
13018                                     mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
13019                                             intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
13020                                 } else {
13021                                     mAppOpsService.uidRemoved(uid);
13022                                 }
13023                             }
13024                             break;
13025                         case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
13026                             // If resources are unavailable just force stop all those packages
13027                             // and flush the attribute cache as well.
13028                             String list[] =
13029                                     intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
13030                             if (list != null && list.length > 0) {
13031                                 for (int i = 0; i < list.length; i++) {
13032                                     forceStopPackageLocked(list[i], -1, false, true, true,
13033                                             false, false, userId, "storage unmount");
13034                                 }
13035                                 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
13036                                 sendPackageBroadcastLocked(
13037                                         ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
13038                                         list, userId);
13039                             }
13040                             break;
13041                         case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
13042                             mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
13043                             break;
13044                         case Intent.ACTION_PACKAGE_REMOVED:
13045                         case Intent.ACTION_PACKAGE_CHANGED:
13046                             Uri data = intent.getData();
13047                             String ssp;
13048                             if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
13049                                 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
13050                                 final boolean replacing =
13051                                         intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
13052                                 final boolean killProcess =
13053                                         !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
13054                                 final boolean fullUninstall = removed && !replacing;
13055                                 if (removed) {
13056                                     if (killProcess) {
13057                                         forceStopPackageLocked(ssp, UserHandle.getAppId(
13058                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
13059                                                 false, true, true, false, fullUninstall, userId,
13060                                                 removed ? "pkg removed" : "pkg changed");
13061                                     } else {
13062                                         // Kill any app zygotes always, since they can't fork new
13063                                         // processes with references to the old code
13064                                         forceStopAppZygoteLocked(ssp, UserHandle.getAppId(
13065                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
13066                                                 userId);
13067                                     }
13068                                     final int cmd = killProcess
13069                                             ? ApplicationThreadConstants.PACKAGE_REMOVED
13070                                             : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
13071                                     sendPackageBroadcastLocked(cmd,
13072                                             new String[] {ssp}, userId);
13073                                     if (fullUninstall) {
13074                                         mAppOpsService.packageRemoved(
13075                                                 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
13076 
13077                                         // Remove all permissions granted from/to this package
13078                                         mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
13079                                                 true, false);
13080 
13081                                         mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
13082 
13083                                         mServices.forceStopPackageLocked(ssp, userId);
13084                                         mAtmInternal.onPackageUninstalled(ssp);
13085                                         mBatteryStatsService.notePackageUninstalled(ssp);
13086                                     }
13087                                 } else {
13088                                     if (killProcess) {
13089                                         final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
13090                                                 -1);
13091                                         synchronized (mProcLock) {
13092                                             mProcessList.killPackageProcessesLSP(ssp,
13093                                                     UserHandle.getAppId(extraUid),
13094                                                     userId, ProcessList.INVALID_ADJ,
13095                                                     ApplicationExitInfo.REASON_USER_REQUESTED,
13096                                                     ApplicationExitInfo.SUBREASON_UNKNOWN,
13097                                                     "change " + ssp);
13098                                         }
13099                                     }
13100                                     cleanupDisabledPackageComponentsLocked(ssp, userId,
13101                                             intent.getStringArrayExtra(
13102                                                     Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
13103                                     mServices.schedulePendingServiceStartLocked(ssp, userId);
13104                                 }
13105                             }
13106                             break;
13107                         case Intent.ACTION_PACKAGES_SUSPENDED:
13108                         case Intent.ACTION_PACKAGES_UNSUSPENDED:
13109                             final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
13110                                     intent.getAction());
13111                             final String[] packageNames = intent.getStringArrayExtra(
13112                                     Intent.EXTRA_CHANGED_PACKAGE_LIST);
13113                             final int userIdExtra = intent.getIntExtra(
13114                                     Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
13115 
13116                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
13117                                     userIdExtra);
13118                             break;
13119                     }
13120                     break;
13121                 case Intent.ACTION_PACKAGE_REPLACED:
13122                 {
13123                     final Uri data = intent.getData();
13124                     final String ssp;
13125                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
13126                         ApplicationInfo aInfo = null;
13127                         try {
13128                             aInfo = AppGlobals.getPackageManager()
13129                                     .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
13130                         } catch (RemoteException ignore) {}
13131                         if (aInfo == null) {
13132                             Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
13133                                     + " ssp=" + ssp + " data=" + data);
13134                             return ActivityManager.BROADCAST_SUCCESS;
13135                         }
13136                         updateAssociationForApp(aInfo);
13137                         mAtmInternal.onPackageReplaced(aInfo);
13138                         mServices.updateServiceApplicationInfoLocked(aInfo);
13139                         sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
13140                                 new String[] {ssp}, userId);
13141                     }
13142                     break;
13143                 }
13144                 case Intent.ACTION_PACKAGE_ADDED:
13145                 {
13146                     // Special case for adding a package: by default turn on compatibility mode.
13147                     Uri data = intent.getData();
13148                     String ssp;
13149                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
13150                         final boolean replacing =
13151                                 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
13152                         mAtmInternal.onPackageAdded(ssp, replacing);
13153 
13154                         try {
13155                             ApplicationInfo ai = AppGlobals.getPackageManager().
13156                                     getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
13157                             mBatteryStatsService.notePackageInstalled(ssp,
13158                                     ai != null ? ai.longVersionCode : 0);
13159                         } catch (RemoteException e) {
13160                         }
13161                     }
13162                     break;
13163                 }
13164                 case Intent.ACTION_PACKAGE_DATA_CLEARED:
13165                 {
13166                     Uri data = intent.getData();
13167                     String ssp;
13168                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
13169                         mAtmInternal.onPackageDataCleared(ssp);
13170                     }
13171                     break;
13172                 }
13173                 case Intent.ACTION_TIMEZONE_CHANGED:
13174                     // If this is the time zone changed action, queue up a message that will reset
13175                     // the timezone of all currently running processes. This message will get
13176                     // queued up before the broadcast happens.
13177                     mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
13178                     break;
13179                 case Intent.ACTION_TIME_CHANGED:
13180                     // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
13181                     // the tri-state value it may contain and "unknown".
13182                     // For convenience we re-use the Intent extra values.
13183                     final int NO_EXTRA_VALUE_FOUND = -1;
13184                     final int timeFormatPreferenceMsgValue = intent.getIntExtra(
13185                             Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
13186                             NO_EXTRA_VALUE_FOUND /* defaultValue */);
13187                     // Only send a message if the time preference is available.
13188                     if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
13189                         Message updateTimePreferenceMsg =
13190                                 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
13191                                         timeFormatPreferenceMsgValue, 0);
13192                         mHandler.sendMessage(updateTimePreferenceMsg);
13193                     }
13194                     mBatteryStatsService.noteCurrentTimeChanged();
13195                     break;
13196                 case ConnectivityManager.ACTION_CLEAR_DNS_CACHE:
13197                     mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
13198                     break;
13199                 case Proxy.PROXY_CHANGE_ACTION:
13200                     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
13201                     break;
13202                 case android.hardware.Camera.ACTION_NEW_PICTURE:
13203                 case android.hardware.Camera.ACTION_NEW_VIDEO:
13204                     // In N we just turned these off; in O we are turing them back on partly,
13205                     // only for registered receivers.  This will still address the main problem
13206                     // (a spam of apps waking up when a picture is taken putting significant
13207                     // memory pressure on the system at a bad point), while still allowing apps
13208                     // that are already actively running to know about this happening.
13209                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13210                     break;
13211                 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
13212                     mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
13213                     break;
13214                 case "com.android.launcher.action.INSTALL_SHORTCUT":
13215                     // As of O, we no longer support this broadcasts, even for pre-O apps.
13216                     // Apps should now be using ShortcutManager.pinRequestShortcut().
13217                     Log.w(TAG, "Broadcast " + action
13218                             + " no longer supported. It will not be delivered.");
13219                     return ActivityManager.BROADCAST_SUCCESS;
13220                 case Intent.ACTION_PRE_BOOT_COMPLETED:
13221                     timeoutExempt = true;
13222                     break;
13223                 case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
13224                     if (!mAtmInternal.checkCanCloseSystemDialogs(callingPid, callingUid,
13225                             callerPackage)) {
13226                         // Returning success seems to be the pattern here
13227                         return ActivityManager.BROADCAST_SUCCESS;
13228                     }
13229                     break;
13230             }
13231 
13232             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
13233                     Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
13234                     Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
13235                 final int uid = getUidFromIntent(intent);
13236                 if (uid != -1) {
13237                     final UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
13238                     if (uidRec != null) {
13239                         uidRec.updateHasInternetPermission();
13240                     }
13241                 }
13242             }
13243         }
13244 
13245         // Add to the sticky list if requested.
13246         if (sticky) {
13247             if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
13248                     callingPid, callingUid)
13249                     != PackageManager.PERMISSION_GRANTED) {
13250                 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
13251                         + callingPid + ", uid=" + callingUid
13252                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
13253                 Slog.w(TAG, msg);
13254                 throw new SecurityException(msg);
13255             }
13256             if (requiredPermissions != null && requiredPermissions.length > 0) {
13257                 Slog.w(TAG, "Can't broadcast sticky intent " + intent
13258                         + " and enforce permissions " + Arrays.toString(requiredPermissions));
13259                 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
13260             }
13261             if (intent.getComponent() != null) {
13262                 throw new SecurityException(
13263                         "Sticky broadcasts can't target a specific component");
13264             }
13265             // We use userId directly here, since the "all" target is maintained
13266             // as a separate set of sticky broadcasts.
13267             if (userId != UserHandle.USER_ALL) {
13268                 // But first, if this is not a broadcast to all users, then
13269                 // make sure it doesn't conflict with an existing broadcast to
13270                 // all users.
13271                 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
13272                         UserHandle.USER_ALL);
13273                 if (stickies != null) {
13274                     ArrayList<Intent> list = stickies.get(intent.getAction());
13275                     if (list != null) {
13276                         int N = list.size();
13277                         int i;
13278                         for (i=0; i<N; i++) {
13279                             if (intent.filterEquals(list.get(i))) {
13280                                 throw new IllegalArgumentException(
13281                                         "Sticky broadcast " + intent + " for user "
13282                                         + userId + " conflicts with existing global broadcast");
13283                             }
13284                         }
13285                     }
13286                 }
13287             }
13288             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
13289             if (stickies == null) {
13290                 stickies = new ArrayMap<>();
13291                 mStickyBroadcasts.put(userId, stickies);
13292             }
13293             ArrayList<Intent> list = stickies.get(intent.getAction());
13294             if (list == null) {
13295                 list = new ArrayList<>();
13296                 stickies.put(intent.getAction(), list);
13297             }
13298             final int stickiesCount = list.size();
13299             int i;
13300             for (i = 0; i < stickiesCount; i++) {
13301                 if (intent.filterEquals(list.get(i))) {
13302                     // This sticky already exists, replace it.
13303                     list.set(i, new Intent(intent));
13304                     break;
13305                 }
13306             }
13307             if (i >= stickiesCount) {
13308                 list.add(new Intent(intent));
13309             }
13310         }
13311 
13312         int[] users;
13313         if (userId == UserHandle.USER_ALL) {
13314             // Caller wants broadcast to go to all started users.
13315             users = mUserController.getStartedUserArray();
13316         } else {
13317             // Caller wants broadcast to go to one specific user.
13318             users = new int[] {userId};
13319         }
13320 
13321         // Figure out who all will receive this broadcast.
13322         List receivers = null;
13323         List<BroadcastFilter> registeredReceivers = null;
13324         // Need to resolve the intent to interested receivers...
13325         if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
13326                  == 0) {
13327             receivers = collectReceiverComponents(
13328                     intent, resolvedType, callingUid, users, broadcastAllowList);
13329         }
13330         if (intent.getComponent() == null) {
13331             if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
13332                 // Query one target user at a time, excluding shell-restricted users
13333                 for (int i = 0; i < users.length; i++) {
13334                     if (mUserController.hasUserRestriction(
13335                             UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
13336                         continue;
13337                     }
13338                     List<BroadcastFilter> registeredReceiversForUser =
13339                             mReceiverResolver.queryIntent(intent,
13340                                     resolvedType, false /*defaultOnly*/, users[i]);
13341                     if (registeredReceivers == null) {
13342                         registeredReceivers = registeredReceiversForUser;
13343                     } else if (registeredReceiversForUser != null) {
13344                         registeredReceivers.addAll(registeredReceiversForUser);
13345                     }
13346                 }
13347             } else {
13348                 registeredReceivers = mReceiverResolver.queryIntent(intent,
13349                         resolvedType, false /*defaultOnly*/, userId);
13350             }
13351         }
13352 
13353         final boolean replacePending =
13354                 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
13355 
13356         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
13357                 + " replacePending=" + replacePending);
13358         if (registeredReceivers != null && broadcastAllowList != null) {
13359             // if a uid whitelist was provided, remove anything in the application space that wasn't
13360             // in it.
13361             for (int i = registeredReceivers.size() - 1; i >= 0; i--) {
13362                 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid);
13363                 if (owningAppId >= Process.FIRST_APPLICATION_UID
13364                         && Arrays.binarySearch(broadcastAllowList, owningAppId) < 0) {
13365                     registeredReceivers.remove(i);
13366                 }
13367             }
13368         }
13369 
13370         int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
13371         if (!ordered && NR > 0) {
13372             // If we are not serializing this broadcast, then send the
13373             // registered receivers separately so they don't wait for the
13374             // components to be launched.
13375             if (isCallerSystem) {
13376                 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
13377                         isProtectedBroadcast, registeredReceivers);
13378             }
13379             final BroadcastQueue queue = broadcastQueueForIntent(intent);
13380             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
13381                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
13382                     requiredPermissions, excludedPermissions, appOp, brOptions, registeredReceivers,
13383                     resultTo, resultCode, resultData, resultExtras, ordered, sticky, false, userId,
13384                     allowBackgroundActivityStarts, backgroundActivityStartsToken,
13385                     timeoutExempt);
13386             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
13387             final boolean replaced = replacePending
13388                     && (queue.replaceParallelBroadcastLocked(r) != null);
13389             // Note: We assume resultTo is null for non-ordered broadcasts.
13390             if (!replaced) {
13391                 queue.enqueueParallelBroadcastLocked(r);
13392                 queue.scheduleBroadcastsLocked();
13393             }
13394             registeredReceivers = null;
13395             NR = 0;
13396         }
13397 
13398         // Merge into one list.
13399         int ir = 0;
13400         if (receivers != null) {
13401             // A special case for PACKAGE_ADDED: do not allow the package
13402             // being added to see this broadcast.  This prevents them from
13403             // using this as a back door to get run as soon as they are
13404             // installed.  Maybe in the future we want to have a special install
13405             // broadcast or such for apps, but we'd like to deliberately make
13406             // this decision.
13407             String skipPackages[] = null;
13408             if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13409                     || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13410                     || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
13411                 Uri data = intent.getData();
13412                 if (data != null) {
13413                     String pkgName = data.getSchemeSpecificPart();
13414                     if (pkgName != null) {
13415                         skipPackages = new String[] { pkgName };
13416                     }
13417                 }
13418             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
13419                 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
13420             }
13421             if (skipPackages != null && (skipPackages.length > 0)) {
13422                 for (String skipPackage : skipPackages) {
13423                     if (skipPackage != null) {
13424                         int NT = receivers.size();
13425                         for (int it=0; it<NT; it++) {
13426                             ResolveInfo curt = (ResolveInfo)receivers.get(it);
13427                             if (curt.activityInfo.packageName.equals(skipPackage)) {
13428                                 receivers.remove(it);
13429                                 it--;
13430                                 NT--;
13431                             }
13432                         }
13433                     }
13434                 }
13435             }
13436 
13437             int NT = receivers != null ? receivers.size() : 0;
13438             int it = 0;
13439             ResolveInfo curt = null;
13440             BroadcastFilter curr = null;
13441             while (it < NT && ir < NR) {
13442                 if (curt == null) {
13443                     curt = (ResolveInfo)receivers.get(it);
13444                 }
13445                 if (curr == null) {
13446                     curr = registeredReceivers.get(ir);
13447                 }
13448                 if (curr.getPriority() >= curt.priority) {
13449                     // Insert this broadcast record into the final list.
13450                     receivers.add(it, curr);
13451                     ir++;
13452                     curr = null;
13453                     it++;
13454                     NT++;
13455                 } else {
13456                     // Skip to the next ResolveInfo in the final list.
13457                     it++;
13458                     curt = null;
13459                 }
13460             }
13461         }
13462         while (ir < NR) {
13463             if (receivers == null) {
13464                 receivers = new ArrayList();
13465             }
13466             receivers.add(registeredReceivers.get(ir));
13467             ir++;
13468         }
13469 
13470         if (isCallerSystem) {
13471             checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
13472                     isProtectedBroadcast, receivers);
13473         }
13474 
13475         if ((receivers != null && receivers.size() > 0)
13476                 || resultTo != null) {
13477             BroadcastQueue queue = broadcastQueueForIntent(intent);
13478             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
13479                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
13480                     requiredPermissions, excludedPermissions, appOp, brOptions,
13481                     receivers, resultTo, resultCode, resultData, resultExtras,
13482                     ordered, sticky, false, userId, allowBackgroundActivityStarts,
13483                     backgroundActivityStartsToken, timeoutExempt);
13484 
13485             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
13486 
13487             final BroadcastRecord oldRecord =
13488                     replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
13489             if (oldRecord != null) {
13490                 // Replaced, fire the result-to receiver.
13491                 if (oldRecord.resultTo != null) {
13492                     final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
13493                     try {
13494                         oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
13495                                 oldRecord.intent,
13496                                 Activity.RESULT_CANCELED, null, null,
13497                                 false, false, oldRecord.userId);
13498                     } catch (RemoteException e) {
13499                         Slog.w(TAG, "Failure ["
13500                                 + queue.mQueueName + "] sending broadcast result of "
13501                                 + intent, e);
13502 
13503                     }
13504                 }
13505             } else {
13506                 queue.enqueueOrderedBroadcastLocked(r);
13507                 queue.scheduleBroadcastsLocked();
13508             }
13509         } else {
13510             // There was nobody interested in the broadcast, but we still want to record
13511             // that it happened.
13512             if (intent.getComponent() == null && intent.getPackage() == null
13513                     && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13514                 // This was an implicit broadcast... let's record it for posterity.
13515                 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
13516             }
13517         }
13518 
13519         return ActivityManager.BROADCAST_SUCCESS;
13520     }
13521 
13522     /**
13523      * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1
13524      */
getUidFromIntent(Intent intent)13525     private int getUidFromIntent(Intent intent) {
13526         if (intent == null) {
13527             return -1;
13528         }
13529         final Bundle intentExtras = intent.getExtras();
13530         return intent.hasExtra(Intent.EXTRA_UID)
13531                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
13532     }
13533 
rotateBroadcastStatsIfNeededLocked()13534     final void rotateBroadcastStatsIfNeededLocked() {
13535         final long now = SystemClock.elapsedRealtime();
13536         if (mCurBroadcastStats == null ||
13537                 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) {
13538             mLastBroadcastStats = mCurBroadcastStats;
13539             if (mLastBroadcastStats != null) {
13540                 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime();
13541                 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis();
13542             }
13543             mCurBroadcastStats = new BroadcastStats();
13544         }
13545     }
13546 
addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)13547     final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount,
13548             int skipCount, long dispatchTime) {
13549         rotateBroadcastStatsIfNeededLocked();
13550         mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime);
13551     }
13552 
addBackgroundCheckViolationLocked(String action, String targetPackage)13553     final void addBackgroundCheckViolationLocked(String action, String targetPackage) {
13554         rotateBroadcastStatsIfNeededLocked();
13555         mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage);
13556     }
13557 
verifyBroadcastLocked(Intent intent)13558     final Intent verifyBroadcastLocked(Intent intent) {
13559         // Refuse possible leaked file descriptors
13560         if (intent != null && intent.hasFileDescriptors() == true) {
13561             throw new IllegalArgumentException("File descriptors passed in Intent");
13562         }
13563 
13564         int flags = intent.getFlags();
13565 
13566         if (!mProcessesReady) {
13567             // if the caller really truly claims to know what they're doing, go
13568             // ahead and allow the broadcast without launching any receivers
13569             if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13570                 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
13571             } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13572                 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13573                         + " before boot completion");
13574                 throw new IllegalStateException("Cannot broadcast before boot completed");
13575             }
13576         }
13577 
13578         if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13579             throw new IllegalArgumentException(
13580                     "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13581         }
13582 
13583         if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
13584             switch (Binder.getCallingUid()) {
13585                 case ROOT_UID:
13586                 case SHELL_UID:
13587                     break;
13588                 default:
13589                     Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
13590                             + Binder.getCallingUid());
13591                     intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
13592                     break;
13593             }
13594         }
13595 
13596         return intent;
13597     }
13598 
13599     /**
13600      * @deprecated Use {@link #broadcastIntentWithFeature}
13601      */
13602     @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)13603     public final int broadcastIntent(IApplicationThread caller,
13604             Intent intent, String resolvedType, IIntentReceiver resultTo,
13605             int resultCode, String resultData, Bundle resultExtras,
13606             String[] requiredPermissions, int appOp, Bundle bOptions,
13607             boolean serialized, boolean sticky, int userId) {
13608         return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode,
13609                 resultData, resultExtras, requiredPermissions, null, appOp, bOptions, serialized,
13610                 sticky, userId);
13611     }
13612 
broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, String[] excludedPermissions, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)13613     public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId,
13614             Intent intent, String resolvedType, IIntentReceiver resultTo,
13615             int resultCode, String resultData, Bundle resultExtras,
13616             String[] requiredPermissions, String[] excludedPermissions, int appOp, Bundle bOptions,
13617             boolean serialized, boolean sticky, int userId) {
13618         enforceNotIsolatedCaller("broadcastIntent");
13619         synchronized(this) {
13620             intent = verifyBroadcastLocked(intent);
13621 
13622             final ProcessRecord callerApp = getRecordForAppLOSP(caller);
13623             final int callingPid = Binder.getCallingPid();
13624             final int callingUid = Binder.getCallingUid();
13625 
13626             final long origId = Binder.clearCallingIdentity();
13627             try {
13628                 return broadcastIntentLocked(callerApp,
13629                         callerApp != null ? callerApp.info.packageName : null, callingFeatureId,
13630                         intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
13631                         requiredPermissions, excludedPermissions, appOp, bOptions, serialized,
13632                         sticky, callingPid, callingUid, callingUid, callingPid, userId);
13633             } finally {
13634                 Binder.restoreCallingIdentity(origId);
13635             }
13636         }
13637     }
13638 
broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)13639     int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
13640             int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
13641             IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras,
13642             String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky,
13643             int userId, boolean allowBackgroundActivityStarts,
13644             @Nullable IBinder backgroundActivityStartsToken) {
13645         synchronized(this) {
13646             intent = verifyBroadcastLocked(intent);
13647 
13648             final long origId = Binder.clearCallingIdentity();
13649             String[] requiredPermissions = requiredPermission == null ? null
13650                     : new String[] {requiredPermission};
13651             try {
13652                 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType,
13653                         resultTo, resultCode, resultData, resultExtras, requiredPermissions, null,
13654                         OP_NONE, bOptions, serialized, sticky, -1, uid, realCallingUid,
13655                         realCallingPid, userId, allowBackgroundActivityStarts,
13656                         backgroundActivityStartsToken,
13657                         null /* broadcastAllowList */);
13658             } finally {
13659                 Binder.restoreCallingIdentity(origId);
13660             }
13661         }
13662     }
13663 
unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)13664     public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
13665         // Refuse possible leaked file descriptors
13666         if (intent != null && intent.hasFileDescriptors() == true) {
13667             throw new IllegalArgumentException("File descriptors passed in Intent");
13668         }
13669 
13670         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
13671                 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
13672 
13673         synchronized(this) {
13674             if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13675                     != PackageManager.PERMISSION_GRANTED) {
13676                 String msg = "Permission Denial: unbroadcastIntent() from pid="
13677                         + Binder.getCallingPid()
13678                         + ", uid=" + Binder.getCallingUid()
13679                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
13680                 Slog.w(TAG, msg);
13681                 throw new SecurityException(msg);
13682             }
13683             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
13684             if (stickies != null) {
13685                 ArrayList<Intent> list = stickies.get(intent.getAction());
13686                 if (list != null) {
13687                     int N = list.size();
13688                     int i;
13689                     for (i=0; i<N; i++) {
13690                         if (intent.filterEquals(list.get(i))) {
13691                             list.remove(i);
13692                             break;
13693                         }
13694                     }
13695                     if (list.size() <= 0) {
13696                         stickies.remove(intent.getAction());
13697                     }
13698                 }
13699                 if (stickies.size() <= 0) {
13700                     mStickyBroadcasts.remove(userId);
13701                 }
13702             }
13703         }
13704     }
13705 
backgroundServicesFinishedLocked(int userId)13706     void backgroundServicesFinishedLocked(int userId) {
13707         for (BroadcastQueue queue : mBroadcastQueues) {
13708             queue.backgroundServicesFinishedLocked(userId);
13709         }
13710     }
13711 
finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)13712     public void finishReceiver(IBinder who, int resultCode, String resultData,
13713             Bundle resultExtras, boolean resultAbort, int flags) {
13714         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who);
13715 
13716         // Refuse possible leaked file descriptors
13717         if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13718             throw new IllegalArgumentException("File descriptors passed in Bundle");
13719         }
13720 
13721         final long origId = Binder.clearCallingIdentity();
13722         try {
13723             boolean doNext = false;
13724             BroadcastRecord r;
13725             BroadcastQueue queue;
13726 
13727             synchronized(this) {
13728                 if (isOnOffloadQueue(flags)) {
13729                     queue = mOffloadBroadcastQueue;
13730                 } else {
13731                     queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0
13732                             ? mFgBroadcastQueue : mBgBroadcastQueue;
13733                 }
13734 
13735                 r = queue.getMatchingOrderedReceiver(who);
13736                 if (r != null) {
13737                     doNext = r.queue.finishReceiverLocked(r, resultCode,
13738                         resultData, resultExtras, resultAbort, true);
13739                 }
13740                 if (doNext) {
13741                     r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true);
13742                 }
13743                 // updateOomAdjLocked() will be done here
13744                 trimApplicationsLocked(false, OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
13745             }
13746 
13747         } finally {
13748             Binder.restoreCallingIdentity(origId);
13749         }
13750     }
13751 
13752     // =========================================================
13753     // INSTRUMENTATION
13754     // =========================================================
13755 
startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)13756     public boolean startInstrumentation(ComponentName className,
13757             String profileFile, int flags, Bundle arguments,
13758             IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
13759             int userId, String abiOverride) {
13760         enforceNotIsolatedCaller("startInstrumentation");
13761         final int callingUid = Binder.getCallingUid();
13762         final int callingPid = Binder.getCallingPid();
13763         userId = mUserController.handleIncomingUser(callingPid, callingUid,
13764                 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
13765         // Refuse possible leaked file descriptors
13766         if (arguments != null && arguments.hasFileDescriptors()) {
13767             throw new IllegalArgumentException("File descriptors passed in Bundle");
13768         }
13769 
13770         synchronized(this) {
13771             InstrumentationInfo ii = null;
13772             ApplicationInfo ai = null;
13773 
13774             boolean noRestart = (flags & INSTR_FLAG_NO_RESTART) != 0;
13775 
13776             try {
13777                 ii = mContext.getPackageManager().getInstrumentationInfo(
13778                         className, STOCK_PM_FLAGS);
13779                 ai = AppGlobals.getPackageManager().getApplicationInfo(
13780                         ii.targetPackage, STOCK_PM_FLAGS, userId);
13781             } catch (PackageManager.NameNotFoundException e) {
13782             } catch (RemoteException e) {
13783             }
13784             if (ii == null) {
13785                 reportStartInstrumentationFailureLocked(watcher, className,
13786                         "Unable to find instrumentation info for: " + className);
13787                 return false;
13788             }
13789             if (ai == null) {
13790                 reportStartInstrumentationFailureLocked(watcher, className,
13791                         "Unable to find instrumentation target package: " + ii.targetPackage);
13792                 return false;
13793             }
13794 
13795             if (ii.targetPackage.equals("android")) {
13796                 if (!noRestart) {
13797                     reportStartInstrumentationFailureLocked(watcher, className,
13798                             "Cannot instrument system server without 'no-restart'");
13799                     return false;
13800                 }
13801             } else if (!ai.hasCode()) {
13802                 reportStartInstrumentationFailureLocked(watcher, className,
13803                         "Instrumentation target has no code: " + ii.targetPackage);
13804                 return false;
13805             }
13806 
13807             if (!Build.IS_DEBUGGABLE) {
13808                 int match = mContext.getPackageManager().checkSignatures(
13809                         ii.targetPackage, ii.packageName);
13810                 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13811                     String msg = "Permission Denial: starting instrumentation "
13812                             + className + " from pid="
13813                             + Binder.getCallingPid()
13814                             + ", uid=" + Binder.getCallingPid()
13815                             + " not allowed because package " + ii.packageName
13816                             + " does not have a signature matching the target "
13817                             + ii.targetPackage;
13818                     reportStartInstrumentationFailureLocked(watcher, className, msg);
13819                     throw new SecurityException(msg);
13820                 }
13821             }
13822 
13823             ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
13824             activeInstr.mClass = className;
13825             String defProcess = ai.processName;;
13826             if (ii.targetProcesses == null) {
13827                 activeInstr.mTargetProcesses = new String[]{ai.processName};
13828             } else if (ii.targetProcesses.equals("*")) {
13829                 activeInstr.mTargetProcesses = new String[0];
13830             } else {
13831                 activeInstr.mTargetProcesses = ii.targetProcesses.split(",");
13832                 defProcess = activeInstr.mTargetProcesses[0];
13833             }
13834             activeInstr.mTargetInfo = ai;
13835             activeInstr.mProfileFile = profileFile;
13836             activeInstr.mArguments = arguments;
13837             activeInstr.mWatcher = watcher;
13838             activeInstr.mUiAutomationConnection = uiAutomationConnection;
13839             activeInstr.mResultClass = className;
13840             activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
13841                     START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
13842                             == PackageManager.PERMISSION_GRANTED;
13843             activeInstr.mHasBackgroundForegroundServiceStartsPermission = checkPermission(
13844                     START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid, callingUid)
13845                             == PackageManager.PERMISSION_GRANTED;
13846             activeInstr.mNoRestart = noRestart;
13847             boolean disableHiddenApiChecks = ai.usesNonSdkApi()
13848                     || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
13849             boolean disableTestApiChecks = disableHiddenApiChecks
13850                     || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0;
13851 
13852             if (disableHiddenApiChecks || disableTestApiChecks) {
13853                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
13854                         "disable hidden API checks");
13855             }
13856 
13857             final long origId = Binder.clearCallingIdentity();
13858 
13859             ProcessRecord app;
13860             synchronized (mProcLock) {
13861                 if (noRestart) {
13862                     app = getProcessRecordLocked(ai.processName, ai.uid);
13863                 } else {
13864                     // Instrumentation can kill and relaunch even persistent processes
13865                     forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false,
13866                             userId, "start instr");
13867                     // Inform usage stats to make the target package active
13868                     if (mUsageStatsService != null) {
13869                         mUsageStatsService.reportEvent(ii.targetPackage, userId,
13870                                 UsageEvents.Event.SYSTEM_INTERACTION);
13871                     }
13872                     app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks,
13873                             disableTestApiChecks, abiOverride, ZYGOTE_POLICY_FLAG_EMPTY);
13874                 }
13875 
13876                 app.setActiveInstrumentation(activeInstr);
13877                 activeInstr.mFinished = false;
13878                 activeInstr.mSourceUid = callingUid;
13879                 activeInstr.mRunningProcesses.add(app);
13880                 if (!mActiveInstrumentation.contains(activeInstr)) {
13881                     mActiveInstrumentation.add(activeInstr);
13882                 }
13883             }
13884 
13885             if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) {
13886                 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with
13887                 // --no-isolated-storage flag.
13888                 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid,
13889                         ii.packageName, AppOpsManager.MODE_ALLOWED);
13890             }
13891             Binder.restoreCallingIdentity(origId);
13892 
13893             if (noRestart) {
13894                 instrumentWithoutRestart(activeInstr, ai);
13895             }
13896         }
13897 
13898         return true;
13899     }
13900 
instrumentWithoutRestart(ActiveInstrumentation activeInstr, ApplicationInfo targetInfo)13901     private void instrumentWithoutRestart(ActiveInstrumentation activeInstr,
13902             ApplicationInfo targetInfo) {
13903         ProcessRecord pr;
13904         synchronized (this) {
13905             pr = getProcessRecordLocked(targetInfo.processName, targetInfo.uid);
13906         }
13907 
13908         try {
13909             pr.getThread().instrumentWithoutRestart(
13910                     activeInstr.mClass,
13911                     activeInstr.mArguments,
13912                     activeInstr.mWatcher,
13913                     activeInstr.mUiAutomationConnection,
13914                     targetInfo);
13915         } catch (RemoteException e) {
13916             Slog.i(TAG, "RemoteException from instrumentWithoutRestart", e);
13917         }
13918     }
13919 
isCallerShell()13920     private boolean isCallerShell() {
13921         final int callingUid = Binder.getCallingUid();
13922         return callingUid == SHELL_UID || callingUid == ROOT_UID;
13923     }
13924 
13925     /**
13926      * Report errors that occur while attempting to start Instrumentation.  Always writes the
13927      * error to the logs, but if somebody is watching, send the report there too.  This enables
13928      * the "am" command to report errors with more information.
13929      *
13930      * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
13931      * @param cn The component name of the instrumentation.
13932      * @param report The error report.
13933      */
reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)13934     private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher,
13935             ComponentName cn, String report) {
13936         Slog.w(TAG, report);
13937         if (watcher != null) {
13938             Bundle results = new Bundle();
13939             results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13940             results.putString("Error", report);
13941             mInstrumentationReporter.reportStatus(watcher, cn, -1, results);
13942         }
13943     }
13944 
addInstrumentationResultsLocked(ProcessRecord app, Bundle results)13945     void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) {
13946         final ActiveInstrumentation instr = app.getActiveInstrumentation();
13947         if (instr == null) {
13948             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
13949             return;
13950         }
13951 
13952         if (!instr.mFinished && results != null) {
13953             if (instr.mCurResults == null) {
13954                 instr.mCurResults = new Bundle(results);
13955             } else {
13956                 instr.mCurResults.putAll(results);
13957             }
13958         }
13959     }
13960 
addInstrumentationResults(IApplicationThread target, Bundle results)13961     public void addInstrumentationResults(IApplicationThread target, Bundle results) {
13962         int userId = UserHandle.getCallingUserId();
13963         // Refuse possible leaked file descriptors
13964         if (results != null && results.hasFileDescriptors()) {
13965             throw new IllegalArgumentException("File descriptors passed in Intent");
13966         }
13967 
13968         synchronized(this) {
13969             ProcessRecord app = getRecordForAppLOSP(target);
13970             if (app == null) {
13971                 Slog.w(TAG, "addInstrumentationResults: no app for " + target);
13972                 return;
13973             }
13974             final long origId = Binder.clearCallingIdentity();
13975             try {
13976                 addInstrumentationResultsLocked(app, results);
13977             } finally {
13978                 Binder.restoreCallingIdentity(origId);
13979             }
13980         }
13981     }
13982 
13983     @GuardedBy("this")
finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)13984     void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13985         final ActiveInstrumentation instr = app.getActiveInstrumentation();
13986         if (instr == null) {
13987             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
13988             return;
13989         }
13990 
13991         synchronized (mProcLock) {
13992             if (!instr.mFinished) {
13993                 if (instr.mWatcher != null) {
13994                     Bundle finalResults = instr.mCurResults;
13995                     if (finalResults != null) {
13996                         if (instr.mCurResults != null && results != null) {
13997                             finalResults.putAll(results);
13998                         }
13999                     } else {
14000                         finalResults = results;
14001                     }
14002                     mInstrumentationReporter.reportFinished(instr.mWatcher,
14003                             instr.mClass, resultCode, finalResults);
14004                 }
14005 
14006                 // Can't call out of the system process with a lock held, so post a message.
14007                 if (instr.mUiAutomationConnection != null) {
14008                     // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op.
14009                     mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid,
14010                             app.info.packageName, AppOpsManager.MODE_ERRORED);
14011                     mAppOpsService.setAppOpsServiceDelegate(null);
14012                     getPermissionManagerInternal().stopShellPermissionIdentityDelegation();
14013                     mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
14014                             instr.mUiAutomationConnection).sendToTarget();
14015                 }
14016                 instr.mFinished = true;
14017             }
14018 
14019             instr.removeProcess(app);
14020             app.setActiveInstrumentation(null);
14021         }
14022 
14023         if (!instr.mNoRestart) {
14024             forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false,
14025                     app.userId,
14026                     "finished inst");
14027         }
14028     }
14029 
finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)14030     public void finishInstrumentation(IApplicationThread target,
14031             int resultCode, Bundle results) {
14032         int userId = UserHandle.getCallingUserId();
14033         // Refuse possible leaked file descriptors
14034         if (results != null && results.hasFileDescriptors()) {
14035             throw new IllegalArgumentException("File descriptors passed in Intent");
14036         }
14037 
14038         synchronized(this) {
14039             ProcessRecord app = getRecordForAppLOSP(target);
14040             if (app == null) {
14041                 Slog.w(TAG, "finishInstrumentation: no app for " + target);
14042                 return;
14043             }
14044             final long origId = Binder.clearCallingIdentity();
14045             finishInstrumentationLocked(app, resultCode, results);
14046             Binder.restoreCallingIdentity(origId);
14047         }
14048     }
14049 
14050     @Override
getFocusedRootTaskInfo()14051     public RootTaskInfo getFocusedRootTaskInfo() throws RemoteException {
14052         return mActivityTaskManager.getFocusedRootTaskInfo();
14053     }
14054 
14055     @Override
getConfiguration()14056     public Configuration getConfiguration() {
14057         return mActivityTaskManager.getConfiguration();
14058     }
14059 
14060     @Override
suppressResizeConfigChanges(boolean suppress)14061     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
14062         mActivityTaskManager.suppressResizeConfigChanges(suppress);
14063     }
14064 
14065     @Override
updatePersistentConfiguration(Configuration values)14066     public void updatePersistentConfiguration(Configuration values) {
14067         updatePersistentConfigurationWithAttribution(values,
14068                 Settings.getPackageNameForUid(mContext, Binder.getCallingUid()), null);
14069     }
14070 
14071     @Override
updatePersistentConfigurationWithAttribution(Configuration values, String callingPackage, String callingAttributionTag)14072     public void updatePersistentConfigurationWithAttribution(Configuration values,
14073             String callingPackage, String callingAttributionTag) {
14074         enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
14075         enforceWriteSettingsPermission("updatePersistentConfiguration()", callingPackage,
14076                 callingAttributionTag);
14077         if (values == null) {
14078             throw new NullPointerException("Configuration must not be null");
14079         }
14080 
14081         int userId = UserHandle.getCallingUserId();
14082 
14083         mActivityTaskManager.updatePersistentConfiguration(values, userId);
14084     }
14085 
enforceWriteSettingsPermission(String func, String callingPackage, String callingAttributionTag)14086     private void enforceWriteSettingsPermission(String func, String callingPackage,
14087             String callingAttributionTag) {
14088         int uid = Binder.getCallingUid();
14089         if (uid == ROOT_UID) {
14090             return;
14091         }
14092 
14093         if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
14094                 callingPackage, callingAttributionTag, false)) {
14095             return;
14096         }
14097 
14098         String msg = "Permission Denial: " + func + " from pid="
14099                 + Binder.getCallingPid()
14100                 + ", uid=" + uid
14101                 + " requires " + android.Manifest.permission.WRITE_SETTINGS;
14102         Slog.w(TAG, msg);
14103         throw new SecurityException(msg);
14104     }
14105 
14106     @Override
updateConfiguration(Configuration values)14107     public boolean updateConfiguration(Configuration values) {
14108         return mActivityTaskManager.updateConfiguration(values);
14109     }
14110 
14111     @Override
updateMccMncConfiguration(String mcc, String mnc)14112     public boolean updateMccMncConfiguration(String mcc, String mnc) {
14113         int mccInt, mncInt;
14114         try {
14115             mccInt = Integer.parseInt(mcc);
14116             mncInt = Integer.parseInt(mnc);
14117         } catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
14118             Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex);
14119             return false;
14120         }
14121         Configuration config = new Configuration();
14122         config.mcc = mccInt;
14123         config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;
14124         return mActivityTaskManager.updateConfiguration(config);
14125     }
14126 
14127     @Override
getLaunchedFromUid(IBinder activityToken)14128     public int getLaunchedFromUid(IBinder activityToken) {
14129         return ActivityClient.getInstance().getLaunchedFromUid(activityToken);
14130     }
14131 
getLaunchedFromPackage(IBinder activityToken)14132     public String getLaunchedFromPackage(IBinder activityToken) {
14133         return ActivityClient.getInstance().getLaunchedFromPackage(activityToken);
14134     }
14135 
14136     // =========================================================
14137     // LIFETIME MANAGEMENT
14138     // =========================================================
14139 
14140     // Returns whether the app is receiving broadcast.
14141     // If receiving, fetch all broadcast queues which the app is
14142     // the current [or imminent] receiver on.
isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)14143     boolean isReceivingBroadcastLocked(ProcessRecord app,
14144             ArraySet<BroadcastQueue> receivingQueues) {
14145         final ProcessReceiverRecord prr = app.mReceivers;
14146         final int numOfReceivers = prr.numberOfCurReceivers();
14147         if (numOfReceivers > 0) {
14148             for (int i = 0; i < numOfReceivers; i++) {
14149                 receivingQueues.add(prr.getCurReceiverAt(i).queue);
14150             }
14151             return true;
14152         }
14153 
14154         // It's not the current receiver, but it might be starting up to become one
14155         for (BroadcastQueue queue : mBroadcastQueues) {
14156             final BroadcastRecord r = queue.mPendingBroadcast;
14157             if (r != null && r.curApp == app) {
14158                 // found it; report which queue it's in
14159                 receivingQueues.add(queue);
14160             }
14161         }
14162 
14163         return !receivingQueues.isEmpty();
14164     }
14165 
startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)14166     Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState,
14167             int targetUid, long targetVersionCode, ComponentName targetComponent,
14168             String targetProcess) {
14169         if (!mTrackingAssociations) {
14170             return null;
14171         }
14172         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
14173                 = mAssociations.get(targetUid);
14174         if (components == null) {
14175             components = new ArrayMap<>();
14176             mAssociations.put(targetUid, components);
14177         }
14178         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
14179         if (sourceUids == null) {
14180             sourceUids = new SparseArray<>();
14181             components.put(targetComponent, sourceUids);
14182         }
14183         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
14184         if (sourceProcesses == null) {
14185             sourceProcesses = new ArrayMap<>();
14186             sourceUids.put(sourceUid, sourceProcesses);
14187         }
14188         Association ass = sourceProcesses.get(sourceProcess);
14189         if (ass == null) {
14190             ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent,
14191                     targetProcess);
14192             sourceProcesses.put(sourceProcess, ass);
14193         }
14194         ass.mCount++;
14195         ass.mNesting++;
14196         if (ass.mNesting == 1) {
14197             ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis();
14198             ass.mLastState = sourceState;
14199         }
14200         return ass;
14201     }
14202 
stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)14203     void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid,
14204             long targetVersionCode, ComponentName targetComponent, String targetProcess) {
14205         if (!mTrackingAssociations) {
14206             return;
14207         }
14208         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
14209                 = mAssociations.get(targetUid);
14210         if (components == null) {
14211             return;
14212         }
14213         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
14214         if (sourceUids == null) {
14215             return;
14216         }
14217         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
14218         if (sourceProcesses == null) {
14219             return;
14220         }
14221         Association ass = sourceProcesses.get(sourceProcess);
14222         if (ass == null || ass.mNesting <= 0) {
14223             return;
14224         }
14225         ass.mNesting--;
14226         if (ass.mNesting == 0) {
14227             long uptime = SystemClock.uptimeMillis();
14228             ass.mTime += uptime - ass.mStartTime;
14229             ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
14230                     += uptime - ass.mLastStateUptime;
14231             ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2;
14232         }
14233     }
14234 
noteUidProcessState(final int uid, final int state, final @ProcessCapability int capability)14235     void noteUidProcessState(final int uid, final int state,
14236                 final @ProcessCapability int capability) {
14237         mBatteryStatsService.noteUidProcessState(uid, state);
14238         mAppOpsService.updateUidProcState(uid, state, capability);
14239         if (mTrackingAssociations) {
14240             for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
14241                 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
14242                         = mAssociations.valueAt(i1);
14243                 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
14244                     SparseArray<ArrayMap<String, Association>> sourceUids
14245                             = targetComponents.valueAt(i2);
14246                     ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid);
14247                     if (sourceProcesses != null) {
14248                         for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
14249                             Association ass = sourceProcesses.valueAt(i4);
14250                             if (ass.mNesting >= 1) {
14251                                 // currently associated
14252                                 long uptime = SystemClock.uptimeMillis();
14253                                 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
14254                                         += uptime - ass.mLastStateUptime;
14255                                 ass.mLastState = state;
14256                                 ass.mLastStateUptime = uptime;
14257                             }
14258                         }
14259                     }
14260                 }
14261             }
14262         }
14263     }
14264 
14265     /**
14266      * Returns true if things are idle enough to perform GCs.
14267      */
14268     @GuardedBy("this")
canGcNowLocked()14269     final boolean canGcNowLocked() {
14270         for (BroadcastQueue q : mBroadcastQueues) {
14271             if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isEmpty()) {
14272                 return false;
14273             }
14274         }
14275         return mAtmInternal.canGcNow();
14276     }
14277 
checkExcessivePowerUsage()14278     private void checkExcessivePowerUsage() {
14279         updateCpuStatsNow();
14280 
14281         final boolean monitorPhantomProcs = mSystemReady && FeatureFlagUtils.isEnabled(mContext,
14282                 SETTINGS_ENABLE_MONITOR_PHANTOM_PROCS);
14283         synchronized (mProcLock) {
14284             final boolean doCpuKills = mLastPowerCheckUptime != 0;
14285             final long curUptime = SystemClock.uptimeMillis();
14286             final long uptimeSince = curUptime - mLastPowerCheckUptime;
14287             mLastPowerCheckUptime = curUptime;
14288             mProcessList.forEachLruProcessesLOSP(false, app -> {
14289                 if (app.getThread() == null) {
14290                     return;
14291                 }
14292                 if (app.mState.getSetProcState() >= ActivityManager.PROCESS_STATE_HOME) {
14293                     int cpuLimit;
14294                     long checkDur = curUptime - app.mState.getWhenUnimportant();
14295                     if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
14296                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
14297                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 2)
14298                             || app.mState.getSetProcState() <= ActivityManager.PROCESS_STATE_HOME) {
14299                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
14300                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL * 3)) {
14301                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
14302                     } else {
14303                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
14304                     }
14305 
14306                     updateAppProcessCpuTimeLPr(uptimeSince, doCpuKills, checkDur, cpuLimit, app);
14307 
14308                     if (monitorPhantomProcs) {
14309                         // Also check the phantom processes if there is any
14310                         updatePhantomProcessCpuTimeLPr(
14311                                 uptimeSince, doCpuKills, checkDur, cpuLimit, app);
14312                     }
14313                 }
14314             });
14315         }
14316     }
14317 
14318     @GuardedBy("mProcLock")
updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)14319     private void updateAppProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills,
14320             final long checkDur, final int cpuLimit, final ProcessRecord app) {
14321         synchronized (mAppProfiler.mProfilerLock) {
14322             final ProcessProfileRecord profile = app.mProfile;
14323             final long curCpuTime = profile.mCurCpuTime.get();
14324             final long lastCpuTime = profile.mLastCpuTime.get();
14325             if (lastCpuTime > 0) {
14326                 final long cpuTimeUsed = curCpuTime - lastCpuTime;
14327                 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed,
14328                             app.processName, app.toShortString(), cpuLimit, app)) {
14329                     mHandler.post(() -> {
14330                         synchronized (ActivityManagerService.this) {
14331                             app.killLocked("excessive cpu " + cpuTimeUsed + " during "
14332                                     + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit,
14333                                     ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
14334                                     ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
14335                                     true);
14336                         }
14337                     });
14338                     profile.reportExcessiveCpu();
14339                 }
14340             }
14341 
14342             profile.mLastCpuTime.set(curCpuTime);
14343         }
14344     }
14345 
14346     @GuardedBy("mProcLock")
updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills, final long checkDur, final int cpuLimit, final ProcessRecord app)14347     private void updatePhantomProcessCpuTimeLPr(final long uptimeSince, final boolean doCpuKills,
14348             final long checkDur, final int cpuLimit, final ProcessRecord app) {
14349         mPhantomProcessList.forEachPhantomProcessOfApp(app, r -> {
14350             if (r.mLastCputime > 0) {
14351                 final long cpuTimeUsed = r.mCurrentCputime - r.mLastCputime;
14352                 if (checkExcessivePowerUsageLPr(uptimeSince, doCpuKills, cpuTimeUsed,
14353                             app.processName, r.toString(), cpuLimit, app)) {
14354                     mHandler.post(() -> {
14355                         synchronized (ActivityManagerService.this) {
14356                             mPhantomProcessList.killPhantomProcessGroupLocked(app, r,
14357                                     ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
14358                                     ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
14359                                     "excessive cpu " + cpuTimeUsed + " during "
14360                                     + uptimeSince + " dur=" + checkDur + " limit=" + cpuLimit);
14361                         }
14362                     });
14363                     return false;
14364                 }
14365             }
14366             r.mLastCputime = r.mCurrentCputime;
14367             return true;
14368         });
14369     }
14370 
14371     @GuardedBy("mProcLock")
checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills, final long cputimeUsed, final String processName, final String description, final int cpuLimit, final ProcessRecord app)14372     private boolean checkExcessivePowerUsageLPr(final long uptimeSince, boolean doCpuKills,
14373             final long cputimeUsed, final String processName, final String description,
14374             final int cpuLimit, final ProcessRecord app) {
14375         if (DEBUG_POWER && (uptimeSince > 0)) {
14376             StringBuilder sb = new StringBuilder(128);
14377             sb.append("CPU for ");
14378             sb.append(description);
14379             sb.append(": over ");
14380             TimeUtils.formatDuration(uptimeSince, sb);
14381             sb.append(" used ");
14382             TimeUtils.formatDuration(cputimeUsed, sb);
14383             sb.append(" (");
14384             sb.append((cputimeUsed * 100.0) / uptimeSince);
14385             sb.append("%)");
14386             Slog.i(TAG_POWER, sb.toString());
14387         }
14388         // If the process has used too much CPU over the last duration, the
14389         // user probably doesn't want this, so kill!
14390         if (doCpuKills && uptimeSince > 0) {
14391             if (((cputimeUsed * 100) / uptimeSince) >= cpuLimit) {
14392                 mBatteryStatsService.reportExcessiveCpu(app.info.uid, app.processName,
14393                         uptimeSince, cputimeUsed);
14394                 app.getPkgList().forEachPackageProcessStats(holder -> {
14395                     final ProcessState state = holder.state;
14396                     FrameworkStatsLog.write(
14397                             FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED,
14398                             app.info.uid,
14399                             processName,
14400                             state != null ? state.getPackage() : app.info.packageName,
14401                             holder.appVersion);
14402                 });
14403                 return true;
14404             }
14405         }
14406         return false;
14407     }
14408 
isEphemeralLocked(int uid)14409     private boolean isEphemeralLocked(int uid) {
14410         final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
14411         if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid
14412             return false;
14413         }
14414         return getPackageManagerInternal().isPackageEphemeral(
14415                 UserHandle.getUserId(uid), packages[0]);
14416     }
14417 
14418     @GuardedBy("this")
enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)14419     void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) {
14420         uid = uidRec != null ? uidRec.getUid() : uid;
14421         if (uid < 0) {
14422             throw new IllegalArgumentException("No UidRecord or uid");
14423         }
14424 
14425         final int procState = uidRec != null
14426                 ? uidRec.getSetProcState() : PROCESS_STATE_NONEXISTENT;
14427         final long procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0;
14428         final int capability = uidRec != null ? uidRec.getSetCapability() : 0;
14429         final boolean ephemeral = uidRec != null ? uidRec.isEphemeral() : isEphemeralLocked(uid);
14430 
14431         if (uidRec != null && !uidRec.isIdle() && (change & UidRecord.CHANGE_GONE) != 0) {
14432             // If this uid is going away, and we haven't yet reported it is gone,
14433             // then do so now.
14434             change |= UidRecord.CHANGE_IDLE;
14435         }
14436         final int enqueuedChange = mUidObserverController.enqueueUidChange(
14437                 uidRec == null ? null : uidRec.pendingChange,
14438                 uid, change, procState, procStateSeq, capability, ephemeral);
14439         if (uidRec != null) {
14440             uidRec.setLastReportedChange(enqueuedChange);
14441             uidRec.updateLastDispatchedProcStateSeq(enqueuedChange);
14442         }
14443 
14444         // Directly update the power manager, since we sit on top of it and it is critical
14445         // it be kept in sync (so wake locks will be held as soon as appropriate).
14446         if (mLocalPowerManager != null) {
14447             // TODO: dispatch cached/uncached changes here, so we don't need to report
14448             // all proc state changes.
14449             if ((enqueuedChange & UidRecord.CHANGE_ACTIVE) != 0) {
14450                 mLocalPowerManager.uidActive(uid);
14451             }
14452             if ((enqueuedChange & UidRecord.CHANGE_IDLE) != 0) {
14453                 mLocalPowerManager.uidIdle(uid);
14454             }
14455             if ((enqueuedChange & UidRecord.CHANGE_GONE) != 0) {
14456                 mLocalPowerManager.uidGone(uid);
14457             } else {
14458                 mLocalPowerManager.updateUidProcState(uid, procState);
14459             }
14460         }
14461     }
14462 
14463     @GuardedBy(anyOf = {"this", "mProcLock"})
setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor, long now)14464     final void setProcessTrackerStateLOSP(ProcessRecord proc, int memFactor, long now) {
14465         if (proc.getThread() != null) {
14466             proc.mProfile.setProcessTrackerState(
14467                     proc.mState.getReportedProcState(), memFactor, now);
14468         }
14469     }
14470 
14471     @GuardedBy("this")
updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)14472     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
14473             int fgServiceTypes, boolean oomAdj) {
14474         final ProcessServiceRecord psr = proc.mServices;
14475         if (isForeground != psr.hasForegroundServices()
14476                 || psr.getForegroundServiceTypes() != fgServiceTypes) {
14477             psr.setHasForegroundServices(isForeground, fgServiceTypes);
14478             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
14479                     proc.info.uid);
14480             if (isForeground) {
14481                 if (curProcs == null) {
14482                     curProcs = new ArrayList<ProcessRecord>();
14483                     mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
14484                 }
14485                 if (!curProcs.contains(proc)) {
14486                     curProcs.add(proc);
14487                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
14488                             proc.info.packageName, proc.info.uid);
14489                 }
14490             } else {
14491                 if (curProcs != null) {
14492                     if (curProcs.remove(proc)) {
14493                         mBatteryStatsService.noteEvent(
14494                                 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
14495                                 proc.info.packageName, proc.info.uid);
14496                         if (curProcs.size() <= 0) {
14497                             mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
14498                         }
14499                     }
14500                 }
14501             }
14502 
14503             psr.setReportedForegroundServiceTypes(fgServiceTypes);
14504             ProcessChangeItem item = mProcessList.enqueueProcessChangeItemLocked(
14505                     proc.getPid(), proc.info.uid);
14506             item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES;
14507             item.foregroundServiceTypes = fgServiceTypes;
14508         }
14509         if (oomAdj) {
14510             updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
14511         }
14512     }
14513 
14514     // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update
14515     // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities
getTopApp()14516     ProcessRecord getTopApp() {
14517         final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null;
14518         final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null;
14519         String pkg;
14520         int uid;
14521         if (r != null) {
14522             pkg = r.processName;
14523             uid = r.info.uid;
14524         } else {
14525             pkg = null;
14526             uid = -1;
14527         }
14528         // Has the UID or resumed package name changed?
14529         synchronized (mCurResumedAppLock) {
14530             if (uid != mCurResumedUid || (pkg != mCurResumedPackage
14531                         && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
14532 
14533                 final long identity = Binder.clearCallingIdentity();
14534                 try {
14535                     if (mCurResumedPackage != null) {
14536                         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
14537                                 mCurResumedPackage, mCurResumedUid);
14538                     }
14539                     mCurResumedPackage = pkg;
14540                     mCurResumedUid = uid;
14541                     if (mCurResumedPackage != null) {
14542                         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
14543                                 mCurResumedPackage, mCurResumedUid);
14544                     }
14545                 } finally {
14546                     Binder.restoreCallingIdentity(identity);
14547                 }
14548             }
14549         }
14550         return r;
14551     }
14552 
14553     /**
14554      * Enqueue the given process into a todo list, and the caller should
14555      * call {@link #updateOomAdjPendingTargetsLocked} to kick off a pass of the oom adj update.
14556      */
14557     @GuardedBy("this")
enqueueOomAdjTargetLocked(ProcessRecord app)14558     void enqueueOomAdjTargetLocked(ProcessRecord app) {
14559         mOomAdjuster.enqueueOomAdjTargetLocked(app);
14560     }
14561 
14562     /**
14563      * Remove the given process into a todo list.
14564      */
14565     @GuardedBy("this")
removeOomAdjTargetLocked(ProcessRecord app, boolean procDied)14566     void removeOomAdjTargetLocked(ProcessRecord app, boolean procDied) {
14567         mOomAdjuster.removeOomAdjTargetLocked(app, procDied);
14568     }
14569 
14570     /**
14571      * Kick off an oom adj update pass for the pending targets which are enqueued via
14572      * {@link #enqueueOomAdjTargetLocked}.
14573      */
14574     @GuardedBy("this")
updateOomAdjPendingTargetsLocked(String oomAdjReason)14575     void updateOomAdjPendingTargetsLocked(String oomAdjReason) {
14576         mOomAdjuster.updateOomAdjPendingTargetsLocked(oomAdjReason);
14577     }
14578 
14579     static final class ProcStatsRunnable implements Runnable {
14580         private final ActivityManagerService mService;
14581         private final ProcessStatsService mProcessStats;
14582 
ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)14583         ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) {
14584             this.mService = service;
14585             this.mProcessStats = mProcessStats;
14586         }
14587 
run()14588         @Override public void run() {
14589             mProcessStats.writeStateAsync();
14590         }
14591     }
14592 
14593     @GuardedBy("this")
updateOomAdjLocked(String oomAdjReason)14594     final void updateOomAdjLocked(String oomAdjReason) {
14595         mOomAdjuster.updateOomAdjLocked(oomAdjReason);
14596     }
14597 
14598     /**
14599      * Update OomAdj for a specific process and its reachable processes.
14600      *
14601      * @param app The process to update
14602      * @param oomAdjReason
14603      * @return whether updateOomAdjLocked(app) was successful.
14604      */
14605     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, String oomAdjReason)14606     final boolean updateOomAdjLocked(ProcessRecord app, String oomAdjReason) {
14607         return mOomAdjuster.updateOomAdjLocked(app, oomAdjReason);
14608     }
14609 
14610     @Override
makePackageIdle(String packageName, int userId)14611     public void makePackageIdle(String packageName, int userId) {
14612         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
14613                 != PackageManager.PERMISSION_GRANTED) {
14614             String msg = "Permission Denial: makePackageIdle() from pid="
14615                     + Binder.getCallingPid()
14616                     + ", uid=" + Binder.getCallingUid()
14617                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
14618             Slog.w(TAG, msg);
14619             throw new SecurityException(msg);
14620         }
14621         final int callingPid = Binder.getCallingPid();
14622         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
14623                 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null);
14624         final long callingId = Binder.clearCallingIdentity();
14625         try {
14626             IPackageManager pm = AppGlobals.getPackageManager();
14627             int pkgUid = -1;
14628             try {
14629                 pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES
14630                         | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM);
14631             } catch (RemoteException e) {
14632             }
14633             if (pkgUid == -1) {
14634                 throw new IllegalArgumentException("Unknown package name " + packageName);
14635             }
14636 
14637             synchronized (this) {
14638                 try {
14639                     if (mLocalPowerManager != null) {
14640                         mLocalPowerManager.startUidChanges();
14641                     }
14642                     final int appId = UserHandle.getAppId(pkgUid);
14643                     for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; i--) {
14644                         final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
14645                         final long bgTime = uidRec.getLastBackgroundTime();
14646                         if (bgTime > 0 && !uidRec.isIdle()) {
14647                             final int uid = uidRec.getUid();
14648                             if (UserHandle.getAppId(uid) == appId) {
14649                                 if (userId == UserHandle.USER_ALL
14650                                         || userId == UserHandle.getUserId(uid)) {
14651                                     EventLogTags.writeAmUidIdle(uid);
14652                                     synchronized (mProcLock) {
14653                                         uidRec.setIdle(true);
14654                                         uidRec.setSetIdle(true);
14655                                     }
14656                                     Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uid)
14657                                             + " from package " + packageName + " user " + userId);
14658                                     doStopUidLocked(uid, uidRec);
14659                                 }
14660                             }
14661                         }
14662                     }
14663                 } finally {
14664                     if (mLocalPowerManager != null) {
14665                         mLocalPowerManager.finishUidChanges();
14666                     }
14667                 }
14668             }
14669         } finally {
14670             Binder.restoreCallingIdentity(callingId);
14671         }
14672     }
14673 
14674     /** Make the currently active UIDs idle after a certain grace period. */
idleUids()14675     final void idleUids() {
14676         synchronized (this) {
14677             mOomAdjuster.idleUidsLocked();
14678         }
14679     }
14680 
runInBackgroundDisabled(int uid)14681     final void runInBackgroundDisabled(int uid) {
14682         synchronized (this) {
14683             UidRecord uidRec = mProcessList.getUidRecordLOSP(uid);
14684             if (uidRec != null) {
14685                 // This uid is actually running...  should it be considered background now?
14686                 if (uidRec.isIdle()) {
14687                     doStopUidLocked(uidRec.getUid(), uidRec);
14688                 }
14689             } else {
14690                 // This uid isn't actually running...  still send a report about it being "stopped".
14691                 doStopUidLocked(uid, null);
14692             }
14693         }
14694     }
14695 
cameraActiveChanged(@serIdInt int uid, boolean active)14696     final void cameraActiveChanged(@UserIdInt int uid, boolean active) {
14697         synchronized (mActiveCameraUids) {
14698             final int curIndex = mActiveCameraUids.indexOf(uid);
14699             if (active) {
14700                 if (curIndex < 0) {
14701                     mActiveCameraUids.add(uid);
14702                 }
14703             } else {
14704                 if (curIndex >= 0) {
14705                     mActiveCameraUids.remove(curIndex);
14706                 }
14707             }
14708         }
14709     }
14710 
isCameraActiveForUid(@serIdInt int uid)14711     final boolean isCameraActiveForUid(@UserIdInt int uid) {
14712         synchronized (mActiveCameraUids) {
14713             return mActiveCameraUids.indexOf(uid) >= 0;
14714         }
14715     }
14716 
14717     @GuardedBy("this")
doStopUidLocked(int uid, final UidRecord uidRec)14718     final void doStopUidLocked(int uid, final UidRecord uidRec) {
14719         mServices.stopInBackgroundLocked(uid);
14720         enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE);
14721     }
14722 
14723     /**
14724      * Allowlists {@code targetUid} to temporarily bypass Power Save mode.
14725      */
14726     @GuardedBy("this")
tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)14727     void tempAllowlistForPendingIntentLocked(int callerPid, int callerUid, int targetUid,
14728             long duration, int type, @ReasonCode int reasonCode, String reason) {
14729         if (DEBUG_ALLOWLISTS) {
14730             Slog.d(TAG, "tempAllowlistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", "
14731                     + targetUid + ", " + duration + ", " + type + ")");
14732         }
14733 
14734         synchronized (mPidsSelfLocked) {
14735             final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
14736             if (pr == null) {
14737                 Slog.w(TAG, "tempAllowlistForPendingIntentLocked() no ProcessRecord for pid "
14738                         + callerPid);
14739                 return;
14740             }
14741             if (!pr.mServices.mAllowlistManager) {
14742                 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid)
14743                         != PackageManager.PERMISSION_GRANTED
14744                         && checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callerPid, callerUid)
14745                         != PackageManager.PERMISSION_GRANTED
14746                         && checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callerPid,
14747                         callerUid) != PackageManager.PERMISSION_GRANTED) {
14748                     if (DEBUG_ALLOWLISTS) {
14749                         Slog.d(TAG, "tempAllowlistForPendingIntentLocked() for target " + targetUid
14750                                 + ": pid " + callerPid + " is not allowed");
14751                     }
14752                     return;
14753                 }
14754             }
14755         }
14756 
14757         tempAllowlistUidLocked(targetUid, duration, reasonCode, reason, type, callerUid);
14758     }
14759 
14760     /**
14761      * Allowlists {@code targetUid} to temporarily bypass Power Save mode.
14762      */
14763     @GuardedBy("this")
tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode, String reason, @TempAllowListType int type, int callingUid)14764     void tempAllowlistUidLocked(int targetUid, long duration, @ReasonCode int reasonCode,
14765             String reason, @TempAllowListType int type, int callingUid) {
14766         synchronized (mProcLock) {
14767             // The temp allowlist type could change according to the reasonCode.
14768             if (mLocalDeviceIdleController != null) {
14769                 type = mLocalDeviceIdleController.getTempAllowListType(reasonCode, type);
14770             }
14771             if (type == TEMPORARY_ALLOW_LIST_TYPE_NONE) {
14772                 return;
14773             }
14774             mPendingTempAllowlist.put(targetUid,
14775                     new PendingTempAllowlist(targetUid, duration, reasonCode, reason, type,
14776                             callingUid));
14777             setUidTempAllowlistStateLSP(targetUid, true);
14778             mUiHandler.obtainMessage(PUSH_TEMP_ALLOWLIST_UI_MSG).sendToTarget();
14779 
14780             if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) {
14781                 mFgsStartTempAllowList.add(targetUid, duration,
14782                         new FgsTempAllowListItem(duration, reasonCode, reason, callingUid));
14783             }
14784         }
14785     }
14786 
pushTempAllowlist()14787     void pushTempAllowlist() {
14788         final int N;
14789         final PendingTempAllowlist[] list;
14790 
14791         // First copy out the pending changes...  we need to leave them in the map for now,
14792         // in case someone needs to check what is coming up while we don't have the lock held.
14793         synchronized (mProcLock) {
14794             N = mPendingTempAllowlist.size();
14795             list = new PendingTempAllowlist[N];
14796             for (int i = 0; i < N; i++) {
14797                 list[i] = mPendingTempAllowlist.valueAt(i);
14798             }
14799         }
14800 
14801         // Now safely dispatch changes to device idle controller.  Skip this if we're early
14802         // in boot and the controller hasn't yet been brought online:  we do not apply
14803         // device idle policy anyway at this phase.
14804         if (mLocalDeviceIdleController != null) {
14805             for (int i = 0; i < N; i++) {
14806                 PendingTempAllowlist ptw = list[i];
14807                 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid,
14808                         ptw.duration, ptw.type, true, ptw.reasonCode, ptw.tag,
14809                         ptw.callingUid);
14810             }
14811         }
14812 
14813         // And now we can safely remove them from the map.
14814         synchronized (this) {
14815             synchronized (mProcLock) {
14816                 for (int i = 0; i < N; i++) {
14817                     PendingTempAllowlist ptw = list[i];
14818                     int index = mPendingTempAllowlist.indexOfKey(ptw.targetUid);
14819                     if (index >= 0 && mPendingTempAllowlist.valueAt(index) == ptw) {
14820                         mPendingTempAllowlist.removeAt(index);
14821                     }
14822                 }
14823             }
14824         }
14825     }
14826 
14827     @GuardedBy({"this", "mProcLock"})
setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist)14828     final void setAppIdTempAllowlistStateLSP(int uid, boolean onAllowlist) {
14829         mOomAdjuster.setAppIdTempAllowlistStateLSP(uid, onAllowlist);
14830     }
14831 
14832     @GuardedBy({"this", "mProcLock"})
setUidTempAllowlistStateLSP(int uid, boolean onAllowlist)14833     final void setUidTempAllowlistStateLSP(int uid, boolean onAllowlist) {
14834         mOomAdjuster.setUidTempAllowlistStateLSP(uid, onAllowlist);
14835     }
14836 
trimApplications(boolean forceFullOomAdj, String oomAdjReason)14837     private void trimApplications(boolean forceFullOomAdj, String oomAdjReason) {
14838         synchronized (this) {
14839             trimApplicationsLocked(forceFullOomAdj, oomAdjReason);
14840         }
14841     }
14842 
14843     @GuardedBy("this")
trimApplicationsLocked(boolean forceFullOomAdj, String oomAdjReason)14844     private void trimApplicationsLocked(boolean forceFullOomAdj, String oomAdjReason) {
14845         // First remove any unused application processes whose package
14846         // has been removed.
14847         boolean didSomething = false;
14848         for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) {
14849             final ProcessRecord app = mProcessList.mRemovedProcesses.get(i);
14850             if (!app.hasActivitiesOrRecentTasks()
14851                     && app.mReceivers.numberOfCurReceivers() == 0
14852                     && app.mServices.numberOfRunningServices() == 0) {
14853                 final IApplicationThread thread = app.getThread();
14854                 Slog.i(TAG, "Exiting empty application process "
14855                         + app.toShortString() + " ("
14856                         + (thread != null ? thread.asBinder() : null)
14857                         + ")\n");
14858                 final int pid = app.getPid();
14859                 if (pid > 0 && pid != MY_PID) {
14860                     app.killLocked("empty",
14861                             ApplicationExitInfo.REASON_OTHER,
14862                             ApplicationExitInfo.SUBREASON_TRIM_EMPTY,
14863                             false);
14864                 } else if (thread != null) {
14865                     try {
14866                         thread.scheduleExit();
14867                     } catch (Exception e) {
14868                         // Ignore exceptions.
14869                     }
14870                 }
14871                 didSomething = true;
14872                 cleanUpApplicationRecordLocked(app, pid, false, true, -1, false /*replacingPid*/,
14873                         false /* fromBinderDied */);
14874                 mProcessList.mRemovedProcesses.remove(i);
14875 
14876                 if (app.isPersistent()) {
14877                     addAppLocked(app.info, null, false, null /* ABI override */,
14878                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
14879                 }
14880             }
14881         }
14882 
14883         // Now update the oom adj for all processes. Don't skip this, since other callers
14884         // might be depending on it.
14885         if (didSomething || forceFullOomAdj) {
14886             updateOomAdjLocked(oomAdjReason);
14887         } else {
14888             // Process any pending oomAdj targets, it'll be a no-op if nothing is pending.
14889             updateOomAdjPendingTargetsLocked(oomAdjReason);
14890         }
14891     }
14892 
14893     /** This method sends the specified signal to each of the persistent apps */
signalPersistentProcesses(final int sig)14894     public void signalPersistentProcesses(final int sig) throws RemoteException {
14895         if (sig != SIGNAL_USR1) {
14896             throw new SecurityException("Only SIGNAL_USR1 is allowed");
14897         }
14898 
14899         if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14900                 != PackageManager.PERMISSION_GRANTED) {
14901             throw new SecurityException("Requires permission "
14902                     + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14903         }
14904 
14905         synchronized (mProcLock) {
14906             mProcessList.forEachLruProcessesLOSP(false, app -> {
14907                 if (app.getThread() != null && app.isPersistent()) {
14908                     sendSignal(app.getPid(), sig);
14909                 }
14910             });
14911         }
14912     }
14913 
profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)14914     public boolean profileControl(String process, int userId, boolean start,
14915             ProfilerInfo profilerInfo, int profileType) throws RemoteException {
14916         // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14917         // its own permission.
14918         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14919                 != PackageManager.PERMISSION_GRANTED) {
14920             throw new SecurityException("Requires permission "
14921                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14922         }
14923 
14924         if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
14925             throw new IllegalArgumentException("null profile info or fd");
14926         }
14927 
14928         ProcessRecord proc = null;
14929         synchronized (mProcLock) {
14930             if (process != null) {
14931                 proc = findProcessLOSP(process, userId, "profileControl");
14932             }
14933 
14934             if (start && (proc == null || proc.getThread() == null)) {
14935                 throw new IllegalArgumentException("Unknown process: " + process);
14936             }
14937         }
14938 
14939         synchronized (mAppProfiler.mProfilerLock) {
14940             return mAppProfiler.profileControlLPf(proc, start, profilerInfo, profileType);
14941         }
14942     }
14943 
14944     @GuardedBy(anyOf = {"this", "mProcLock"})
findProcessLOSP(String process, int userId, String callName)14945     private ProcessRecord findProcessLOSP(String process, int userId, String callName) {
14946         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
14947                 userId, true, ALLOW_FULL_ONLY, callName, null);
14948         ProcessRecord proc = null;
14949         try {
14950             int pid = Integer.parseInt(process);
14951             synchronized (mPidsSelfLocked) {
14952                 proc = mPidsSelfLocked.get(pid);
14953             }
14954         } catch (NumberFormatException e) {
14955         }
14956 
14957         if (proc == null) {
14958             ArrayMap<String, SparseArray<ProcessRecord>> all =
14959                     mProcessList.getProcessNamesLOSP().getMap();
14960             SparseArray<ProcessRecord> procs = all.get(process);
14961             if (procs != null && procs.size() > 0) {
14962                 proc = procs.valueAt(0);
14963                 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14964                     for (int i=1; i<procs.size(); i++) {
14965                         ProcessRecord thisProc = procs.valueAt(i);
14966                         if (thisProc.userId == userId) {
14967                             proc = thisProc;
14968                             break;
14969                         }
14970                     }
14971                 }
14972             }
14973         }
14974 
14975         return proc;
14976     }
14977 
14978     @Override
dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)14979     public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo,
14980             boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) {
14981         try {
14982             // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14983             // its own permission (same as profileControl).
14984             if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14985                     != PackageManager.PERMISSION_GRANTED) {
14986                 throw new SecurityException("Requires permission "
14987                         + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14988             }
14989 
14990             if (fd == null) {
14991                 throw new IllegalArgumentException("null fd");
14992             }
14993 
14994             synchronized (this) {
14995                 ProcessRecord proc = findProcessLOSP(process, userId, "dumpHeap");
14996                 IApplicationThread thread;
14997                 if (proc == null || (thread = proc.getThread()) == null) {
14998                     throw new IllegalArgumentException("Unknown process: " + process);
14999                 }
15000 
15001                 boolean isDebuggable = Build.IS_DEBUGGABLE;
15002                 if (!isDebuggable) {
15003                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15004                         throw new SecurityException("Process not debuggable: " + proc);
15005                     }
15006                 }
15007 
15008                 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
15009 
15010                 final RemoteCallback intermediateCallback = new RemoteCallback(
15011                         new RemoteCallback.OnResultListener() {
15012                         @Override
15013                         public void onResult(Bundle result) {
15014                             finishCallback.sendResult(result);
15015                             mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
15016                         }
15017                     }, null);
15018 
15019                 thread.dumpHeap(managed, mallocInfo, runGc, path, fd, intermediateCallback);
15020                 fd = null;
15021                 return true;
15022             }
15023         } catch (RemoteException e) {
15024             throw new IllegalStateException("Process disappeared");
15025         } finally {
15026             if (fd != null) {
15027                 try {
15028                     fd.close();
15029                 } catch (IOException e) {
15030                 }
15031             }
15032         }
15033     }
15034 
15035     @Override
setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)15036     public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize,
15037             String reportPackage) {
15038         if (processName != null) {
15039             enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
15040                     "setDumpHeapDebugLimit()");
15041         } else {
15042             synchronized (mPidsSelfLocked) {
15043                 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid());
15044                 if (proc == null) {
15045                     throw new SecurityException("No process found for calling pid "
15046                             + Binder.getCallingPid());
15047                 }
15048                 if (!Build.IS_DEBUGGABLE
15049                         && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15050                     throw new SecurityException("Not running a debuggable build");
15051                 }
15052                 processName = proc.processName;
15053                 uid = proc.uid;
15054                 if (reportPackage != null && !proc.getPkgList().containsKey(reportPackage)) {
15055                     throw new SecurityException("Package " + reportPackage + " is not running in "
15056                             + proc);
15057                 }
15058             }
15059         }
15060         mAppProfiler.setDumpHeapDebugLimit(processName, uid, maxMemSize, reportPackage);
15061     }
15062 
15063     @Override
dumpHeapFinished(String path)15064     public void dumpHeapFinished(String path) {
15065         mAppProfiler.dumpHeapFinished(path, Binder.getCallingPid());
15066     }
15067 
15068     /** In this method we try to acquire our lock to make sure that we have not deadlocked */
monitor()15069     public void monitor() {
15070         synchronized (this) { }
15071     }
15072 
onCoreSettingsChange(Bundle settings)15073     void onCoreSettingsChange(Bundle settings) {
15074         synchronized (mProcLock) {
15075             mProcessList.updateCoreSettingsLOSP(settings);
15076         }
15077     }
15078 
15079     // Multi-user methods
15080 
15081     /**
15082      * Start user, if its not already running, but don't bring it to foreground.
15083      */
15084     @Override
startUserInBackground(final int userId)15085     public boolean startUserInBackground(final int userId) {
15086         return startUserInBackgroundWithListener(userId, null);
15087     }
15088 
15089     @Override
startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)15090     public boolean startUserInBackgroundWithListener(final int userId,
15091                 @Nullable IProgressListener unlockListener) {
15092         return mUserController.startUser(userId, /* foreground */ false, unlockListener);
15093     }
15094 
15095     @Override
startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)15096     public boolean startUserInForegroundWithListener(final int userId,
15097             @Nullable IProgressListener unlockListener) {
15098         // Permission check done inside UserController.
15099         return mUserController.startUser(userId, /* foreground */ true, unlockListener);
15100     }
15101 
15102     @Override
unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener)15103     public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) {
15104         return mUserController.unlockUser(userId, token, secret, listener);
15105     }
15106 
15107     @Override
switchUser(final int targetUserId)15108     public boolean switchUser(final int targetUserId) {
15109         return mUserController.switchUser(targetUserId);
15110     }
15111 
15112     @Override
getSwitchingFromUserMessage()15113     public String getSwitchingFromUserMessage() {
15114         return mUserController.getSwitchingFromSystemUserMessage();
15115     }
15116 
15117     @Override
getSwitchingToUserMessage()15118     public String getSwitchingToUserMessage() {
15119         return mUserController.getSwitchingToSystemUserMessage();
15120     }
15121 
15122     @Override
setStopUserOnSwitch(@topUserOnSwitch int value)15123     public void setStopUserOnSwitch(@StopUserOnSwitch int value) {
15124         mUserController.setStopUserOnSwitch(value);
15125     }
15126 
15127     @Override
stopUser(final int userId, boolean force, final IStopUserCallback callback)15128     public int stopUser(final int userId, boolean force, final IStopUserCallback callback) {
15129         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ false,
15130                 /* callback= */ callback, /* keyEvictedCallback= */ null);
15131     }
15132 
15133     /**
15134      * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after
15135      * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true.
15136      *
15137      * <p>When delayed locking is not enabled through the overlay, this call becomes the same
15138      * with {@link #stopUser(int, boolean, IStopUserCallback)} call.
15139      *
15140      * @param userId User id to stop.
15141      * @param force Force stop the user even if the user is related with system user or current
15142      *              user.
15143      * @param callback Callback called when user has stopped.
15144      *
15145      * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns
15146      *         other {@code ActivityManager#USER_OP_*} codes for failure.
15147      *
15148      */
15149     @Override
stopUserWithDelayedLocking(final int userId, boolean force, final IStopUserCallback callback)15150     public int stopUserWithDelayedLocking(final int userId, boolean force,
15151             final IStopUserCallback callback) {
15152         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ true,
15153                 /* callback= */ callback, /* keyEvictedCallback= */ null);
15154     }
15155 
15156     @Override
startProfile(@serIdInt int userId)15157     public boolean startProfile(@UserIdInt int userId) {
15158         return mUserController.startProfile(userId);
15159     }
15160 
15161     @Override
stopProfile(@serIdInt int userId)15162     public boolean stopProfile(@UserIdInt int userId) {
15163         return mUserController.stopProfile(userId);
15164     }
15165 
15166     @Override
getCurrentUser()15167     public UserInfo getCurrentUser() {
15168         return mUserController.getCurrentUser();
15169     }
15170 
15171     @Override
getCurrentUserId()15172     public @UserIdInt int getCurrentUserId() {
15173         return mUserController.getCurrentUserIdChecked();
15174     }
15175 
getStartedUserState(int userId)15176     String getStartedUserState(int userId) {
15177         final UserState userState = mUserController.getStartedUserState(userId);
15178         return UserState.stateToString(userState.state);
15179     }
15180 
15181     @Override
isUserRunning(int userId, int flags)15182     public boolean isUserRunning(int userId, int flags) {
15183         if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId())
15184                 && checkCallingPermission(INTERACT_ACROSS_USERS)
15185                     != PackageManager.PERMISSION_GRANTED) {
15186             String msg = "Permission Denial: isUserRunning() from pid="
15187                     + Binder.getCallingPid()
15188                     + ", uid=" + Binder.getCallingUid()
15189                     + " requires " + INTERACT_ACROSS_USERS;
15190             Slog.w(TAG, msg);
15191             throw new SecurityException(msg);
15192         }
15193         return mUserController.isUserRunning(userId, flags);
15194     }
15195 
15196     @Override
getRunningUserIds()15197     public int[] getRunningUserIds() {
15198         if (checkCallingPermission(INTERACT_ACROSS_USERS)
15199                 != PackageManager.PERMISSION_GRANTED) {
15200             String msg = "Permission Denial: isUserRunning() from pid="
15201                     + Binder.getCallingPid()
15202                     + ", uid=" + Binder.getCallingUid()
15203                     + " requires " + INTERACT_ACROSS_USERS;
15204             Slog.w(TAG, msg);
15205             throw new SecurityException(msg);
15206         }
15207         return mUserController.getStartedUserArray();
15208     }
15209 
15210     @Override
registerUserSwitchObserver(IUserSwitchObserver observer, String name)15211     public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
15212         mUserController.registerUserSwitchObserver(observer, name);
15213     }
15214 
15215     @Override
unregisterUserSwitchObserver(IUserSwitchObserver observer)15216     public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
15217         mUserController.unregisterUserSwitchObserver(observer);
15218     }
15219 
getAppInfoForUser(ApplicationInfo info, int userId)15220     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
15221         if (info == null) return null;
15222         ApplicationInfo newInfo = new ApplicationInfo(info);
15223         newInfo.initForUser(userId);
15224         return newInfo;
15225     }
15226 
isUserStopped(int userId)15227     public boolean isUserStopped(int userId) {
15228         return mUserController.getStartedUserState(userId) == null;
15229     }
15230 
getActivityInfoForUser(ActivityInfo aInfo, int userId)15231     ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
15232         if (aInfo == null
15233                 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
15234             return aInfo;
15235         }
15236 
15237         ActivityInfo info = new ActivityInfo(aInfo);
15238         info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15239         return info;
15240     }
15241 
15242     @GuardedBy("mProcLock")
processSanityChecksLPr(ProcessRecord process, IApplicationThread thread)15243     private boolean processSanityChecksLPr(ProcessRecord process, IApplicationThread thread) {
15244         if (process == null || thread == null) {
15245             return false;
15246         }
15247 
15248         if (!Build.IS_DEBUGGABLE) {
15249             if ((process.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15250                 return false;
15251             }
15252         }
15253 
15254         return true;
15255     }
15256 
startBinderTracking()15257     public boolean startBinderTracking() throws RemoteException {
15258         // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
15259         // permission (same as profileControl).
15260         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15261                 != PackageManager.PERMISSION_GRANTED) {
15262             throw new SecurityException("Requires permission "
15263                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15264         }
15265 
15266         synchronized (mProcLock) {
15267             mBinderTransactionTrackingEnabled = true;
15268             mProcessList.forEachLruProcessesLOSP(true, process -> {
15269                 final IApplicationThread thread = process.getThread();
15270                 if (!processSanityChecksLPr(process, thread)) {
15271                     return;
15272                 }
15273                 try {
15274                     thread.startBinderTracking();
15275                 } catch (RemoteException e) {
15276                     Log.v(TAG, "Process disappared");
15277                 }
15278             });
15279         }
15280         return true;
15281     }
15282 
15283     @Override
stopBinderTrackingAndDump(final ParcelFileDescriptor fd)15284     public boolean stopBinderTrackingAndDump(final ParcelFileDescriptor fd) throws RemoteException {
15285         // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
15286         // permission (same as profileControl).
15287         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15288                 != PackageManager.PERMISSION_GRANTED) {
15289             throw new SecurityException("Requires permission "
15290                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15291         }
15292 
15293         boolean closeFd = true;
15294         try {
15295             synchronized (mProcLock) {
15296                 if (fd == null) {
15297                     throw new IllegalArgumentException("null fd");
15298                 }
15299                 mBinderTransactionTrackingEnabled = false;
15300 
15301                 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor()));
15302                 pw.println("Binder transaction traces for all processes.\n");
15303                 mProcessList.forEachLruProcessesLOSP(true, process -> {
15304                     final IApplicationThread thread = process.getThread();
15305                     if (!processSanityChecksLPr(process, thread)) {
15306                         return;
15307                     }
15308 
15309                     pw.println("Traces for process: " + process.processName);
15310                     pw.flush();
15311                     try {
15312                         TransferPipe tp = new TransferPipe();
15313                         try {
15314                             thread.stopBinderTrackingAndDump(tp.getWriteFd());
15315                             tp.go(fd.getFileDescriptor());
15316                         } finally {
15317                             tp.kill();
15318                         }
15319                     } catch (IOException e) {
15320                         pw.println("Failure while dumping IPC traces from " + process +
15321                                 ".  Exception: " + e);
15322                         pw.flush();
15323                     } catch (RemoteException e) {
15324                         pw.println("Got a RemoteException while dumping IPC traces from " +
15325                                 process + ".  Exception: " + e);
15326                         pw.flush();
15327                     }
15328                 });
15329                 closeFd = false;
15330                 return true;
15331             }
15332         } finally {
15333             if (fd != null && closeFd) {
15334                 try {
15335                     fd.close();
15336                 } catch (IOException e) {
15337                 }
15338             }
15339         }
15340     }
15341 
15342     @VisibleForTesting
15343     public final class LocalService extends ActivityManagerInternal
15344             implements ActivityManagerLocal {
15345         @Override
checkContentProviderAccess(String authority, int userId)15346         public String checkContentProviderAccess(String authority, int userId) {
15347             return mCpHelper.checkContentProviderAccess(authority, userId);
15348         }
15349 
15350         @Override
checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)15351         public int checkContentProviderUriPermission(Uri uri, int userId,
15352                 int callingUid, int modeFlags) {
15353             return mCpHelper.checkContentProviderUriPermission(uri, userId, callingUid, modeFlags);
15354         }
15355 
15356         @Override
onWakefulnessChanged(int wakefulness)15357         public void onWakefulnessChanged(int wakefulness) {
15358             ActivityManagerService.this.onWakefulnessChanged(wakefulness);
15359         }
15360 
15361         @Override
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)15362         public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
15363                 String processName, String abiOverride, int uid, Runnable crashHandler) {
15364             return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
15365                     processName, abiOverride, uid, crashHandler);
15366         }
15367 
15368         @Override
onUserRemoved(@serIdInt int userId)15369         public void onUserRemoved(@UserIdInt int userId) {
15370             // Clean up any ActivityTaskManager state (by telling it the user is stopped)
15371             mAtmInternal.onUserStopped(userId);
15372             // Clean up various services by removing the user
15373             mBatteryStatsService.onUserRemoved(userId);
15374             mUserController.onUserRemoved(userId);
15375         }
15376 
15377         @Override
killForegroundAppsForUser(@serIdInt int userId)15378         public void killForegroundAppsForUser(@UserIdInt int userId) {
15379             final ArrayList<ProcessRecord> procs = new ArrayList<>();
15380             synchronized (mProcLock) {
15381                 final int numOfProcs = mProcessList.getProcessNamesLOSP().getMap().size();
15382                 for (int ip = 0; ip < numOfProcs; ip++) {
15383                     final SparseArray<ProcessRecord> apps =
15384                             mProcessList.getProcessNamesLOSP().getMap().valueAt(ip);
15385                     final int NA = apps.size();
15386                     for (int ia = 0; ia < NA; ia++) {
15387                         final ProcessRecord app = apps.valueAt(ia);
15388                         if (app.isPersistent()) {
15389                             // We don't kill persistent processes.
15390                             continue;
15391                         }
15392                         if (app.isRemoved()
15393                                 || (app.userId == userId && app.mState.hasForegroundActivities())) {
15394                             procs.add(app);
15395                         }
15396                     }
15397                 }
15398             }
15399 
15400             final int numOfProcs = procs.size();
15401             if (numOfProcs > 0) {
15402                 synchronized (ActivityManagerService.this) {
15403                     for (int i = 0; i < numOfProcs; i++) {
15404                         mProcessList.removeProcessLocked(procs.get(i), false, true,
15405                                 ApplicationExitInfo.REASON_OTHER,
15406                                 ApplicationExitInfo.SUBREASON_KILL_ALL_FG,
15407                                 "kill all fg");
15408                     }
15409                 }
15410             }
15411         }
15412 
15413         @Override
setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken, long duration, int type, @ReasonCode int reasonCode, @Nullable String reason)15414         public void setPendingIntentAllowlistDuration(IIntentSender target, IBinder allowlistToken,
15415                 long duration, int type, @ReasonCode int reasonCode, @Nullable String reason) {
15416             mPendingIntentController.setPendingIntentAllowlistDuration(target, allowlistToken,
15417                     duration, type, reasonCode, reason);
15418         }
15419 
15420         @Override
getPendingIntentFlags(IIntentSender target)15421         public int getPendingIntentFlags(IIntentSender target) {
15422             return mPendingIntentController.getPendingIntentFlags(target);
15423         }
15424 
15425         @Override
getStartedUserIds()15426         public int[] getStartedUserIds() {
15427             return mUserController.getStartedUserArray();
15428         }
15429 
15430         @Override
setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken, int flags)15431         public void setPendingIntentAllowBgActivityStarts(IIntentSender target,
15432                 IBinder allowlistToken, int flags) {
15433             if (!(target instanceof PendingIntentRecord)) {
15434                 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():"
15435                         + " not a PendingIntentRecord: " + target);
15436                 return;
15437             }
15438             synchronized (ActivityManagerService.this) {
15439                 ((PendingIntentRecord) target).setAllowBgActivityStarts(allowlistToken, flags);
15440             }
15441         }
15442 
15443         @Override
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder allowlistToken)15444         public void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
15445                 IBinder allowlistToken) {
15446             if (!(target instanceof PendingIntentRecord)) {
15447                 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():"
15448                         + " not a PendingIntentRecord: " + target);
15449                 return;
15450             }
15451             synchronized (ActivityManagerService.this) {
15452                 ((PendingIntentRecord) target).clearAllowBgActivityStarts(allowlistToken);
15453             }
15454         }
15455 
15456         @Override
setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids)15457         public void setDeviceIdleAllowlist(int[] allAppids, int[] exceptIdleAppids) {
15458             synchronized (ActivityManagerService.this) {
15459                 synchronized (mProcLock) {
15460                     mDeviceIdleAllowlist = allAppids;
15461                     mDeviceIdleExceptIdleAllowlist = exceptIdleAppids;
15462                 }
15463             }
15464         }
15465 
15466         @Override
updateDeviceIdleTempAllowlist(@ullable int[] appids, int changingUid, boolean adding, long durationMs, @TempAllowListType int type, @ReasonCode int reasonCode, @Nullable String reason, int callingUid)15467         public void updateDeviceIdleTempAllowlist(@Nullable int[] appids, int changingUid,
15468                 boolean adding, long durationMs, @TempAllowListType int type,
15469                 @ReasonCode int reasonCode, @Nullable String reason, int callingUid) {
15470             synchronized (ActivityManagerService.this) {
15471                 synchronized (mProcLock) {
15472                     if (appids != null) {
15473                         mDeviceIdleTempAllowlist = appids;
15474                     }
15475                     if (adding) {
15476                         if (type == TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED) {
15477                             // Note, the device idle temp-allowlist are by app-ids, but here
15478                             // mFgsStartTempAllowList contains UIDs.
15479                             mFgsStartTempAllowList.add(changingUid, durationMs,
15480                                     new FgsTempAllowListItem(durationMs, reasonCode, reason,
15481                                     callingUid));
15482                         }
15483                     } else {
15484                         mFgsStartTempAllowList.removeUid(changingUid);
15485                     }
15486                     setAppIdTempAllowlistStateLSP(changingUid, adding);
15487                 }
15488             }
15489         }
15490 
15491         @Override
getUidProcessState(int uid)15492         public int getUidProcessState(int uid) {
15493             return getUidState(uid);
15494         }
15495 
15496         @Override
getProcessesWithPendingBindMounts(int userId)15497         public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) {
15498             return mProcessList.getProcessesWithPendingBindMounts(userId);
15499         }
15500 
15501         @Override
isSystemReady()15502         public boolean isSystemReady() {
15503             // no need to synchronize(this) just to read & return the value
15504             return mSystemReady;
15505         }
15506 
15507         /**
15508          * Sets if the given pid has an overlay UI or not.
15509          *
15510          * @param pid The pid we are setting overlay UI for.
15511          * @param hasOverlayUi True if the process has overlay UI.
15512          * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
15513          */
15514         @Override
setHasOverlayUi(int pid, boolean hasOverlayUi)15515         public void setHasOverlayUi(int pid, boolean hasOverlayUi) {
15516             synchronized (ActivityManagerService.this) {
15517                 final ProcessRecord pr;
15518                 synchronized (mPidsSelfLocked) {
15519                     pr = mPidsSelfLocked.get(pid);
15520                     if (pr == null) {
15521                         Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid);
15522                         return;
15523                     }
15524                 }
15525                 if (pr.mState.hasOverlayUi() == hasOverlayUi) {
15526                     return;
15527                 }
15528                 pr.mState.setHasOverlayUi(hasOverlayUi);
15529                 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid);
15530                 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
15531             }
15532         }
15533 
15534         /**
15535          * Called after the network policy rules are updated by
15536          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
15537          * and {@param procStateSeq}.
15538          */
15539         @Override
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)15540         public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
15541             if (DEBUG_NETWORK) {
15542                 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: "
15543                         + uid + " seq: " + procStateSeq);
15544             }
15545             UidRecord record;
15546             synchronized (mProcLock) {
15547                 record = mProcessList.getUidRecordLOSP(uid);
15548                 if (record == null) {
15549                     if (DEBUG_NETWORK) {
15550                         Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
15551                                 + " procStateSeq: " + procStateSeq);
15552                     }
15553                     return;
15554                 }
15555             }
15556             synchronized (record.networkStateLock) {
15557                 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
15558                     if (DEBUG_NETWORK) {
15559                         Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already"
15560                                 + " been handled for uid: " + uid);
15561                     }
15562                     return;
15563                 }
15564                 record.lastNetworkUpdatedProcStateSeq = procStateSeq;
15565                 if (record.curProcStateSeq > procStateSeq) {
15566                     if (DEBUG_NETWORK) {
15567                         Slog.d(TAG_NETWORK, "No need to handle older seq no., Uid: " + uid
15568                                 + ", curProcstateSeq: " + record.curProcStateSeq
15569                                 + ", procStateSeq: " + procStateSeq);
15570                     }
15571                     return;
15572                 }
15573                 if (record.waitingForNetwork) {
15574                     if (DEBUG_NETWORK) {
15575                         Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid
15576                                 + ", procStateSeq: " + procStateSeq);
15577                     }
15578                     record.networkStateLock.notifyAll();
15579                 }
15580             }
15581         }
15582 
15583         @Override
isRuntimeRestarted()15584         public boolean isRuntimeRestarted() {
15585             return mSystemServiceManager.isRuntimeRestarted();
15586         }
15587 
15588         @Override
canStartMoreUsers()15589         public boolean canStartMoreUsers() {
15590             return mUserController.canStartMoreUsers();
15591         }
15592 
15593         @Override
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)15594         public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
15595             mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage);
15596         }
15597 
15598         @Override
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)15599         public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
15600             mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage);
15601         }
15602 
15603         @Override
getMaxRunningUsers()15604         public int getMaxRunningUsers() {
15605             return mUserController.getMaxRunningUsers();
15606         }
15607 
15608         @Override
isUidActive(int uid)15609         public boolean isUidActive(int uid) {
15610             synchronized (mProcLock) {
15611                 return isUidActiveLOSP(uid);
15612             }
15613         }
15614 
15615         @Override
getMemoryStateForProcesses()15616         public List<ProcessMemoryState> getMemoryStateForProcesses() {
15617             List<ProcessMemoryState> processMemoryStates = new ArrayList<>();
15618             synchronized (mPidsSelfLocked) {
15619                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
15620                     final ProcessRecord r = mPidsSelfLocked.valueAt(i);
15621                     processMemoryStates.add(new ProcessMemoryState(
15622                             r.uid, r.getPid(), r.processName, r.mState.getCurAdj()));
15623                 }
15624             }
15625             return processMemoryStates;
15626         }
15627 
15628         @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)15629         public int handleIncomingUser(int callingPid, int callingUid, int userId,
15630                 boolean allowAll, int allowMode, String name, String callerPackage) {
15631             return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
15632                     allowMode, name, callerPackage);
15633         }
15634 
15635         @Override
enforceCallingPermission(String permission, String func)15636         public void enforceCallingPermission(String permission, String func) {
15637             ActivityManagerService.this.enforceCallingPermission(permission, func);
15638         }
15639 
15640         @Override
getCurrentUserId()15641         public int getCurrentUserId() {
15642             return mUserController.getCurrentUserId();
15643         }
15644 
15645         @Override
isUserRunning(int userId, int flags)15646         public boolean isUserRunning(int userId, int flags) {
15647             // Holding am lock isn't required to call into user controller.
15648             return mUserController.isUserRunning(userId, flags);
15649         }
15650 
15651         @Override
trimApplications()15652         public void trimApplications() {
15653             ActivityManagerService.this.trimApplications(true, OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
15654         }
15655 
killProcessesForRemovedTask(ArrayList<Object> procsToKill)15656         public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) {
15657             synchronized (ActivityManagerService.this) {
15658                 for (int i = 0; i < procsToKill.size(); i++) {
15659                     final WindowProcessController wpc =
15660                             (WindowProcessController) procsToKill.get(i);
15661                     final ProcessRecord pr = (ProcessRecord) wpc.mOwner;
15662                     if (pr.mState.getSetSchedGroup() == ProcessList.SCHED_GROUP_BACKGROUND
15663                             && pr.mReceivers.numberOfCurReceivers() == 0) {
15664                         pr.killLocked("remove task", ApplicationExitInfo.REASON_USER_REQUESTED,
15665                                 ApplicationExitInfo.SUBREASON_UNKNOWN, true);
15666                     } else {
15667                         // We delay killing processes that are not in the background or running a
15668                         // receiver.
15669                         pr.setWaitingToKill("remove task");
15670                     }
15671                 }
15672             }
15673         }
15674 
15675         @Override
killProcess(String processName, int uid, String reason)15676         public void killProcess(String processName, int uid, String reason) {
15677             synchronized (ActivityManagerService.this) {
15678                 final ProcessRecord proc = getProcessRecordLocked(processName, uid);
15679                 if (proc != null) {
15680                     mProcessList.removeProcessLocked(proc, false /* callerWillRestart */,
15681                             true /* allowRestart */,  ApplicationExitInfo.REASON_OTHER, reason);
15682                 }
15683             }
15684         }
15685 
15686         @Override
hasRunningActivity(int uid, @Nullable String packageName)15687         public boolean hasRunningActivity(int uid, @Nullable String packageName) {
15688             if (packageName == null) return false;
15689 
15690             synchronized (mProcLock) {
15691                 return mProcessList.searchEachLruProcessesLOSP(true, app -> {
15692                     if (app.uid == uid
15693                             && app.getWindowProcessController().hasRunningActivity(packageName)) {
15694                         return Boolean.TRUE;
15695                     }
15696                     return null;
15697                 }) != null;
15698             }
15699         }
15700 
15701         @Override
updateOomAdj()15702         public void updateOomAdj() {
15703             synchronized (ActivityManagerService.this) {
15704                 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
15705             }
15706         }
15707 
15708         @Override
updateCpuStats()15709         public void updateCpuStats() {
15710             ActivityManagerService.this.updateCpuStats();
15711         }
15712 
15713         @Override
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)15714         public void updateBatteryStats(ComponentName activity, int uid, int userId,
15715                 boolean resumed) {
15716             ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed);
15717         }
15718 
15719         @Override
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)15720         public void updateActivityUsageStats(ComponentName activity, int userId, int event,
15721                 IBinder appToken, ComponentName taskRoot) {
15722             ActivityManagerService.this.updateActivityUsageStats(activity, userId, event,
15723                     appToken, taskRoot);
15724         }
15725 
15726         @Override
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)15727         public void updateForegroundTimeIfOnBattery(
15728                 String packageName, int uid, long cpuTimeDiff) {
15729             mBatteryStatsService.updateForegroundTimeIfOnBattery(packageName, uid, cpuTimeDiff);
15730         }
15731 
15732         @Override
sendForegroundProfileChanged(int userId)15733         public void sendForegroundProfileChanged(int userId) {
15734             mUserController.sendForegroundProfileChanged(userId);
15735         }
15736 
15737         @Override
shouldConfirmCredentials(int userId)15738         public boolean shouldConfirmCredentials(int userId) {
15739             return mUserController.shouldConfirmCredentials(userId);
15740         }
15741 
15742         @Override
noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)15743         public void noteAlarmFinish(PendingIntent ps, WorkSource workSource, int sourceUid,
15744                 String tag) {
15745             ActivityManagerService.this.noteAlarmFinish((ps != null) ? ps.getTarget() : null,
15746                     workSource, sourceUid, tag);
15747         }
15748 
15749         @Override
noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid, String tag)15750         public void noteAlarmStart(PendingIntent ps, WorkSource workSource, int sourceUid,
15751                 String tag) {
15752             ActivityManagerService.this.noteAlarmStart((ps != null) ? ps.getTarget() : null,
15753                     workSource, sourceUid, tag);
15754         }
15755 
15756         @Override
noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid, String sourcePkg, String tag)15757         public void noteWakeupAlarm(PendingIntent ps, WorkSource workSource, int sourceUid,
15758                 String sourcePkg, String tag) {
15759             ActivityManagerService.this.noteWakeupAlarm((ps != null) ? ps.getTarget() : null,
15760                     workSource, sourceUid, sourcePkg, tag);
15761         }
15762 
15763         @Override
isAppStartModeDisabled(int uid, String packageName)15764         public boolean isAppStartModeDisabled(int uid, String packageName) {
15765             return ActivityManagerService.this.isAppStartModeDisabled(uid, packageName);
15766         }
15767 
15768         @Override
getCurrentProfileIds()15769         public int[] getCurrentProfileIds() {
15770             return mUserController.getCurrentProfileIds();
15771         }
15772 
15773         @Override
getCurrentUser()15774         public UserInfo getCurrentUser() {
15775             return mUserController.getCurrentUser();
15776         }
15777 
15778         @Override
ensureNotSpecialUser(int userId)15779         public void ensureNotSpecialUser(int userId) {
15780             mUserController.ensureNotSpecialUser(userId);
15781         }
15782 
15783         @Override
isCurrentProfile(int userId)15784         public boolean isCurrentProfile(int userId) {
15785             return mUserController.isCurrentProfile(userId);
15786         }
15787 
15788         @Override
hasStartedUserState(int userId)15789         public boolean hasStartedUserState(int userId) {
15790             return mUserController.hasStartedUserState(userId);
15791         }
15792 
15793         @Override
finishUserSwitch(Object uss)15794         public void finishUserSwitch(Object uss) {
15795             mUserController.finishUserSwitch((UserState) uss);
15796         }
15797 
15798         @Override
scheduleAppGcs()15799         public void scheduleAppGcs() {
15800             synchronized (mAppProfiler.mProfilerLock) {
15801                 mAppProfiler.scheduleAppGcsLPf();
15802             }
15803         }
15804 
15805         @Override
getTaskIdForActivity(IBinder token, boolean onlyRoot)15806         public int getTaskIdForActivity(IBinder token, boolean onlyRoot) {
15807             return ActivityManagerService.this.getTaskForActivity(token, onlyRoot);
15808         }
15809 
15810         @Override
getActivityPresentationInfo(IBinder token)15811         public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
15812             final ActivityClient ac = ActivityClient.getInstance();
15813             return new ActivityPresentationInfo(ac.getTaskForActivity(token,
15814                     /*onlyRoot=*/ false), ac.getDisplayId(token),
15815                     mAtmInternal.getActivityName(token));
15816         }
15817 
15818         @Override
setBooting(boolean booting)15819         public void setBooting(boolean booting) {
15820             mBooting = booting;
15821         }
15822 
15823         @Override
isBooting()15824         public boolean isBooting() {
15825             return mBooting;
15826         }
15827 
15828         @Override
setBooted(boolean booted)15829         public void setBooted(boolean booted) {
15830             mBooted = booted;
15831         }
15832 
15833         @Override
isBooted()15834         public boolean isBooted() {
15835             return mBooted;
15836         }
15837 
15838         @Override
finishBooting()15839         public void finishBooting() {
15840             ActivityManagerService.this.finishBooting();
15841         }
15842 
15843         @Override
tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, int type, @ReasonCode int reasonCode, String reason)15844         public void tempAllowlistForPendingIntent(int callerPid, int callerUid, int targetUid,
15845                 long duration, int type, @ReasonCode int reasonCode, String reason) {
15846             synchronized (ActivityManagerService.this) {
15847                 ActivityManagerService.this.tempAllowlistForPendingIntentLocked(
15848                         callerPid, callerUid, targetUid, duration, type, reasonCode, reason);
15849             }
15850         }
15851 
15852         @Override
broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid, int realCallingUid, int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)15853         public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
15854                 int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
15855                 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras,
15856                 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky,
15857                 int userId, boolean allowBackgroundActivityStarts,
15858                 @Nullable IBinder backgroundActivityStartsToken) {
15859             synchronized (ActivityManagerService.this) {
15860                 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId,
15861                         uid, realCallingUid, realCallingPid, intent, resolvedType, resultTo,
15862                         resultCode, resultData, resultExtras, requiredPermission, bOptions,
15863                         serialized, sticky, userId, allowBackgroundActivityStarts,
15864                         backgroundActivityStartsToken);
15865             }
15866         }
15867 
15868         @Override
broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdAllowList, @Nullable Bundle bOptions)15869         public int broadcastIntent(Intent intent,
15870                 IIntentReceiver resultTo,
15871                 String[] requiredPermissions,
15872                 boolean serialized, int userId, int[] appIdAllowList, @Nullable Bundle bOptions) {
15873             synchronized (ActivityManagerService.this) {
15874                 intent = verifyBroadcastLocked(intent);
15875 
15876                 final int callingPid = Binder.getCallingPid();
15877                 final int callingUid = Binder.getCallingUid();
15878                 final long origId = Binder.clearCallingIdentity();
15879                 try {
15880                     return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/,
15881                             null /*callerPackage*/, null /*callingFeatureId*/, intent,
15882                             null /*resolvedType*/, resultTo, 0 /*resultCode*/, null /*resultData*/,
15883                             null /*resultExtras*/, requiredPermissions, null, AppOpsManager.OP_NONE,
15884                             bOptions /*options*/, serialized, false /*sticky*/, callingPid,
15885                             callingUid, callingUid, callingPid, userId,
15886                             false /*allowBackgroundStarts*/,
15887                             null /*tokenNeededForBackgroundActivityStarts*/, appIdAllowList);
15888                 } finally {
15889                     Binder.restoreCallingIdentity(origId);
15890                 }
15891             }
15892 
15893         }
15894 
15895         @Override
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)15896         public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType,
15897                 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId,
15898                 int userId, boolean allowBackgroundActivityStarts,
15899                 @Nullable IBinder backgroundActivityStartsToken)
15900                 throws TransactionTooLargeException {
15901             synchronized(ActivityManagerService.this) {
15902                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
15903                         "startServiceInPackage: " + service + " type=" + resolvedType);
15904                 final long origId = Binder.clearCallingIdentity();
15905                 ComponentName res;
15906                 try {
15907                     res = mServices.startServiceLocked(null, service,
15908                             resolvedType, -1, uid, fgRequired, callingPackage,
15909                             callingFeatureId, userId, allowBackgroundActivityStarts,
15910                             backgroundActivityStartsToken);
15911                 } finally {
15912                     Binder.restoreCallingIdentity(origId);
15913                 }
15914                 return res;
15915             }
15916         }
15917 
15918         // The arguments here are untyped because the base ActivityManagerInternal class
15919         // doesn't have compile-time visibility into ActivityServiceConnectionHolder or
15920         // ConnectionRecord.
15921         @Override
disconnectActivityFromServices(Object connectionHolder)15922         public void disconnectActivityFromServices(Object connectionHolder) {
15923             // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder
15924             final ActivityServiceConnectionsHolder holder =
15925                     (ActivityServiceConnectionsHolder) connectionHolder;
15926             synchronized (ActivityManagerService.this) {
15927                 synchronized (mProcLock) {
15928                     holder.forEachConnection(cr -> mServices.removeConnectionLocked(
15929                             (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */,
15930                             false /* enqueueOomAdj */));
15931                 }
15932             }
15933         }
15934 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)15935         public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
15936             synchronized(ActivityManagerService.this) {
15937                 mServices.cleanUpServices(userId, component, baseIntent);
15938             }
15939         }
15940 
getActivityInfoForUser(ActivityInfo aInfo, int userId)15941         public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
15942             // Locked intentionally not held as it isn't needed for this case.
15943             return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId);
15944         }
15945 
ensureBootCompleted()15946         public void ensureBootCompleted() {
15947             // Locked intentionally not held as it isn't needed for this case.
15948             ActivityManagerService.this.ensureBootCompleted();
15949         }
15950 
updateOomLevelsForDisplay(int displayId)15951         public void updateOomLevelsForDisplay(int displayId) {
15952             synchronized(ActivityManagerService.this) {
15953                 if (mWindowManager != null) {
15954                     mProcessList.applyDisplaySize(mWindowManager);
15955                 }
15956             }
15957         }
15958 
isActivityStartsLoggingEnabled()15959         public boolean isActivityStartsLoggingEnabled() {
15960             return mConstants.mFlagActivityStartsLoggingEnabled;
15961         }
15962 
isBackgroundActivityStartsEnabled()15963         public boolean isBackgroundActivityStartsEnabled() {
15964             return mConstants.mFlagBackgroundActivityStartsEnabled;
15965         }
15966 
reportCurKeyguardUsageEvent(boolean keyguardShowing)15967         public void reportCurKeyguardUsageEvent(boolean keyguardShowing) {
15968             ActivityManagerService.this.reportGlobalUsageEvent(keyguardShowing
15969                     ? UsageEvents.Event.KEYGUARD_SHOWN
15970                     : UsageEvents.Event.KEYGUARD_HIDDEN);
15971         }
15972 
15973         @Override
monitor()15974         public void monitor() {
15975             ActivityManagerService.this.monitor();
15976         }
15977 
15978         @Override
inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)15979         public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) {
15980             return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem, reason);
15981         }
15982 
15983         @Override
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)15984         public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
15985                 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
15986                 boolean aboveSystem, String reason) {
15987             return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc,
15988                     activityShortComponentName, aInfo, parentShortComponentName,
15989                     (WindowProcessController) parentProc, aboveSystem, reason);
15990 
15991         }
15992 
15993         @Override
inputDispatchingResumed(int pid)15994         public void inputDispatchingResumed(int pid) {
15995             // TODO (b/171218828)
15996             return;
15997         }
15998 
15999         @Override
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)16000         public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) {
16001             synchronized (ActivityManagerService.this) {
16002                 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
16003                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
16004                         | Intent.FLAG_RECEIVER_REPLACE_PENDING
16005                         | Intent.FLAG_RECEIVER_FOREGROUND
16006                         | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
16007                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
16008                         null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
16009                         Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
16010                 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
16011                     intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
16012                     intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
16013                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
16014                             | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
16015                     if (initLocale || !mProcessesReady) {
16016                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
16017                     }
16018                     final BroadcastOptions bOptions = BroadcastOptions.makeBasic();
16019                     bOptions.setTemporaryAppAllowlist(mInternal.getBootTimeTempAllowListDuration(),
16020                             TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
16021                             PowerExemptionManager.REASON_LOCALE_CHANGED, "");
16022                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
16023                             null, OP_NONE, bOptions.toBundle(), false, false, MY_PID, SYSTEM_UID,
16024                             Binder.getCallingUid(), Binder.getCallingPid(),
16025                             UserHandle.USER_ALL);
16026                 }
16027 
16028                 // Send a broadcast to PackageInstallers if the configuration change is interesting
16029                 // for the purposes of installing additional splits.
16030                 if (!initLocale && isSplitConfigurationChange(changes)) {
16031                     intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
16032                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
16033                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
16034 
16035                     // Typically only app stores will have this permission.
16036                     String[] permissions =
16037                             new String[] { android.Manifest.permission.INSTALL_PACKAGES };
16038                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null,
16039                             permissions, null, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
16040                             Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
16041                 }
16042             }
16043         }
16044 
16045         /**
16046          * Returns true if this configuration change is interesting enough to send an
16047          * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
16048          */
isSplitConfigurationChange(int configDiff)16049         private boolean isSplitConfigurationChange(int configDiff) {
16050             return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
16051         }
16052 
16053         @Override
broadcastCloseSystemDialogs(String reason)16054         public void broadcastCloseSystemDialogs(String reason) {
16055             synchronized (ActivityManagerService.this) {
16056                 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
16057                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
16058                         | Intent.FLAG_RECEIVER_FOREGROUND);
16059                 if (reason != null) {
16060                     intent.putExtra("reason", reason);
16061                 }
16062 
16063                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
16064                         null, OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
16065                         Binder.getCallingPid(), UserHandle.USER_ALL);
16066             }
16067         }
16068 
16069         @Override
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)16070         public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
16071             synchronized (ActivityManagerService.this) {
16072                 ActivityManagerService.this.killAllBackgroundProcessesExcept(
16073                         minTargetSdk, maxProcState);
16074             }
16075         }
16076 
16077         @Override
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)16078         public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
16079                 boolean isTop, String hostingType, ComponentName hostingName) {
16080             try {
16081                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
16082                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
16083                             + processName);
16084                 }
16085                 synchronized (ActivityManagerService.this) {
16086                     // If the process is known as top app, set a hint so when the process is
16087                     // started, the top priority can be applied immediately to avoid cpu being
16088                     // preempted by other processes before attaching the process of top app.
16089                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
16090                             new HostingRecord(hostingType, hostingName, isTop),
16091                             ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
16092                             false /* isolated */);
16093                 }
16094             } finally {
16095                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
16096             }
16097         }
16098 
16099         @Override
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)16100         public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
16101                 ProfilerInfo profilerInfo, Object wmLock) {
16102             synchronized (ActivityManagerService.this) {
16103                 /**
16104                  * This function is called from the window manager context and needs to be executed
16105                  * synchronously.  To avoid deadlock, we pass a message to AMS to execute the
16106                  * function and notify the passed in lock when it has been completed.
16107                  */
16108                 synchronized (wmLock) {
16109                     if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
16110                         setDebugApp(aInfo.processName, true, false);
16111                     }
16112 
16113                     if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
16114                         setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
16115                     }
16116 
16117                     if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
16118                         setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
16119                     }
16120 
16121                     if (profilerInfo != null) {
16122                         setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
16123                     }
16124                     wmLock.notify();
16125                 }
16126             }
16127         }
16128 
16129         @Override
getStorageMountMode(int pid, int uid)16130         public int getStorageMountMode(int pid, int uid) {
16131             if (uid == SHELL_UID || uid == ROOT_UID) {
16132                 return Zygote.MOUNT_EXTERNAL_DEFAULT;
16133             }
16134             synchronized (mPidsSelfLocked) {
16135                 final ProcessRecord pr = mPidsSelfLocked.get(pid);
16136                 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.getMountMode();
16137             }
16138         }
16139 
16140         @Override
isAppForeground(int uid)16141         public boolean isAppForeground(int uid) {
16142             return ActivityManagerService.this.isAppForeground(uid);
16143         }
16144 
16145         @Override
isAppBad(final String processName, final int uid)16146         public boolean isAppBad(final String processName, final int uid) {
16147             return ActivityManagerService.this.isAppBad(processName, uid);
16148         }
16149 
16150         @Override
clearPendingBackup(int userId)16151         public void clearPendingBackup(int userId) {
16152             ActivityManagerService.this.clearPendingBackup(userId);
16153         }
16154 
16155         /**
16156          * When power button is very long pressed, call this interface to do some pre-shutdown work
16157          * like persisting database etc.
16158          */
16159         @Override
prepareForPossibleShutdown()16160         public void prepareForPossibleShutdown() {
16161             ActivityManagerService.this.prepareForPossibleShutdown();
16162         }
16163 
16164         @Override
hasRunningForegroundService(int uid, int foregroundServicetype)16165         public boolean hasRunningForegroundService(int uid, int foregroundServicetype) {
16166             synchronized (ActivityManagerService.this) {
16167                 return mProcessList.searchEachLruProcessesLOSP(true, app -> {
16168                     if (app.uid != uid) {
16169                         return null;
16170                     }
16171 
16172                     if ((app.mServices.getForegroundServiceTypes() & foregroundServicetype) != 0) {
16173                         return Boolean.TRUE;
16174                     }
16175                     return null;
16176                 }) != null;
16177             }
16178         }
16179 
16180         @Override
16181         public boolean hasForegroundServiceNotification(String pkg, int userId,
16182                 String channelId) {
16183             synchronized (ActivityManagerService.this) {
16184                 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId);
16185             }
16186         }
16187 
16188         @Override
16189         public ServiceNotificationPolicy applyForegroundServiceNotification(
16190                 Notification notification, String tag, int id, String pkg, int userId) {
16191             synchronized (ActivityManagerService.this) {
16192                 return mServices.applyForegroundServiceNotificationLocked(notification,
16193                         tag, id, pkg, userId);
16194             }
16195         }
16196 
16197         @Override
16198         public void onForegroundServiceNotificationUpdate(boolean shown,
16199                 Notification notification, int id, String pkg, @UserIdInt int userId) {
16200             synchronized (ActivityManagerService.this) {
16201                 mServices.onForegroundServiceNotificationUpdateLocked(shown,
16202                         notification, id, pkg, userId);
16203             }
16204         }
16205 
16206         @Override
16207         public void stopForegroundServicesForChannel(String pkg, int userId,
16208                 String channelId) {
16209             synchronized (ActivityManagerService.this) {
16210                 mServices.stopForegroundServicesForChannelLocked(pkg, userId, channelId);
16211             }
16212         }
16213 
16214         @Override
16215         public void registerProcessObserver(IProcessObserver processObserver) {
16216             ActivityManagerService.this.registerProcessObserver(processObserver);
16217         }
16218 
16219         @Override
16220         public void unregisterProcessObserver(IProcessObserver processObserver) {
16221             ActivityManagerService.this.unregisterProcessObserver(processObserver);
16222         }
16223 
16224         @Override
16225         public boolean isUidCurrentlyInstrumented(int uid) {
16226             synchronized (mProcLock) {
16227                 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) {
16228                     ActiveInstrumentation activeInst = mActiveInstrumentation.get(i);
16229                     if (!activeInst.mFinished && activeInst.mTargetInfo != null
16230                             && activeInst.mTargetInfo.uid == uid) {
16231                         return true;
16232                     }
16233                 }
16234             }
16235             return false;
16236         }
16237 
16238         @Override
16239         public void setDeviceOwnerUid(int uid) {
16240             mDeviceOwnerUid = uid;
16241         }
16242 
16243         @Override
16244         public boolean isDeviceOwner(int uid) {
16245             int cachedUid = mDeviceOwnerUid;
16246             return uid >= 0 && cachedUid == uid;
16247         }
16248 
16249 
16250         @Override
16251         public void setProfileOwnerUid(ArraySet<Integer> profileOwnerUids) {
16252             synchronized (ActivityManagerService.this) {
16253                 mProfileOwnerUids = profileOwnerUids;
16254             }
16255         }
16256 
16257         @Override
16258         public boolean isProfileOwner(int uid) {
16259             synchronized (ActivityManagerService.this) {
16260                 return mProfileOwnerUids != null && mProfileOwnerUids.indexOf(uid) >= 0;
16261             }
16262         }
16263 
16264         @Override
16265         public void setCompanionAppUids(int userId, Set<Integer> companionAppUids) {
16266             synchronized (ActivityManagerService.this) {
16267                 mCompanionAppUidsMap.put(userId, companionAppUids);
16268             }
16269         }
16270 
16271         @Override
16272         public boolean isAssociatedCompanionApp(int userId, int uid) {
16273             final Set<Integer> allUids = mCompanionAppUidsMap.get(userId);
16274             if (allUids == null) {
16275                 return false;
16276             }
16277             return allUids.contains(uid);
16278         }
16279 
16280         @Override
16281         public void addPendingTopUid(int uid, int pid) {
16282             mPendingStartActivityUids.add(uid, pid);
16283         }
16284 
16285         @Override
16286         public void deletePendingTopUid(int uid) {
16287             mPendingStartActivityUids.delete(uid);
16288         }
16289 
16290         @Override
16291         public boolean isPendingTopUid(int uid) {
16292             return mPendingStartActivityUids.isPendingTopUid(uid);
16293         }
16294 
16295         @Override
16296         public Intent getIntentForIntentSender(IIntentSender sender) {
16297             return ActivityManagerService.this.getIntentForIntentSender(sender);
16298         }
16299 
16300         @Override
16301         public PendingIntent getPendingIntentActivityAsApp(
16302                 int requestCode, @NonNull Intent intent, int flags, Bundle options,
16303                 String ownerPkg, int ownerUid) {
16304             return getPendingIntentActivityAsApp(requestCode, new Intent[] { intent }, flags,
16305                     options, ownerPkg, ownerUid);
16306         }
16307 
16308         @Override
16309         public PendingIntent getPendingIntentActivityAsApp(
16310                 int requestCode, @NonNull Intent[] intents, int flags, Bundle options,
16311                 String ownerPkg, int ownerUid) {
16312             // system callers must explicitly set mutability state
16313             final boolean flagImmutableSet = (flags & PendingIntent.FLAG_IMMUTABLE) != 0;
16314             final boolean flagMutableSet = (flags & PendingIntent.FLAG_MUTABLE) != 0;
16315             if (flagImmutableSet == flagMutableSet) {
16316                 throw new IllegalArgumentException(
16317                         "Must set exactly one of FLAG_IMMUTABLE or FLAG_MUTABLE");
16318             }
16319 
16320             final Context context = ActivityManagerService.this.mContext;
16321             final ContentResolver resolver = context.getContentResolver();
16322             final int len = intents.length;
16323             final String[] resolvedTypes = new String[len];
16324             for (int i = 0; i < len; i++) {
16325                 final Intent intent = intents[i];
16326                 resolvedTypes[i] = intent.resolveTypeIfNeeded(resolver);
16327                 intent.migrateExtraStreamToClipData(context);
16328                 intent.prepareToLeaveProcess(context);
16329             }
16330             IIntentSender target =
16331                     ActivityManagerService.this.getIntentSenderWithFeatureAsApp(
16332                             INTENT_SENDER_ACTIVITY, ownerPkg,
16333                             context.getAttributionTag(), null, null, requestCode,
16334                             intents,
16335                             resolvedTypes,
16336                             flags, options, UserHandle.getUserId(ownerUid), ownerUid);
16337             return target != null ? new PendingIntent(target) : null;
16338         }
16339 
16340         @Override
16341         public long getBootTimeTempAllowListDuration() {
16342             // Do not lock ActivityManagerService.this here, this API is called by
16343             // PackageManagerService.
16344             return mConstants.mBootTimeTempAllowlistDuration;
16345         }
16346 
16347         @Override
16348         public void registerAnrController(AnrController controller) {
16349             mActivityTaskManager.registerAnrController(controller);
16350         }
16351 
16352         @Override
16353         public void unregisterAnrController(AnrController controller) {
16354             mActivityTaskManager.unregisterAnrController(controller);
16355         }
16356 
16357         @Override
16358         public boolean canStartForegroundService(int pid, int uid, @NonNull String packageName) {
16359             synchronized (ActivityManagerService.this) {
16360                 return mServices.canStartForegroundServiceLocked(pid, uid, packageName);
16361             }
16362         }
16363 
16364         @Override
16365         public void tempAllowWhileInUsePermissionInFgs(int uid, long durationMs) {
16366             mFgsWhileInUseTempAllowList.add(uid, durationMs, "");
16367         }
16368 
16369         @Override
16370         public boolean isTempAllowlistedForFgsWhileInUse(int uid) {
16371             return mFgsWhileInUseTempAllowList.isAllowed(uid);
16372         }
16373 
16374         @Override
16375         public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid,
16376                 @NonNull String packageName) {
16377             synchronized (ActivityManagerService.this) {
16378                 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName);
16379             }
16380         }
16381 
16382         @Override
16383         public @TempAllowListType int getPushMessagingOverQuotaBehavior() {
16384             synchronized (ActivityManagerService.this) {
16385                 return mConstants.mPushMessagingOverQuotaBehavior;
16386             }
16387         }
16388 
16389         @Override
16390         public int getUidCapability(int uid) {
16391             synchronized (ActivityManagerService.this) {
16392                 UidRecord uidRecord = mProcessList.getUidRecordLOSP(uid);
16393                 if (uidRecord == null) {
16394                     throw new IllegalArgumentException("uid record for " + uid + " not found");
16395                 }
16396                 return uidRecord.getCurCapability();
16397             }
16398         }
16399 
16400         /**
16401          * @return The PID list of the isolated process with packages matching the given uid.
16402          */
16403         @Nullable
16404         public List<Integer> getIsolatedProcesses(int uid) {
16405             synchronized (ActivityManagerService.this) {
16406                 return mProcessList.getIsolatedProcessesLocked(uid);
16407             }
16408         }
16409 
16410         /** @see ActivityManagerService#sendIntentSender */
16411         @Override
16412         public int sendIntentSender(IIntentSender target, IBinder allowlistToken, int code,
16413                 Intent intent, String resolvedType,
16414                 IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
16415             return ActivityManagerService.this.sendIntentSender(target, allowlistToken, code,
16416                     intent, resolvedType, finishedReceiver, requiredPermission, options);
16417         }
16418 
16419         @Override
16420         public void setVoiceInteractionManagerProvider(
16421                 @Nullable ActivityManagerInternal.VoiceInteractionManagerProvider provider) {
16422             ActivityManagerService.this.setVoiceInteractionManagerProvider(provider);
16423         }
16424 
16425         @Override
16426         public void setStopUserOnSwitch(int value) {
16427             ActivityManagerService.this.setStopUserOnSwitch(value);
16428         }
16429     }
16430 
16431     long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
16432         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
16433             throw new SecurityException("Requires permission " + FILTER_EVENTS);
16434         }
16435         ProcessRecord proc;
16436         synchronized (mPidsSelfLocked) {
16437             proc = mPidsSelfLocked.get(pid);
16438         }
16439         final long timeoutMillis = proc != null ? proc.getInputDispatchingTimeoutMillis() :
16440                 DEFAULT_DISPATCHING_TIMEOUT_MILLIS;
16441 
16442         if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) {
16443             return 0;
16444         }
16445 
16446         return timeoutMillis;
16447     }
16448 
16449     /**
16450      * Handle input dispatching timeouts.
16451      * @return whether input dispatching should be aborted or not.
16452      */
16453     boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName,
16454             ApplicationInfo aInfo, String parentShortComponentName,
16455             WindowProcessController parentProcess, boolean aboveSystem, String reason) {
16456         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
16457             throw new SecurityException("Requires permission " + FILTER_EVENTS);
16458         }
16459 
16460         final String annotation;
16461         if (reason == null) {
16462             annotation = "Input dispatching timed out";
16463         } else {
16464             annotation = "Input dispatching timed out (" + reason + ")";
16465         }
16466 
16467         if (proc != null) {
16468             synchronized (this) {
16469                 if (proc.isDebugging()) {
16470                     return false;
16471                 }
16472 
16473                 if (proc.getActiveInstrumentation() != null) {
16474                     Bundle info = new Bundle();
16475                     info.putString("shortMsg", "keyDispatchingTimedOut");
16476                     info.putString("longMsg", annotation);
16477                     finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
16478                     return true;
16479                 }
16480             }
16481             mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo,
16482                     parentShortComponentName, parentProcess, aboveSystem, annotation);
16483         }
16484 
16485         return true;
16486     }
16487 
16488     /**
16489      * Called by app main thread to wait for the network policy rules to get updated.
16490      *
16491      * @param procStateSeq The sequence number indicating the process state change that the main
16492      *                     thread is interested in.
16493      */
16494     @Override
16495     public void waitForNetworkStateUpdate(long procStateSeq) {
16496         final int callingUid = Binder.getCallingUid();
16497         if (DEBUG_NETWORK) {
16498             Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq);
16499         }
16500         UidRecord record;
16501         synchronized (mProcLock) {
16502             record = mProcessList.getUidRecordLOSP(callingUid);
16503             if (record == null) {
16504                 return;
16505             }
16506         }
16507         synchronized (record.networkStateLock) {
16508             if (record.lastDispatchedProcStateSeq < procStateSeq) {
16509                 if (DEBUG_NETWORK) {
16510                     Slog.d(TAG_NETWORK, "Uid state change for seq no. " + procStateSeq + " is not "
16511                             + "dispatched to NPMS yet, so don't wait. Uid: " + callingUid
16512                             + " lastProcStateSeqDispatchedToObservers: "
16513                             + record.lastDispatchedProcStateSeq);
16514                 }
16515                 return;
16516             }
16517             if (record.curProcStateSeq > procStateSeq) {
16518                 if (DEBUG_NETWORK) {
16519                     Slog.d(TAG_NETWORK, "Ignore the wait requests for older seq numbers. Uid: "
16520                             + callingUid + ", curProcStateSeq: " + record.curProcStateSeq
16521                             + ", procStateSeq: " + procStateSeq);
16522                 }
16523                 return;
16524             }
16525             if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
16526                 if (DEBUG_NETWORK) {
16527                     Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. "
16528                             + procStateSeq + ", so no need to wait. Uid: "
16529                             + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: "
16530                             + record.lastNetworkUpdatedProcStateSeq);
16531                 }
16532                 return;
16533             }
16534             try {
16535                 if (DEBUG_NETWORK) {
16536                     Slog.d(TAG_NETWORK, "Starting to wait for the network rules update."
16537                         + " Uid: " + callingUid + " procStateSeq: " + procStateSeq);
16538                 }
16539                 final long startTime = SystemClock.uptimeMillis();
16540                 record.waitingForNetwork = true;
16541                 record.networkStateLock.wait(mWaitForNetworkTimeoutMs);
16542                 record.waitingForNetwork = false;
16543                 final long totalTime = SystemClock.uptimeMillis() - startTime;
16544                 if (totalTime >= mWaitForNetworkTimeoutMs || DEBUG_NETWORK) {
16545                     Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: "
16546                             + totalTime + ". Uid: " + callingUid + " procStateSeq: "
16547                             + procStateSeq + " UidRec: " + record
16548                             + " validateUidRec: "
16549                             + mUidObserverController.getValidateUidRecord(callingUid));
16550                 }
16551             } catch (InterruptedException e) {
16552                 Thread.currentThread().interrupt();
16553             }
16554         }
16555     }
16556 
16557     @Override
16558     public void waitForBroadcastIdle() {
16559         waitForBroadcastIdle(/* printWriter= */ null);
16560     }
16561 
16562     public void waitForBroadcastIdle(@Nullable PrintWriter pw) {
16563         enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()");
16564         while (true) {
16565             boolean idle = true;
16566             synchronized (this) {
16567                 for (BroadcastQueue queue : mBroadcastQueues) {
16568                     if (!queue.isIdle()) {
16569                         final String msg = "Waiting for queue " + queue + " to become idle...";
16570                         if (pw != null) {
16571                             pw.println(msg);
16572                             pw.println(queue.describeState());
16573                             pw.flush();
16574                         }
16575                         Slog.v(TAG, msg);
16576                         queue.cancelDeferrals();
16577                         idle = false;
16578                     }
16579                 }
16580             }
16581 
16582             if (idle) {
16583                 final String msg = "All broadcast queues are idle!";
16584                 if (pw != null) {
16585                     pw.println(msg);
16586                     pw.flush();
16587                 }
16588                 Slog.v(TAG, msg);
16589                 return;
16590             } else {
16591                 SystemClock.sleep(1000);
16592             }
16593         }
16594     }
16595 
16596     /**
16597      * Force the settings cache to be loaded
16598      */
16599     void refreshSettingsCache() {
16600         mCoreSettingsObserver.onChange(true);
16601     }
16602 
16603     /**
16604      * Kill processes for the user with id userId and that depend on the package named packageName
16605      */
16606     @Override
16607     public void killPackageDependents(String packageName, int userId) {
16608         enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()");
16609         if (packageName == null) {
16610             throw new NullPointerException(
16611                     "Cannot kill the dependents of a package without its name.");
16612         }
16613 
16614         final long callingId = Binder.clearCallingIdentity();
16615         IPackageManager pm = AppGlobals.getPackageManager();
16616         int pkgUid = -1;
16617         try {
16618             pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
16619         } catch (RemoteException e) {
16620         }
16621         if (userId != UserHandle.USER_ALL && pkgUid == -1) {
16622             throw new IllegalArgumentException(
16623                     "Cannot kill dependents of non-existing package " + packageName);
16624         }
16625         try {
16626             synchronized(this) {
16627                 synchronized (mProcLock) {
16628                     mProcessList.killPackageProcessesLSP(packageName, UserHandle.getAppId(pkgUid),
16629                             userId, ProcessList.FOREGROUND_APP_ADJ,
16630                             ApplicationExitInfo.REASON_DEPENDENCY_DIED,
16631                             ApplicationExitInfo.SUBREASON_UNKNOWN,
16632                             "dep: " + packageName);
16633                 }
16634             }
16635         } finally {
16636             Binder.restoreCallingIdentity(callingId);
16637         }
16638     }
16639 
16640     @Override
16641     public int restartUserInBackground(final int userId) {
16642         return mUserController.restartUser(userId, /* foreground */ false);
16643     }
16644 
16645     @Override
16646     public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) {
16647         enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
16648                 "scheduleApplicationInfoChanged()");
16649 
16650         final long origId = Binder.clearCallingIdentity();
16651         try {
16652             final boolean updateFrameworkRes = packageNames.contains("android");
16653             synchronized (mProcLock) {
16654                 updateApplicationInfoLOSP(packageNames, updateFrameworkRes, userId);
16655             }
16656 
16657             AppWidgetManagerInternal widgets = LocalServices.getService(
16658                     AppWidgetManagerInternal.class);
16659             if (widgets != null) {
16660                 widgets.applyResourceOverlaysToWidgets(new HashSet<>(packageNames), userId,
16661                         updateFrameworkRes);
16662             }
16663         } finally {
16664             Binder.restoreCallingIdentity(origId);
16665         }
16666     }
16667 
16668     /**
16669      * Synchronously update the system ActivityThread, bypassing any deferred threading so any
16670      * resources and overlaid values are available immediately.
16671      */
16672     public void updateSystemUiContext() {
16673         final PackageManagerInternal packageManagerInternal = getPackageManagerInternal();
16674 
16675         ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android",
16676                 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM);
16677         ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai);
16678     }
16679 
16680     @GuardedBy(anyOf = {"this", "mProcLock"})
16681     private void updateApplicationInfoLOSP(@NonNull List<String> packagesToUpdate,
16682             boolean updateFrameworkRes, int userId) {
16683         if (updateFrameworkRes) {
16684             ParsingPackageUtils.readConfigUseRoundIcon(null);
16685         }
16686 
16687         mProcessList.updateApplicationInfoLOSP(packagesToUpdate, userId, updateFrameworkRes);
16688 
16689         if (updateFrameworkRes) {
16690             // Update system server components that need to know about changed overlays. Because the
16691             // overlay is applied in ActivityThread, we need to serialize through its thread too.
16692             final Executor executor = ActivityThread.currentActivityThread().getExecutor();
16693             final DisplayManagerInternal display =
16694                     LocalServices.getService(DisplayManagerInternal.class);
16695             if (display != null) {
16696                 executor.execute(display::onOverlayChanged);
16697             }
16698             if (mWindowManager != null) {
16699                 executor.execute(mWindowManager::onOverlayChanged);
16700             }
16701         }
16702     }
16703 
16704     /**
16705      * Update the binder call heavy hitter watcher per the new configuration
16706      */
16707     void scheduleUpdateBinderHeavyHitterWatcherConfig() {
16708         // There are two sets of configs: the default watcher and the auto sampler,
16709         // the default one takes precedence. System would kick off auto sampler when there is
16710         // an anomaly (i.e., consecutive ANRs), but it'll be stopped automatically after a while.
16711         mHandler.post(() -> {
16712             final boolean enabled;
16713             final int batchSize;
16714             final float threshold;
16715             final BinderCallHeavyHitterListener listener;
16716             synchronized (mProcLock) {
16717                 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
16718                     // Default watcher takes precedence, ignore the auto sampler.
16719                     mHandler.removeMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG);
16720                     // Set the watcher with the default watcher's config
16721                     enabled = true;
16722                     batchSize = mConstants.BINDER_HEAVY_HITTER_WATCHER_BATCHSIZE;
16723                     threshold = mConstants.BINDER_HEAVY_HITTER_WATCHER_THRESHOLD;
16724                     listener = (a, b, c, d) -> mHandler.post(
16725                             () -> handleBinderHeavyHitters(a, b, c, d));
16726                 } else if (mHandler.hasMessages(BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG)) {
16727                     // There is an ongoing auto sampler session, update it
16728                     enabled = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED;
16729                     batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
16730                     threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
16731                     listener = (a, b, c, d) -> mHandler.post(
16732                             () -> handleBinderHeavyHitters(a, b, c, d));
16733                 } else {
16734                     // Stop it
16735                     enabled = false;
16736                     batchSize = 0;
16737                     threshold = 0.0f;
16738                     listener = null;
16739                 }
16740             }
16741             Binder.setHeavyHitterWatcherConfig(enabled, batchSize, threshold, listener);
16742         });
16743     }
16744 
16745     /**
16746      * Kick off the watcher to run for given timeout, it could be throttled however.
16747      */
16748     void scheduleBinderHeavyHitterAutoSampler() {
16749         mHandler.post(() -> {
16750             final int batchSize;
16751             final float threshold;
16752             final long now;
16753             synchronized (mProcLock) {
16754                 if (!mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_ENABLED) {
16755                     // It's configured OFF
16756                     return;
16757                 }
16758                 if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
16759                     // If the default watcher is active already, don't start the auto sampler
16760                     return;
16761                 }
16762                 now = SystemClock.uptimeMillis();
16763                 if (mLastBinderHeavyHitterAutoSamplerStart
16764                         + BINDER_HEAVY_HITTER_AUTO_SAMPLER_THROTTLE_MS > now) {
16765                     // Too frequent, throttle it
16766                     return;
16767                 }
16768                 batchSize = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_BATCHSIZE;
16769                 threshold = mConstants.BINDER_HEAVY_HITTER_AUTO_SAMPLER_THRESHOLD;
16770             }
16771             // No lock is needed because we are accessing these variables in handle thread only.
16772             mLastBinderHeavyHitterAutoSamplerStart = now;
16773             // Start the watcher with the auto sampler's config.
16774             Binder.setHeavyHitterWatcherConfig(true, batchSize, threshold,
16775                     (a, b, c, d) -> mHandler.post(() -> handleBinderHeavyHitters(a, b, c, d)));
16776             // Schedule to stop it after given timeout.
16777             mHandler.sendMessageDelayed(mHandler.obtainMessage(
16778                     BINDER_HEAVYHITTER_AUTOSAMPLER_TIMEOUT_MSG),
16779                     BINDER_HEAVY_HITTER_AUTO_SAMPLER_DURATION_MS);
16780         });
16781     }
16782 
16783     /**
16784      * Stop the binder heavy hitter auto sampler after given timeout.
16785      */
16786     private void handleBinderHeavyHitterAutoSamplerTimeOut() {
16787         synchronized (mProcLock) {
16788             if (mConstants.BINDER_HEAVY_HITTER_WATCHER_ENABLED) {
16789                 // The default watcher is ON, don't bother to stop it.
16790                 return;
16791             }
16792         }
16793         Binder.setHeavyHitterWatcherConfig(false, 0, 0.0f, null);
16794     }
16795 
16796     /**
16797      * Handle the heavy hitters
16798      */
16799     private void handleBinderHeavyHitters(@NonNull final List<HeavyHitterContainer> hitters,
16800             final int totalBinderCalls, final float threshold, final long timeSpan) {
16801         final int size = hitters.size();
16802         if (size == 0) {
16803             return;
16804         }
16805         // Simply log it for now
16806         final String pfmt = "%.1f%%";
16807         final BinderTransactionNameResolver resolver = new BinderTransactionNameResolver();
16808         final StringBuilder sb = new StringBuilder("Excessive incoming binder calls(>")
16809                 .append(String.format(pfmt, threshold * 100))
16810                 .append(',').append(totalBinderCalls)
16811                 .append(',').append(timeSpan)
16812                 .append("ms): ");
16813         for (int i = 0; i < size; i++) {
16814             if (i > 0) {
16815                 sb.append(", ");
16816             }
16817             final HeavyHitterContainer container = hitters.get(i);
16818             sb.append('[').append(container.mUid)
16819                     .append(',').append(container.mClass.getName())
16820                     .append(',').append(resolver.getMethodName(container.mClass, container.mCode))
16821                     .append(',').append(container.mCode)
16822                     .append(',').append(String.format(pfmt, container.mFrequency * 100))
16823                     .append(']');
16824         }
16825         Slog.w(TAG, sb.toString());
16826     }
16827 
16828     /**
16829      * Attach an agent to the specified process (proces name or PID)
16830      */
16831     public void attachAgent(String process, String path) {
16832         try {
16833             synchronized (mProcLock) {
16834                 ProcessRecord proc = findProcessLOSP(process, UserHandle.USER_SYSTEM,
16835                         "attachAgent");
16836                 IApplicationThread thread;
16837                 if (proc == null || (thread = proc.getThread()) == null) {
16838                     throw new IllegalArgumentException("Unknown process: " + process);
16839                 }
16840 
16841                 if (!Build.IS_DEBUGGABLE) {
16842                     if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
16843                         throw new SecurityException("Process not debuggable: " + proc);
16844                     }
16845                 }
16846 
16847                 thread.attachAgent(path);
16848             }
16849         } catch (RemoteException e) {
16850             throw new IllegalStateException("Process disappeared");
16851         }
16852     }
16853 
16854     /**
16855      * When power button is very long pressed, call this interface to do some pre-shutdown work
16856      * like persisting database etc.
16857      */
16858     public void prepareForPossibleShutdown() {
16859         if (mUsageStatsService != null) {
16860             mUsageStatsService.prepareForPossibleShutdown();
16861         }
16862     }
16863 
16864     @VisibleForTesting
16865     public static class Injector {
16866         private NetworkManagementInternal mNmi;
16867         private Context mContext;
16868 
16869         public Injector(Context context) {
16870             mContext = context;
16871         }
16872 
16873         public Context getContext() {
16874             return mContext;
16875         }
16876 
16877         public AppOpsService getAppOpsService(File file, Handler handler) {
16878             return new AppOpsService(file, handler, getContext());
16879         }
16880 
16881         public Handler getUiHandler(ActivityManagerService service) {
16882             return service.new UiHandler();
16883         }
16884 
16885         public boolean isNetworkRestrictedForUid(int uid) {
16886             if (ensureHasNetworkManagementInternal()) {
16887                 return mNmi.isNetworkRestrictedForUid(uid);
16888             }
16889             return false;
16890         }
16891 
16892         /**
16893          * Return the process list instance
16894          */
16895         public ProcessList getProcessList(ActivityManagerService service) {
16896             return new ProcessList();
16897         }
16898 
16899         private boolean ensureHasNetworkManagementInternal() {
16900             if (mNmi == null) {
16901                 mNmi = LocalServices.getService(NetworkManagementInternal.class);
16902             }
16903             return mNmi != null;
16904         }
16905     }
16906 
16907     @Override
16908     public void startDelegateShellPermissionIdentity(int delegateUid,
16909             @Nullable String[] permissions) {
16910         if (UserHandle.getCallingAppId() != Process.SHELL_UID
16911                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
16912             throw new SecurityException("Only the shell can delegate its permissions");
16913         }
16914 
16915         // We allow delegation only to one instrumentation started from the shell
16916         synchronized (mProcLock) {
16917             // If the delegate is already set up for the target UID, nothing to do.
16918             if (mAppOpsService.getAppOpsServiceDelegate() != null) {
16919                 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) {
16920                     throw new IllegalStateException("Bad shell delegate state");
16921                 }
16922                 final ShellDelegate delegate = (ShellDelegate) mAppOpsService
16923                         .getAppOpsServiceDelegate();
16924                 if (delegate.getDelegateUid() != delegateUid) {
16925                     throw new SecurityException("Shell can delegate permissions only "
16926                             + "to one instrumentation at a time");
16927                 }
16928             }
16929 
16930             final int instrCount = mActiveInstrumentation.size();
16931             for (int i = 0; i < instrCount; i++) {
16932                 final ActiveInstrumentation instr = mActiveInstrumentation.get(i);
16933                 if (instr.mTargetInfo.uid != delegateUid) {
16934                     continue;
16935                 }
16936                 // If instrumentation started from the shell the connection is not null
16937                 if (instr.mUiAutomationConnection == null) {
16938                     throw new SecurityException("Shell can delegate its permissions" +
16939                             " only to an instrumentation started from the shell");
16940                 }
16941 
16942                 // Hook them up...
16943                 final ShellDelegate shellDelegate = new ShellDelegate(delegateUid,
16944                         permissions);
16945                 mAppOpsService.setAppOpsServiceDelegate(shellDelegate);
16946                 final String packageName = instr.mTargetInfo.packageName;
16947                 final List<String> permissionNames = permissions != null ?
16948                         Arrays.asList(permissions) : null;
16949                 getPermissionManagerInternal().startShellPermissionIdentityDelegation(
16950                         delegateUid, packageName, permissionNames);
16951                 return;
16952             }
16953         }
16954     }
16955 
16956     @Override
16957     public void stopDelegateShellPermissionIdentity() {
16958         if (UserHandle.getCallingAppId() != Process.SHELL_UID
16959                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
16960             throw new SecurityException("Only the shell can delegate its permissions");
16961         }
16962         synchronized (mProcLock) {
16963             mAppOpsService.setAppOpsServiceDelegate(null);
16964             getPermissionManagerInternal().stopShellPermissionIdentityDelegation();
16965         }
16966     }
16967 
16968     @Override
16969     public List<String> getDelegatedShellPermissions() {
16970         if (UserHandle.getCallingAppId() != Process.SHELL_UID
16971                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
16972             throw new SecurityException("Only the shell can get delegated permissions");
16973         }
16974         synchronized (mProcLock) {
16975             return getPermissionManagerInternal().getDelegatedShellPermissions();
16976         }
16977     }
16978 
16979     private class ShellDelegate implements CheckOpsDelegate {
16980         private final int mTargetUid;
16981         @Nullable
16982         private final String[] mPermissions;
16983 
16984         ShellDelegate(int targetUid, @Nullable String[] permissions) {
16985             mTargetUid = targetUid;
16986             mPermissions = permissions;
16987         }
16988 
16989         int getDelegateUid() {
16990             return mTargetUid;
16991         }
16992 
16993         @Override
16994         public int checkOperation(int code, int uid, String packageName,
16995                 String attributionTag, boolean raw,
16996                 QuintFunction<Integer, Integer, String, String, Boolean, Integer> superImpl) {
16997             if (uid == mTargetUid && isTargetOp(code)) {
16998                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
16999                         Process.SHELL_UID);
17000                 final long identity = Binder.clearCallingIdentity();
17001                 try {
17002                     return superImpl.apply(code, shellUid, "com.android.shell", null, raw);
17003                 } finally {
17004                     Binder.restoreCallingIdentity(identity);
17005                 }
17006             }
17007             return superImpl.apply(code, uid, packageName, attributionTag, raw);
17008         }
17009 
17010         @Override
17011         public int checkAudioOperation(int code, int usage, int uid, String packageName,
17012                 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) {
17013             if (uid == mTargetUid && isTargetOp(code)) {
17014                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
17015                         Process.SHELL_UID);
17016                 final long identity = Binder.clearCallingIdentity();
17017                 try {
17018                     return superImpl.apply(code, usage, shellUid, "com.android.shell");
17019                 } finally {
17020                     Binder.restoreCallingIdentity(identity);
17021                 }
17022             }
17023             return superImpl.apply(code, usage, uid, packageName);
17024         }
17025 
17026         @Override
17027         public SyncNotedAppOp noteOperation(int code, int uid, @Nullable String packageName,
17028                 @Nullable String featureId, boolean shouldCollectAsyncNotedOp,
17029                 @Nullable String message, boolean shouldCollectMessage,
17030                 @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean,
17031                         SyncNotedAppOp> superImpl) {
17032             if (uid == mTargetUid && isTargetOp(code)) {
17033                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
17034                         Process.SHELL_UID);
17035                 final long identity = Binder.clearCallingIdentity();
17036                 try {
17037                     return superImpl.apply(code, shellUid, "com.android.shell", featureId,
17038                             shouldCollectAsyncNotedOp, message, shouldCollectMessage);
17039                 } finally {
17040                     Binder.restoreCallingIdentity(identity);
17041                 }
17042             }
17043             return superImpl.apply(code, uid, packageName, featureId, shouldCollectAsyncNotedOp,
17044                     message, shouldCollectMessage);
17045         }
17046 
17047         @Override
17048         public SyncNotedAppOp noteProxyOperation(int code,
17049                 @NonNull AttributionSource attributionSource, boolean shouldCollectAsyncNotedOp,
17050                 @Nullable String message, boolean shouldCollectMessage, boolean skiProxyOperation,
17051                 @NonNull HexFunction<Integer, AttributionSource, Boolean, String, Boolean,
17052                                 Boolean, SyncNotedAppOp> superImpl) {
17053             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
17054                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
17055                         attributionSource.getUid()), Process.SHELL_UID);
17056                 final long identity = Binder.clearCallingIdentity();
17057                 try {
17058                     return superImpl.apply(code, new AttributionSource(shellUid,
17059                             "com.android.shell", attributionSource.getAttributionTag(),
17060                             attributionSource.getToken(), attributionSource.getNext()),
17061                             shouldCollectAsyncNotedOp, message, shouldCollectMessage,
17062                             skiProxyOperation);
17063                 } finally {
17064                     Binder.restoreCallingIdentity(identity);
17065                 }
17066             }
17067             return superImpl.apply(code, attributionSource, shouldCollectAsyncNotedOp,
17068                     message, shouldCollectMessage, skiProxyOperation);
17069         }
17070 
17071         @Override
17072         public SyncNotedAppOp startOperation(IBinder token, int code, int uid,
17073                 @Nullable String packageName, @Nullable String attributionTag,
17074                 boolean startIfModeDefault, boolean shouldCollectAsyncNotedOp,
17075                 @Nullable String message, boolean shouldCollectMessage,
17076                 @AttributionFlags int attributionFlags, int attributionChainId,
17077                 @NonNull UndecFunction<IBinder, Integer, Integer, String, String, Boolean,
17078                         Boolean, String, Boolean, Integer, Integer, SyncNotedAppOp> superImpl) {
17079             if (uid == mTargetUid && isTargetOp(code)) {
17080                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
17081                         Process.SHELL_UID);
17082                 final long identity = Binder.clearCallingIdentity();
17083                 try {
17084                     return superImpl.apply(token, code, shellUid, "com.android.shell",
17085                             attributionTag, startIfModeDefault, shouldCollectAsyncNotedOp, message,
17086                             shouldCollectMessage, attributionFlags, attributionChainId);
17087                 } finally {
17088                     Binder.restoreCallingIdentity(identity);
17089                 }
17090             }
17091             return superImpl.apply(token, code, uid, packageName, attributionTag,
17092                     startIfModeDefault, shouldCollectAsyncNotedOp, message, shouldCollectMessage,
17093                     attributionFlags, attributionChainId);
17094         }
17095 
17096         @Override
17097         public SyncNotedAppOp startProxyOperation(int code,
17098                 @NonNull AttributionSource attributionSource, boolean startIfModeDefault,
17099                 boolean shouldCollectAsyncNotedOp, String message, boolean shouldCollectMessage,
17100                 boolean skipProxyOperation, @AttributionFlags int proxyAttributionFlags,
17101                 @AttributionFlags int proxiedAttributionFlags, int attributionChainId,
17102                 @NonNull DecFunction<Integer, AttributionSource, Boolean, Boolean, String, Boolean,
17103                         Boolean, Integer, Integer, Integer, SyncNotedAppOp> superImpl) {
17104             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
17105                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
17106                         attributionSource.getUid()), Process.SHELL_UID);
17107                 final long identity = Binder.clearCallingIdentity();
17108                 try {
17109                     return superImpl.apply(code, new AttributionSource(shellUid,
17110                             "com.android.shell", attributionSource.getAttributionTag(),
17111                             attributionSource.getToken(), attributionSource.getNext()),
17112                             startIfModeDefault, shouldCollectAsyncNotedOp, message,
17113                             shouldCollectMessage, skipProxyOperation, proxyAttributionFlags,
17114                             proxiedAttributionFlags, attributionChainId);
17115                 } finally {
17116                     Binder.restoreCallingIdentity(identity);
17117                 }
17118             }
17119             return superImpl.apply(code, attributionSource, startIfModeDefault,
17120                     shouldCollectAsyncNotedOp, message, shouldCollectMessage, skipProxyOperation,
17121                     proxyAttributionFlags, proxiedAttributionFlags, attributionChainId);
17122         }
17123 
17124         @Override
17125         public void finishProxyOperation(int code, @NonNull AttributionSource attributionSource,
17126                 boolean skipProxyOperation, @NonNull TriFunction<Integer, AttributionSource,
17127                         Boolean, Void> superImpl) {
17128             if (attributionSource.getUid() == mTargetUid && isTargetOp(code)) {
17129                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(
17130                         attributionSource.getUid()), Process.SHELL_UID);
17131                 final long identity = Binder.clearCallingIdentity();
17132                 try {
17133                     superImpl.apply(code, new AttributionSource(shellUid,
17134                             "com.android.shell", attributionSource.getAttributionTag(),
17135                             attributionSource.getToken(), attributionSource.getNext()),
17136                             skipProxyOperation);
17137                 } finally {
17138                     Binder.restoreCallingIdentity(identity);
17139                 }
17140             }
17141             superImpl.apply(code, attributionSource, skipProxyOperation);
17142         }
17143 
17144         private boolean isTargetOp(int code) {
17145             // null permissions means all ops are targeted
17146             if (mPermissions == null) {
17147                 return true;
17148             }
17149             // no permission for the op means the op is targeted
17150             final String permission = AppOpsManager.opToPermission(code);
17151             if (permission == null) {
17152                 return true;
17153             }
17154             return isTargetPermission(permission);
17155         }
17156 
17157         private boolean isTargetPermission(@NonNull String permission) {
17158             // null permissions means all permissions are targeted
17159             return (mPermissions == null || ArrayUtils.contains(mPermissions, permission));
17160         }
17161     }
17162 
17163     /**
17164      * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would
17165      * cause a watchdog kill.
17166      */
17167     void maybeTriggerWatchdog() {
17168         final String key = "debug.trigger.watchdog";
17169         if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) {
17170             Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!");
17171 
17172             // Clear the property; otherwise the system would hang again after a watchdog restart.
17173             SystemProperties.set(key, "");
17174             synchronized (ActivityManagerService.this) {
17175                 try {
17176                     // Arbitrary long sleep for watchdog to catch.
17177                     Thread.sleep(60 * 60 * 1000);
17178                 } catch (InterruptedException e) {
17179                 }
17180             }
17181         }
17182     }
17183 
17184     private boolean isOnOffloadQueue(int flags) {
17185         return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
17186     }
17187 
17188     @Override
17189     public ParcelFileDescriptor getLifeMonitor() {
17190         if (!isCallerShell()) {
17191             throw new SecurityException("Only shell can call it");
17192         }
17193         synchronized (mProcLock) {
17194             try {
17195                 if (mLifeMonitorFds == null) {
17196                     mLifeMonitorFds = ParcelFileDescriptor.createPipe();
17197                 }
17198                 // The returned FD will be closed, but we want to keep our reader open,
17199                 // so return a dup instead.
17200                 return mLifeMonitorFds[0].dup();
17201             } catch (IOException e) {
17202                 Slog.w(TAG, "Unable to create pipe", e);
17203                 return null;
17204             }
17205         }
17206     }
17207 
17208     @Override
17209     public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) {
17210         final int callingUid = Binder.getCallingUid();
17211         final int userId = UserHandle.getCallingUserId();
17212         if (getPackageManagerInternal().getPackageUid(activity.getPackageName(),
17213                 /*flags=*/ 0, userId) != callingUid) {
17214             throw new SecurityException("Calling uid " + callingUid + " cannot set locusId"
17215                     + "for package " + activity.getPackageName());
17216         }
17217         mActivityTaskManager.setLocusId(locusId, appToken);
17218         if (mUsageStatsService != null) {
17219             mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken);
17220         }
17221     }
17222 
17223     @Override
17224     public boolean isAppFreezerSupported() {
17225         final long token = Binder.clearCallingIdentity();
17226 
17227         try {
17228             return mOomAdjuster.mCachedAppOptimizer.isFreezerSupported();
17229         } finally {
17230             Binder.restoreCallingIdentity(token);
17231         }
17232     }
17233 
17234     /**
17235      * Resets the state of the {@link com.android.server.am.AppErrors} instance.
17236      * This is intended for testing within the CTS only and is protected by
17237      * android.permission.RESET_APP_ERRORS.
17238      */
17239     @Override
17240     public void resetAppErrors() {
17241         enforceCallingPermission(Manifest.permission.RESET_APP_ERRORS, "resetAppErrors");
17242         mAppErrors.resetState();
17243     }
17244 
17245     @Override
17246     public boolean enableAppFreezer(boolean enable) {
17247         int callerUid = Binder.getCallingUid();
17248 
17249         // Only system can toggle the freezer state
17250         if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) {
17251             return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable);
17252         } else {
17253             throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state ");
17254         }
17255     }
17256 
17257     /**
17258      * Suppress or reenable the rate limit on foreground service notification deferral.
17259      * @param enable false to suppress rate-limit policy; true to reenable it.
17260      */
17261     @Override
17262     public boolean enableFgsNotificationRateLimit(boolean enable) {
17263         enforceCallingPermission(permission.WRITE_DEVICE_CONFIG,
17264                 "enableFgsNotificationRateLimit");
17265         synchronized (this) {
17266             return mServices.enableFgsNotificationRateLimitLocked(enable);
17267         }
17268     }
17269 
17270     /**
17271      * Holds the AM lock for the specified amount of milliseconds.
17272      * Intended for use by the tests that need to imitate lock contention.
17273      * The token should be obtained by
17274      * {@link android.content.pm.PackageManager#getHoldLockToken()}.
17275      */
17276     @Override
17277     public void holdLock(IBinder token, int durationMs) {
17278         getTestUtilityServiceLocked().verifyHoldLockToken(token);
17279 
17280         synchronized (this) {
17281             SystemClock.sleep(durationMs);
17282         }
17283     }
17284 
17285     static void traceBegin(long traceTag, String methodName, String subInfo) {
17286         if (Trace.isTagEnabled(traceTag)) {
17287             Trace.traceBegin(traceTag, methodName + subInfo);
17288         }
17289     }
17290 }
17291