• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006-2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.am;
18 
19 import static android.Manifest.permission.CHANGE_CONFIGURATION;
20 import static android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
21 import static android.Manifest.permission.FILTER_EVENTS;
22 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
24 import static android.Manifest.permission.REMOVE_TASKS;
25 import static android.Manifest.permission.START_ACTIVITIES_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.PROCESS_STATE_LAST_ACTIVITY;
30 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
31 import static android.app.ActivityManager.PROCESS_STATE_TOP;
32 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
33 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
34 import static android.app.AppOpsManager.OP_NONE;
35 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
36 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
37 import static android.content.pm.PackageManager.GET_PROVIDERS;
38 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES;
39 import static android.content.pm.PackageManager.MATCH_ALL;
40 import static android.content.pm.PackageManager.MATCH_ANY_USER;
41 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
42 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
43 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
44 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
45 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
46 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
47 import static android.os.FactoryTest.FACTORY_TEST_OFF;
48 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
49 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
50 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
51 import static android.os.IServiceManager.DUMP_FLAG_PROTO;
52 import static android.os.Process.BLUETOOTH_UID;
53 import static android.os.Process.FIRST_APPLICATION_UID;
54 import static android.os.Process.NETWORK_STACK_UID;
55 import static android.os.Process.NFC_UID;
56 import static android.os.Process.PHONE_UID;
57 import static android.os.Process.PROC_CHAR;
58 import static android.os.Process.PROC_OUT_LONG;
59 import static android.os.Process.PROC_PARENS;
60 import static android.os.Process.PROC_SPACE_TERM;
61 import static android.os.Process.ROOT_UID;
62 import static android.os.Process.SCHED_FIFO;
63 import static android.os.Process.SCHED_RESET_ON_FORK;
64 import static android.os.Process.SE_UID;
65 import static android.os.Process.SHELL_UID;
66 import static android.os.Process.SIGNAL_USR1;
67 import static android.os.Process.SYSTEM_UID;
68 import static android.os.Process.THREAD_PRIORITY_FOREGROUND;
69 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH;
70 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
71 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
72 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS;
73 import static android.os.Process.ZYGOTE_PROCESS;
74 import static android.os.Process.getTotalMemory;
75 import static android.os.Process.isThreadInProcess;
76 import static android.os.Process.killProcess;
77 import static android.os.Process.killProcessQuiet;
78 import static android.os.Process.myPid;
79 import static android.os.Process.myUid;
80 import static android.os.Process.readProcFile;
81 import static android.os.Process.removeAllProcessGroups;
82 import static android.os.Process.sendSignal;
83 import static android.os.Process.setThreadPriority;
84 import static android.os.Process.setThreadScheduler;
85 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
86 import static android.provider.Settings.Global.DEBUG_APP;
87 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS;
88 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
89 import static android.text.format.DateUtils.DAY_IN_MILLIS;
90 
91 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
92 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
93 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
94 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP;
95 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
96 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND;
97 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
98 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
99 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
100 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
101 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESS_OBSERVERS;
105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROVIDER;
106 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS;
107 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
108 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS;
109 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS;
110 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
111 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
112 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
113 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
114 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
115 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESS_OBSERVERS;
120 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROVIDER;
121 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS;
122 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
123 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
124 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
125 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
126 import static com.android.server.am.MemoryStatUtil.hasMemcg;
127 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
128 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
129 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
130 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
131 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
132 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
133 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
134 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
135 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
136 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
137 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD;
138 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
139 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD;
140 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
141 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD;
142 import static com.android.server.wm.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
143 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
144 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString;
145 
146 import android.Manifest;
147 import android.Manifest.permission;
148 import android.annotation.BroadcastBehavior;
149 import android.annotation.NonNull;
150 import android.annotation.Nullable;
151 import android.annotation.UserIdInt;
152 import android.app.Activity;
153 import android.app.ActivityManager;
154 import android.app.ActivityManager.RunningTaskInfo;
155 import android.app.ActivityManager.StackInfo;
156 import android.app.ActivityManagerInternal;
157 import android.app.ActivityManagerProto;
158 import android.app.ActivityThread;
159 import android.app.AppGlobals;
160 import android.app.AppOpsManager;
161 import android.app.AppOpsManagerInternal.CheckOpsDelegate;
162 import android.app.ApplicationErrorReport;
163 import android.app.ApplicationExitInfo;
164 import android.app.ApplicationThreadConstants;
165 import android.app.BroadcastOptions;
166 import android.app.ContentProviderHolder;
167 import android.app.IActivityController;
168 import android.app.IActivityManager;
169 import android.app.IApplicationThread;
170 import android.app.IAssistDataReceiver;
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.WaitResult;
188 import android.app.backup.IBackupManager;
189 import android.app.usage.UsageEvents;
190 import android.app.usage.UsageEvents.Event;
191 import android.app.usage.UsageStatsManager;
192 import android.app.usage.UsageStatsManagerInternal;
193 import android.appwidget.AppWidgetManager;
194 import android.content.AutofillOptions;
195 import android.content.BroadcastReceiver;
196 import android.content.ComponentCallbacks2;
197 import android.content.ComponentName;
198 import android.content.ContentCaptureOptions;
199 import android.content.ContentProvider;
200 import android.content.ContentResolver;
201 import android.content.Context;
202 import android.content.IContentProvider;
203 import android.content.IIntentReceiver;
204 import android.content.IIntentSender;
205 import android.content.Intent;
206 import android.content.IntentFilter;
207 import android.content.LocusId;
208 import android.content.pm.ActivityInfo;
209 import android.content.pm.ActivityPresentationInfo;
210 import android.content.pm.ApplicationInfo;
211 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy;
212 import android.content.pm.IPackageDataObserver;
213 import android.content.pm.IPackageManager;
214 import android.content.pm.InstrumentationInfo;
215 import android.content.pm.PackageInfo;
216 import android.content.pm.PackageManager;
217 import android.content.pm.PackageManager.NameNotFoundException;
218 import android.content.pm.PackageManagerInternal;
219 import android.content.pm.PackageParser;
220 import android.content.pm.ParceledListSlice;
221 import android.content.pm.PathPermission;
222 import android.content.pm.PermissionInfo;
223 import android.content.pm.ProcessInfo;
224 import android.content.pm.ProviderInfo;
225 import android.content.pm.ProviderInfoList;
226 import android.content.pm.ResolveInfo;
227 import android.content.pm.SELinuxUtil;
228 import android.content.pm.ServiceInfo;
229 import android.content.pm.UserInfo;
230 import android.content.res.CompatibilityInfo;
231 import android.content.res.Configuration;
232 import android.content.res.Resources;
233 import android.database.ContentObserver;
234 import android.graphics.Rect;
235 import android.hardware.display.DisplayManagerInternal;
236 import android.location.LocationManager;
237 import android.media.audiofx.AudioEffect;
238 import android.net.Proxy;
239 import android.net.Uri;
240 import android.os.AppZygote;
241 import android.os.BatteryStats;
242 import android.os.Binder;
243 import android.os.BinderProxy;
244 import android.os.BugreportParams;
245 import android.os.Build;
246 import android.os.Bundle;
247 import android.os.Debug;
248 import android.os.DropBoxManager;
249 import android.os.FactoryTest;
250 import android.os.FileUtils;
251 import android.os.Handler;
252 import android.os.IBinder;
253 import android.os.IDeviceIdentifiersPolicyService;
254 import android.os.IPermissionController;
255 import android.os.IProcessInfoService;
256 import android.os.IProgressListener;
257 import android.os.Looper;
258 import android.os.Message;
259 import android.os.Parcel;
260 import android.os.ParcelFileDescriptor;
261 import android.os.PowerManager;
262 import android.os.PowerManager.ServiceType;
263 import android.os.PowerManagerInternal;
264 import android.os.Process;
265 import android.os.RemoteCallback;
266 import android.os.RemoteCallbackList;
267 import android.os.RemoteException;
268 import android.os.ResultReceiver;
269 import android.os.ServiceManager;
270 import android.os.ShellCallback;
271 import android.os.StrictMode;
272 import android.os.SystemClock;
273 import android.os.SystemProperties;
274 import android.os.Trace;
275 import android.os.TransactionTooLargeException;
276 import android.os.UserHandle;
277 import android.os.UserManager;
278 import android.os.WorkSource;
279 import android.os.storage.IStorageManager;
280 import android.os.storage.StorageManager;
281 import android.permission.PermissionManagerInternal.CheckPermissionDelegate;
282 import android.provider.DeviceConfig;
283 import android.provider.DeviceConfig.Properties;
284 import android.provider.Settings;
285 import android.server.ServerProtoEnums;
286 import android.sysprop.InitProperties;
287 import android.sysprop.VoldProperties;
288 import android.telephony.TelephonyManager;
289 import android.text.TextUtils;
290 import android.text.format.DateUtils;
291 import android.text.style.SuggestionSpan;
292 import android.util.ArrayMap;
293 import android.util.ArraySet;
294 import android.util.DebugUtils;
295 import android.util.EventLog;
296 import android.util.IntArray;
297 import android.util.Log;
298 import android.util.Pair;
299 import android.util.PrintWriterPrinter;
300 import android.util.Slog;
301 import android.util.SparseArray;
302 import android.util.SparseIntArray;
303 import android.util.TimeUtils;
304 import android.util.proto.ProtoOutputStream;
305 import android.util.proto.ProtoUtils;
306 import android.view.Display;
307 import android.view.Gravity;
308 import android.view.IRecentsAnimationRunner;
309 import android.view.LayoutInflater;
310 import android.view.View;
311 import android.view.WindowManager;
312 import android.view.autofill.AutofillManagerInternal;
313 
314 import com.android.internal.annotations.GuardedBy;
315 import com.android.internal.annotations.VisibleForTesting;
316 import com.android.internal.app.IAppOpsActiveCallback;
317 import com.android.internal.app.IAppOpsCallback;
318 import com.android.internal.app.IAppOpsService;
319 import com.android.internal.app.ProcessMap;
320 import com.android.internal.app.SystemUserHomeActivity;
321 import com.android.internal.app.procstats.ProcessStats;
322 import com.android.internal.content.PackageHelper;
323 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
324 import com.android.internal.notification.SystemNotificationChannels;
325 import com.android.internal.os.BackgroundThread;
326 import com.android.internal.os.BatteryStatsImpl;
327 import com.android.internal.os.BinderInternal;
328 import com.android.internal.os.ByteTransferPipe;
329 import com.android.internal.os.IResultReceiver;
330 import com.android.internal.os.ProcessCpuTracker;
331 import com.android.internal.os.TransferPipe;
332 import com.android.internal.os.Zygote;
333 import com.android.internal.util.ArrayUtils;
334 import com.android.internal.util.DumpUtils;
335 import com.android.internal.util.FastPrintWriter;
336 import com.android.internal.util.FrameworkStatsLog;
337 import com.android.internal.util.MemInfoReader;
338 import com.android.internal.util.Preconditions;
339 import com.android.internal.util.function.HeptFunction;
340 import com.android.internal.util.function.QuadFunction;
341 import com.android.internal.util.function.TriFunction;
342 import com.android.server.AlarmManagerInternal;
343 import com.android.server.AttributeCache;
344 import com.android.server.DeviceIdleInternal;
345 import com.android.server.DisplayThread;
346 import com.android.server.IntentResolver;
347 import com.android.server.IoThread;
348 import com.android.server.LocalServices;
349 import com.android.server.LockGuard;
350 import com.android.server.NetworkManagementInternal;
351 import com.android.server.PackageWatchdog;
352 import com.android.server.RescueParty;
353 import com.android.server.ServiceThread;
354 import com.android.server.SystemConfig;
355 import com.android.server.SystemService;
356 import com.android.server.SystemServiceManager;
357 import com.android.server.ThreadPriorityBooster;
358 import com.android.server.UserspaceRebootLogger;
359 import com.android.server.Watchdog;
360 import com.android.server.am.ActivityManagerServiceDumpProcessesProto.UidObserverRegistrationProto;
361 import com.android.server.appop.AppOpsService;
362 import com.android.server.compat.PlatformCompat;
363 import com.android.server.contentcapture.ContentCaptureManagerInternal;
364 import com.android.server.firewall.IntentFirewall;
365 import com.android.server.job.JobSchedulerInternal;
366 import com.android.server.pm.Installer;
367 import com.android.server.pm.permission.PermissionManagerServiceInternal;
368 import com.android.server.uri.GrantUri;
369 import com.android.server.uri.NeededUriGrants;
370 import com.android.server.uri.UriGrantsManagerInternal;
371 import com.android.server.utils.PriorityDump;
372 import com.android.server.utils.TimingsTraceAndSlog;
373 import com.android.server.vr.VrManagerInternal;
374 import com.android.server.wm.ActivityMetricsLaunchObserver;
375 import com.android.server.wm.ActivityServiceConnectionsHolder;
376 import com.android.server.wm.ActivityTaskManagerInternal;
377 import com.android.server.wm.ActivityTaskManagerService;
378 import com.android.server.wm.WindowManagerInternal;
379 import com.android.server.wm.WindowManagerService;
380 import com.android.server.wm.WindowProcessController;
381 
382 import dalvik.system.VMRuntime;
383 
384 import libcore.util.EmptyArray;
385 
386 import java.io.File;
387 import java.io.FileDescriptor;
388 import java.io.FileNotFoundException;
389 import java.io.FileOutputStream;
390 import java.io.IOException;
391 import java.io.InputStreamReader;
392 import java.io.PrintWriter;
393 import java.io.StringWriter;
394 import java.text.SimpleDateFormat;
395 import java.util.ArrayList;
396 import java.util.Arrays;
397 import java.util.Collections;
398 import java.util.Comparator;
399 import java.util.Date;
400 import java.util.HashMap;
401 import java.util.HashSet;
402 import java.util.Iterator;
403 import java.util.LinkedList;
404 import java.util.List;
405 import java.util.Locale;
406 import java.util.Map;
407 import java.util.Objects;
408 import java.util.Set;
409 import java.util.concurrent.CountDownLatch;
410 import java.util.concurrent.Executor;
411 import java.util.concurrent.atomic.AtomicBoolean;
412 import java.util.concurrent.atomic.AtomicInteger;
413 import java.util.concurrent.atomic.AtomicLong;
414 import java.util.function.BiFunction;
415 
416 public class ActivityManagerService extends IActivityManager.Stub
417         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
418 
419     /**
420      * Priority we boost main thread and RT of top app to.
421      */
422     public static final int TOP_APP_PRIORITY_BOOST = -10;
423     private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED =
424             "persist.sys.device_provisioned";
425 
426     static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
427     static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
428     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
429     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
430     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
431     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
432     static final String TAG_LRU = TAG + POSTFIX_LRU;
433     private static final String TAG_MU = TAG + POSTFIX_MU;
434     static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
435     static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
436     private static final String TAG_POWER = TAG + POSTFIX_POWER;
437     static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
438     static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
439     private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER;
440     static final String TAG_PSS = TAG + POSTFIX_PSS;
441     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
442     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
443     static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
444 
445     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
446     // here so that while the job scheduler can depend on AMS, the other way around
447     // need not be the case.
448     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
449 
450     private static final String INTENT_BUGREPORT_REQUESTED =
451             "com.android.internal.intent.action.BUGREPORT_REQUESTED";
452     private static final String SHELL_APP_PACKAGE = "com.android.shell";
453 
454     /** Control over CPU and battery monitoring */
455     // write battery stats every 30 minutes.
456     static final long BATTERY_STATS_TIME = 30 * 60 * 1000;
457     static final boolean MONITOR_CPU_USAGE = true;
458     // don't sample cpu less than every 5 seconds.
459     static final long MONITOR_CPU_MIN_TIME = 5 * 1000;
460     // wait possibly forever for next cpu sample.
461     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;
462     static final boolean MONITOR_THREAD_CPU_USAGE = false;
463 
464     // The flags that are set for all calls we make to the package manager.
465     public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
466 
467     static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
468 
469     static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed";
470 
471     public static final String ANR_TRACE_DIR = "/data/anr";
472 
473     // Maximum number of receivers an app can register.
474     private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000;
475 
476     // How long we wait for a launched process to attach to the activity manager
477     // before we decide it's never going to come up for real.
478     static final int PROC_START_TIMEOUT = 10*1000;
479     // How long we wait to kill an application zygote, after the last process using
480     // it has gone away.
481     static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000;
482 
483     // How long we wait for a launched process to attach to the activity manager
484     // before we decide it's never going to come up for real, when the process was
485     // started with a wrapper for instrumentation (such as Valgrind) because it
486     // could take much longer than usual.
487     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
488 
489     // How long we allow a receiver to run before giving up on it.
490     static final int BROADCAST_FG_TIMEOUT = 10*1000;
491     static final int BROADCAST_BG_TIMEOUT = 60*1000;
492 
493     public static final int MY_PID = myPid();
494 
495     static final String[] EMPTY_STRING_ARRAY = new String[0];
496 
497     // How many bytes to write into the dropbox log before truncating
498     static final int DROPBOX_DEFAULT_MAX_SIZE = 192 * 1024;
499     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
500     // as one line, but close enough for now.
501     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
502 
503     /** If a UID observer takes more than this long, send a WTF. */
504     private static final int SLOW_UID_OBSERVER_THRESHOLD_MS = 20;
505 
506     // Necessary ApplicationInfo flags to mark an app as persistent
507     static final int PERSISTENT_MASK =
508             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
509 
510     // Intent sent when remote bugreport collection has been completed
511     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
512             "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
513 
514     /**
515      * Broadcast sent when heap dump collection has been completed.
516      */
517     @BroadcastBehavior(includeBackground = true, protectedBroadcast = true)
518     private static final String ACTION_HEAP_DUMP_FINISHED =
519             "com.android.internal.intent.action.HEAP_DUMP_FINISHED";
520 
521     /**
522      * The process we are reporting
523      */
524     private static final String EXTRA_HEAP_DUMP_PROCESS_NAME =
525             "com.android.internal.extra.heap_dump.PROCESS_NAME";
526 
527     /**
528      * The size limit the process reached.
529      */
530     private static final String EXTRA_HEAP_DUMP_SIZE_BYTES =
531             "com.android.internal.extra.heap_dump.SIZE_BYTES";
532 
533     /**
534      * Whether the user initiated the dump or not.
535      */
536     private static final String EXTRA_HEAP_DUMP_IS_USER_INITIATED =
537             "com.android.internal.extra.heap_dump.IS_USER_INITIATED";
538 
539     /**
540      * Optional name of package to directly launch.
541      */
542     private static final String EXTRA_HEAP_DUMP_REPORT_PACKAGE =
543             "com.android.internal.extra.heap_dump.REPORT_PACKAGE";
544 
545     // If set, we will push process association information in to procstats.
546     static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true;
547 
548     /**
549      * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}.
550      */
551     private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec
552 
553     // The minimum memory growth threshold (in KB) for low RAM devices.
554     private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB
555 
556     /**
557      * The number of binder proxies we need to have before we start warning and
558      * dumping debug info.
559      */
560     private static final int BINDER_PROXY_HIGH_WATERMARK = 6000;
561 
562     /**
563      * Low watermark that needs to be met before we consider dumping info again,
564      * after already hitting the high watermark.
565      */
566     private static final int BINDER_PROXY_LOW_WATERMARK = 5500;
567 
568     // Max character limit for a notification title. If the notification title is larger than this
569     // the notification will not be legible to the user.
570     private static final int MAX_BUGREPORT_TITLE_SIZE = 50;
571     private static final int MAX_BUGREPORT_DESCRIPTION_SIZE = 150;
572 
573     private static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds;
574     private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes.
575 
576     OomAdjuster mOomAdjuster;
577     final LowMemDetector mLowMemDetector;
578 
579     static final String EXTRA_TITLE = "android.intent.extra.TITLE";
580     static final String EXTRA_DESCRIPTION = "android.intent.extra.DESCRIPTION";
581     static final String EXTRA_BUGREPORT_TYPE = "android.intent.extra.BUGREPORT_TYPE";
582 
583     /**
584      * The maximum number of bytes that {@link #setProcessStateSummary} accepts.
585      *
586      * @see {@link android.app.ActivityManager#setProcessStateSummary(byte[])}
587      */
588     static final int MAX_STATE_DATA_SIZE = 128;
589 
590     /** All system services */
591     SystemServiceManager mSystemServiceManager;
592 
593     private Installer mInstaller;
594 
595     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
596 
597     final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
598 
599     public final IntentFirewall mIntentFirewall;
600 
601     public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler();
602 
603     // Whether we should use SCHED_FIFO for UI and RenderThreads.
604     boolean mUseFifoUiScheduling = false;
605 
606     // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
607     // For simplicity, since we statically declare the size of the array of BroadcastQueues,
608     // we still create this new offload queue, but never ever put anything on it.
609     boolean mEnableOffloadQueue;
610 
611     BroadcastQueue mFgBroadcastQueue;
612     BroadcastQueue mBgBroadcastQueue;
613     BroadcastQueue mOffloadBroadcastQueue;
614     // Convenient for easy iteration over the queues. Foreground is first
615     // so that dispatch of foreground broadcasts gets precedence.
616     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[3];
617 
618     BroadcastStats mLastBroadcastStats;
619     BroadcastStats mCurBroadcastStats;
620 
broadcastQueueForIntent(Intent intent)621     BroadcastQueue broadcastQueueForIntent(Intent intent) {
622         if (isOnOffloadQueue(intent.getFlags())) {
623             if (DEBUG_BROADCAST_BACKGROUND) {
624                 Slog.i(TAG_BROADCAST,
625                         "Broadcast intent " + intent + " on offload queue");
626             }
627             return mOffloadBroadcastQueue;
628         }
629 
630         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
631         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
632                 "Broadcast intent " + intent + " on "
633                 + (isFg ? "foreground" : "background") + " queue");
634         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
635     }
636 
637     /**
638      * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
639      */
640     String mDeviceOwnerName;
641 
642     private int mDeviceOwnerUid = Process.INVALID_UID;
643 
644     final UserController mUserController;
645     @VisibleForTesting
646     public final PendingIntentController mPendingIntentController;
647 
648     final AppErrors mAppErrors;
649     final PackageWatchdog mPackageWatchdog;
650 
651     /**
652      * Indicates the maximum time spent waiting for the network rules to get updated.
653      */
654     @VisibleForTesting
655     long mWaitForNetworkTimeoutMs;
656 
657     /** Total # of UID change events dispatched, shown in dumpsys. */
658     int mUidChangeDispatchCount;
659 
660     /**
661      * Uids of apps with current active camera sessions.  Access synchronized on
662      * the IntArray instance itself, and no other locks must be acquired while that
663      * one is held.
664      */
665     @GuardedBy("mActiveCameraUids")
666     final IntArray mActiveCameraUids = new IntArray(4);
667 
668     /**
669      * Helper class which strips out priority and proto arguments then calls the dump function with
670      * the appropriate arguments. If priority arguments are omitted, function calls the legacy
671      * dump command.
672      * If priority arguments are omitted all sections are dumped, otherwise sections are dumped
673      * according to their priority.
674      */
675     private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
676         @Override
677         public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
678                 boolean asProto) {
679             if (asProto) return;
680             doDump(fd, pw, new String[]{"activities"}, asProto);
681             doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
682         }
683 
684         @Override
685         public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
686             doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto);
687         }
688 
689         @Override
690         public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
691             doDump(fd, pw, args, asProto);
692         }
693     };
694 
695     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
696             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
697 
boostPriorityForLockedSection()698     static void boostPriorityForLockedSection() {
699         sThreadPriorityBooster.boost();
700     }
701 
resetPriorityAfterLockedSection()702     static void resetPriorityAfterLockedSection() {
703         sThreadPriorityBooster.reset();
704     }
705 
706     /**
707      * Process management.
708      */
709     final ProcessList mProcessList;
710 
711     /**
712      * Tracking long-term execution of processes to look for abuse and other
713      * bad app behavior.
714      */
715     final ProcessStatsService mProcessStats;
716 
717     /**
718      * Non-persistent appId whitelist for background restrictions
719      */
720     int[] mBackgroundAppIdWhitelist = new int[] {
721             BLUETOOTH_UID
722     };
723 
724     /**
725      * Broadcast actions that will always be deliverable to unlaunched/background apps
726      */
727     ArraySet<String> mBackgroundLaunchBroadcasts;
728 
729     /**
730      * When an app has restrictions on the other apps that can have associations with it,
731      * it appears here with a set of the allowed apps and also track debuggability of the app.
732      */
733     ArrayMap<String, PackageAssociationInfo> mAllowedAssociations;
734 
735     /**
736      * Tracks association information for a particular package along with debuggability.
737      * <p> Associations for a package A are allowed to package B if B is part of the
738      *     allowed associations for A or if A is debuggable.
739      */
740     private final class PackageAssociationInfo {
741         private final String mSourcePackage;
742         private final ArraySet<String> mAllowedPackageAssociations;
743         private boolean mIsDebuggable;
744 
PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)745         PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages,
746                 boolean isDebuggable) {
747             mSourcePackage = sourcePackage;
748             mAllowedPackageAssociations = allowedPackages;
749             mIsDebuggable = isDebuggable;
750         }
751 
752         /**
753          * Returns true if {@code mSourcePackage} is allowed association with
754          * {@code targetPackage}.
755          */
isPackageAssociationAllowed(String targetPackage)756         boolean isPackageAssociationAllowed(String targetPackage) {
757             return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage);
758         }
759 
isDebuggable()760         boolean isDebuggable() {
761             return mIsDebuggable;
762         }
763 
setDebuggable(boolean isDebuggable)764         void setDebuggable(boolean isDebuggable) {
765             mIsDebuggable = isDebuggable;
766         }
767 
getAllowedPackageAssociations()768         ArraySet<String> getAllowedPackageAssociations() {
769             return mAllowedPackageAssociations;
770         }
771     }
772 
773     /**
774      * These are the currently running processes for which we have a ProcessInfo.
775      * Note: needs to be static since the permission checking call chain is static.  This
776      * all probably should be refactored into a separate permission checking object.
777      */
778     @GuardedBy("sActiveProcessInfoSelfLocked")
779     static final SparseArray<ProcessInfo> sActiveProcessInfoSelfLocked = new SparseArray<>();
780 
781     /**
782      * All of the processes we currently have running organized by pid.
783      * The keys are the pid running the application.
784      *
785      * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock!
786      */
787     final PidMap mPidsSelfLocked = new PidMap();
788     static final class PidMap {
789         private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>();
790 
get(int pid)791         ProcessRecord get(int pid) {
792             return mPidMap.get(pid);
793         }
794 
size()795         int size() {
796             return mPidMap.size();
797         }
798 
valueAt(int index)799         ProcessRecord valueAt(int index) {
800             return mPidMap.valueAt(index);
801         }
802 
keyAt(int index)803         int keyAt(int index) {
804             return mPidMap.keyAt(index);
805         }
806 
indexOfKey(int key)807         int indexOfKey(int key) {
808             return mPidMap.indexOfKey(key);
809         }
810 
doAddInternal(ProcessRecord app)811         void doAddInternal(ProcessRecord app) {
812             mPidMap.put(app.pid, app);
813         }
814 
doRemoveInternal(ProcessRecord app)815         boolean doRemoveInternal(ProcessRecord app) {
816             final ProcessRecord existingApp = mPidMap.get(app.pid);
817             if (existingApp != null && existingApp.startSeq == app.startSeq) {
818                 mPidMap.remove(app.pid);
819                 return true;
820             }
821             return false;
822         }
823 
doRemoveIfNoThreadInternal(ProcessRecord app)824         boolean doRemoveIfNoThreadInternal(ProcessRecord app) {
825             if (app == null || app.thread != null) {
826                 return false;
827             }
828             return doRemoveInternal(app);
829         }
830     }
831 
832     private final PendingStartActivityUids mPendingStartActivityUids;
833 
834     /**
835      * Puts the process record in the map.
836      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
837      * method.
838      */
addPidLocked(ProcessRecord app)839     void addPidLocked(ProcessRecord app) {
840         synchronized (mPidsSelfLocked) {
841             mPidsSelfLocked.doAddInternal(app);
842         }
843         synchronized (sActiveProcessInfoSelfLocked) {
844             if (app.processInfo != null) {
845                 sActiveProcessInfoSelfLocked.put(app.pid, app.processInfo);
846             } else {
847                 sActiveProcessInfoSelfLocked.remove(app.pid);
848             }
849         }
850         mAtmInternal.onProcessMapped(app.pid, app.getWindowProcessController());
851     }
852 
853     /**
854      * Removes the process record from the map.
855      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
856      * method.
857      */
removePidLocked(ProcessRecord app)858     void removePidLocked(ProcessRecord app) {
859         final boolean removed;
860         synchronized (mPidsSelfLocked) {
861             removed = mPidsSelfLocked.doRemoveInternal(app);
862         }
863         if (removed) {
864             synchronized (sActiveProcessInfoSelfLocked) {
865                 sActiveProcessInfoSelfLocked.remove(app.pid);
866             }
867             mAtmInternal.onProcessUnMapped(app.pid);
868         }
869     }
870 
871     /**
872      * Removes the process record from the map if it doesn't have a thread.
873      * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
874      * method.
875      */
removePidIfNoThread(ProcessRecord app)876     boolean removePidIfNoThread(ProcessRecord app) {
877         final boolean removed;
878         synchronized (mPidsSelfLocked) {
879             removed = mPidsSelfLocked.doRemoveIfNoThreadInternal(app);
880         }
881         if (removed) {
882             synchronized (sActiveProcessInfoSelfLocked) {
883                 sActiveProcessInfoSelfLocked.remove(app.pid);
884             }
885             mAtmInternal.onProcessUnMapped(app.pid);
886         }
887         return removed;
888     }
889 
890     /**
891      * All of the processes that have been forced to be important.  The key
892      * is the pid of the caller who requested it (we hold a death
893      * link on it).
894      */
895     abstract class ImportanceToken implements IBinder.DeathRecipient {
896         final int pid;
897         final IBinder token;
898         final String reason;
899 
ImportanceToken(int _pid, IBinder _token, String _reason)900         ImportanceToken(int _pid, IBinder _token, String _reason) {
901             pid = _pid;
902             token = _token;
903             reason = _reason;
904         }
905 
906         @Override
toString()907         public String toString() {
908             return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
909                     + " " + reason + " " + pid + " " + token + " }";
910         }
911 
dumpDebug(ProtoOutputStream proto, long fieldId)912         void dumpDebug(ProtoOutputStream proto, long fieldId) {
913             final long pToken = proto.start(fieldId);
914             proto.write(ImportanceTokenProto.PID, pid);
915             if (token != null) {
916                 proto.write(ImportanceTokenProto.TOKEN, token.toString());
917             }
918             proto.write(ImportanceTokenProto.REASON, reason);
919             proto.end(pToken);
920         }
921     }
922     final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
923 
924     /**
925      * List of records for processes that someone had tried to start before the
926      * system was ready.  We don't start them at that point, but ensure they
927      * are started by the time booting is complete.
928      */
929     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
930 
931     /**
932      * List of persistent applications that are in the process
933      * of being started.
934      */
935     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
936 
937     /**
938      * List of processes that should gc as soon as things are idle.
939      */
940     final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
941 
942     /**
943      * Processes we want to collect PSS data from.
944      */
945     final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
946 
947     /**
948      * Depth of overlapping activity-start PSS deferral notes
949      */
950     private final AtomicInteger mActivityStartingNesting = new AtomicInteger(0);
951 
952     private final ActivityMetricsLaunchObserver mActivityLaunchObserver =
953             new ActivityMetricsLaunchObserver() {
954         @Override
955         public void onActivityLaunched(byte[] activity, int temperature) {
956             // This is safe to force to the head of the queue because it relies only
957             // on refcounting to track begin/end of deferrals, not on actual
958             // message ordering.  We don't care *what* activity is being
959             // launched; only that we're doing so.
960             if (mPssDeferralTime > 0) {
961                 final Message msg = mBgHandler.obtainMessage(DEFER_PSS_MSG);
962                 mBgHandler.sendMessageAtFrontOfQueue(msg);
963             }
964         }
965 
966         // The other observer methods are unused
967         @Override
968         public void onIntentStarted(Intent intent, long timestampNs) {
969         }
970 
971         @Override
972         public void onIntentFailed() {
973         }
974 
975         @Override
976         public void onActivityLaunchCancelled(byte[] abortingActivity) {
977         }
978 
979         @Override
980         public void onActivityLaunchFinished(byte[] finalActivity, long timestampNs) {
981         }
982 
983         @Override
984         public void onReportFullyDrawn(byte[] finalActivity, long timestampNs) {
985         }
986     };
987 
988     /**
989      * How long we defer PSS gathering while activities are starting, in milliseconds.
990      * This is adjustable via DeviceConfig.  If it is zero or negative, no PSS deferral
991      * is done.
992      */
993     private volatile long mPssDeferralTime = 0;
994     private static final String ACTIVITY_START_PSS_DEFER_CONFIG = "activity_start_pss_defer";
995 
996     private boolean mBinderTransactionTrackingEnabled = false;
997 
998     /**
999      * Last time we requested PSS data of all processes.
1000      */
1001     long mLastFullPssTime = SystemClock.uptimeMillis();
1002 
1003     /**
1004      * If set, the next time we collect PSS data we should do a full collection
1005      * with data from native processes and the kernel.
1006      */
1007     boolean mFullPssPending = false;
1008 
1009     /**
1010      * Observe DeviceConfig changes to the PSS calculation interval
1011      */
1012     private final DeviceConfig.OnPropertiesChangedListener mPssDelayConfigListener =
1013             new DeviceConfig.OnPropertiesChangedListener() {
1014                 @Override
1015                 public void onPropertiesChanged(Properties properties) {
1016                     if (properties.getKeyset().contains(ACTIVITY_START_PSS_DEFER_CONFIG)) {
1017                         mPssDeferralTime = properties.getLong(ACTIVITY_START_PSS_DEFER_CONFIG, 0);
1018                         if (DEBUG_PSS) {
1019                             Slog.d(TAG_PSS, "Activity-start PSS delay now "
1020                                     + mPssDeferralTime + " ms");
1021                         }
1022                     }
1023                 }
1024             };
1025 
1026     /**
1027      * This is for verifying the UID report flow.
1028      */
1029     static final boolean VALIDATE_UID_STATES = true;
1030     final ActiveUids mValidateUids = new ActiveUids(this, false /* postChangesToAtm */);
1031 
1032     /**
1033      * Fingerprints (hashCode()) of stack traces that we've
1034      * already logged DropBox entries for.  Guarded by itself.  If
1035      * something (rogue user app) forces this over
1036      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
1037      */
1038     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
1039     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
1040 
1041     /**
1042      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
1043      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
1044      */
1045     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
1046 
1047     /**
1048      * Resolver for broadcast intents to registered receivers.
1049      * Holds BroadcastFilter (subclass of IntentFilter).
1050      */
1051     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
1052             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
1053         @Override
1054         protected boolean allowFilterResult(
1055                 BroadcastFilter filter, List<BroadcastFilter> dest) {
1056             IBinder target = filter.receiverList.receiver.asBinder();
1057             for (int i = dest.size() - 1; i >= 0; i--) {
1058                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
1059                     return false;
1060                 }
1061             }
1062             return true;
1063         }
1064 
1065         @Override
1066         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
1067             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
1068                     || userId == filter.owningUserId) {
1069                 return super.newResult(filter, match, userId);
1070             }
1071             return null;
1072         }
1073 
1074         @Override
1075         protected IntentFilter getIntentFilter(@NonNull BroadcastFilter input) {
1076             return input;
1077         }
1078 
1079         @Override
1080         protected BroadcastFilter[] newArray(int size) {
1081             return new BroadcastFilter[size];
1082         }
1083 
1084         @Override
1085         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
1086             return packageName.equals(filter.packageName);
1087         }
1088     };
1089 
1090     /**
1091      * State of all active sticky broadcasts per user.  Keys are the action of the
1092      * sticky Intent, values are an ArrayList of all broadcasted intents with
1093      * that action (which should usually be one).  The SparseArray is keyed
1094      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1095      * for stickies that are sent to all users.
1096      */
1097     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
1098             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
1099 
1100     final ActiveServices mServices;
1101 
1102     final static class Association {
1103         final int mSourceUid;
1104         final String mSourceProcess;
1105         final int mTargetUid;
1106         final ComponentName mTargetComponent;
1107         final String mTargetProcess;
1108 
1109         int mCount;
1110         long mTime;
1111 
1112         int mNesting;
1113         long mStartTime;
1114 
1115         // states of the source process when the bind occurred.
1116         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1117         long mLastStateUptime;
1118         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1119                 - ActivityManager.MIN_PROCESS_STATE+1];
1120 
Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1121         Association(int sourceUid, String sourceProcess, int targetUid,
1122                 ComponentName targetComponent, String targetProcess) {
1123             mSourceUid = sourceUid;
1124             mSourceProcess = sourceProcess;
1125             mTargetUid = targetUid;
1126             mTargetComponent = targetComponent;
1127             mTargetProcess = targetProcess;
1128         }
1129     }
1130 
1131     /**
1132      * When service association tracking is enabled, this is all of the associations we
1133      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
1134      * -> association data.
1135      */
1136     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1137             mAssociations = new SparseArray<>();
1138     boolean mTrackingAssociations;
1139 
1140     /**
1141      * Backup/restore process management
1142      */
1143     @GuardedBy("this")
1144     final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>();
1145 
1146     final ProviderMap mProviderMap;
1147 
1148     /**
1149      * List of content providers who have clients waiting for them.  The
1150      * application is currently being launched and the provider will be
1151      * removed from this list once it is published.
1152      */
1153     final ArrayList<ContentProviderRecord> mLaunchingProviders = new ArrayList<>();
1154 
1155     boolean mSystemProvidersInstalled;
1156 
1157     CoreSettingsObserver mCoreSettingsObserver;
1158 
1159     DevelopmentSettingsObserver mDevelopmentSettingsObserver;
1160 
1161     private final class DevelopmentSettingsObserver extends ContentObserver {
1162         private final Uri mUri = Settings.Global
1163                 .getUriFor(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
1164 
1165         private final ComponentName mBugreportStorageProvider = new ComponentName(
1166                 "com.android.shell", "com.android.shell.BugreportStorageProvider");
1167 
DevelopmentSettingsObserver()1168         public DevelopmentSettingsObserver() {
1169             super(mHandler);
1170             mContext.getContentResolver().registerContentObserver(mUri, false, this,
1171                     UserHandle.USER_ALL);
1172             // Always kick once to ensure that we match current state
1173             onChange();
1174         }
1175 
1176         @Override
onChange(boolean selfChange, Uri uri, @UserIdInt int userId)1177         public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
1178             if (mUri.equals(uri)) {
1179                 onChange();
1180             }
1181         }
1182 
onChange()1183         public void onChange() {
1184             final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(),
1185                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, Build.IS_ENG ? 1 : 0) != 0;
1186             mContext.getPackageManager().setComponentEnabledSetting(mBugreportStorageProvider,
1187                     enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1188                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
1189                     0);
1190         }
1191     }
1192 
1193     /**
1194      * Thread-local storage used to carry caller permissions over through
1195      * indirect content-provider access.
1196      */
1197     private class Identity {
1198         public final IBinder token;
1199         public final int pid;
1200         public final int uid;
1201 
Identity(IBinder _token, int _pid, int _uid)1202         Identity(IBinder _token, int _pid, int _uid) {
1203             token = _token;
1204             pid = _pid;
1205             uid = _uid;
1206         }
1207     }
1208 
1209     private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1210 
1211     /**
1212      * All information we have collected about the runtime performance of
1213      * any user id that can impact battery performance.
1214      */
1215     final BatteryStatsService mBatteryStatsService;
1216 
1217     /**
1218      * Information about component usage
1219      */
1220     UsageStatsManagerInternal mUsageStatsService;
1221 
1222     /**
1223      * Access to DeviceIdleController service.
1224      */
1225     DeviceIdleInternal mLocalDeviceIdleController;
1226 
1227     /**
1228      * Power-save whitelisted app-ids (not including except-idle-whitelisted ones).
1229      */
1230     int[] mDeviceIdleWhitelist = new int[0];
1231 
1232     /**
1233      * Power-save whitelisted app-ids (including except-idle-whitelisted ones).
1234      */
1235     int[] mDeviceIdleExceptIdleWhitelist = new int[0];
1236 
1237     /**
1238      * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1239      */
1240     int[] mDeviceIdleTempWhitelist = new int[0];
1241 
1242     static final class PendingTempWhitelist {
1243         final int targetUid;
1244         final long duration;
1245         final String tag;
1246 
PendingTempWhitelist(int _targetUid, long _duration, String _tag)1247         PendingTempWhitelist(int _targetUid, long _duration, String _tag) {
1248             targetUid = _targetUid;
1249             duration = _duration;
1250             tag = _tag;
1251         }
1252 
dumpDebug(ProtoOutputStream proto, long fieldId)1253         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1254             final long token = proto.start(fieldId);
1255             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, targetUid);
1256             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, duration);
1257             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag);
1258             proto.end(token);
1259         }
1260     }
1261 
1262     final PendingTempWhitelists mPendingTempWhitelist = new PendingTempWhitelists(this);
1263 
1264     /**
1265      * List of uids that are allowed to have while-in-use permission when FGS is started from
1266      * background.
1267      */
1268     private final FgsWhileInUseTempAllowList mFgsWhileInUseTempAllowList =
1269             new FgsWhileInUseTempAllowList();
1270 
1271     /**
1272      * Information about and control over application operations
1273      */
1274     final AppOpsService mAppOpsService;
1275     private AppOpsManager mAppOpsManager;
1276 
1277     /**
1278      * List of initialization arguments to pass to all processes when binding applications to them.
1279      * For example, references to the commonly used services.
1280      */
1281     ArrayMap<String, IBinder> mAppBindArgs;
1282     ArrayMap<String, IBinder> mIsolatedAppBindArgs;
1283 
1284     /**
1285      * Temporary to avoid allocations.  Protected by main lock.
1286      */
1287     final StringBuilder mStringBuilder = new StringBuilder(256);
1288 
1289     volatile boolean mProcessesReady = false;
1290     volatile boolean mSystemReady = false;
1291     volatile boolean mOnBattery = false;
1292     final int mFactoryTest;
1293     volatile boolean mBooting = false;
1294 
1295     @GuardedBy("this") boolean mCallFinishBooting = false;
1296     @GuardedBy("this") boolean mBootAnimationComplete = false;
1297 
1298     final Context mContext;
1299 
1300     /**
1301      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1302      * change at runtime. Use mContext for non-UI purposes.
1303      */
1304     final Context mUiContext;
1305 
1306     /**
1307      * Last time (in uptime) at which we checked for power usage.
1308      */
1309     long mLastPowerCheckUptime;
1310 
1311     /**
1312      * For some direct access we need to power manager.
1313      */
1314     PowerManagerInternal mLocalPowerManager;
1315 
1316     /**
1317      * State of external calls telling us if the device is awake or asleep.
1318      */
1319     int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
1320 
1321     /**
1322      * Allow the current computed overall memory level of the system to go down?
1323      * This is set to false when we are killing processes for reasons other than
1324      * memory management, so that the now smaller process list will not be taken as
1325      * an indication that memory is tighter.
1326      */
1327     boolean mAllowLowerMemLevel = false;
1328 
1329     /**
1330      * The last computed memory level, for holding when we are in a state that
1331      * processes are going away for other reasons.
1332      */
1333     int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1334 
1335     /**
1336      * The last total number of process we have, to determine if changes actually look
1337      * like a shrinking number of process due to lower RAM.
1338      */
1339     int mLastNumProcesses;
1340 
1341     /**
1342      * The uptime of the last time we performed idle maintenance.
1343      */
1344     long mLastIdleTime = SystemClock.uptimeMillis();
1345 
1346     /**
1347      * Total time spent with RAM that has been added in the past since the last idle time.
1348      */
1349     long mLowRamTimeSinceLastIdle = 0;
1350 
1351     /**
1352      * If RAM is currently low, when that horrible situation started.
1353      */
1354     long mLowRamStartTime = 0;
1355 
1356     /**
1357      * For reporting to battery stats the current top application.
1358      */
1359     private String mCurResumedPackage = null;
1360     private int mCurResumedUid = -1;
1361 
1362     /**
1363      * For reporting to battery stats the apps currently running foreground
1364      * service.  The ProcessMap is package/uid tuples; each of these contain
1365      * an array of the currently foreground processes.
1366      */
1367     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1368             = new ProcessMap<ArrayList<ProcessRecord>>();
1369 
1370     /**
1371      * Set if the systemServer made a call to enterSafeMode.
1372      */
1373     boolean mSafeMode;
1374 
1375     /**
1376      * If true, we are running under a test environment so will sample PSS from processes
1377      * much more rapidly to try to collect better data when the tests are rapidly
1378      * running through apps.
1379      */
1380     boolean mTestPssMode = false;
1381 
1382     String mDebugApp = null;
1383     boolean mWaitForDebugger = false;
1384     boolean mDebugTransient = false;
1385     String mOrigDebugApp = null;
1386     boolean mOrigWaitForDebugger = false;
1387     boolean mAlwaysFinishActivities = false;
1388 
1389     class ProfileData {
1390         private String mProfileApp = null;
1391         private ProcessRecord mProfileProc = null;
1392         private ProfilerInfo mProfilerInfo = null;
1393 
setProfileApp(String profileApp)1394         void setProfileApp(String profileApp) {
1395             mProfileApp = profileApp;
1396             if (mAtmInternal != null) {
1397                 mAtmInternal.setProfileApp(profileApp);
1398             }
1399         }
1400 
getProfileApp()1401         String getProfileApp() {
1402             return mProfileApp;
1403         }
1404 
setProfileProc(ProcessRecord profileProc)1405         void setProfileProc(ProcessRecord profileProc) {
1406             mProfileProc = profileProc;
1407             if (mAtmInternal != null) {
1408                 mAtmInternal.setProfileProc(profileProc == null ? null
1409                         : profileProc.getWindowProcessController());
1410             }
1411         }
1412 
getProfileProc()1413         ProcessRecord getProfileProc() {
1414             return mProfileProc;
1415         }
1416 
setProfilerInfo(ProfilerInfo profilerInfo)1417         void setProfilerInfo(ProfilerInfo profilerInfo) {
1418             mProfilerInfo = profilerInfo;
1419             if (mAtmInternal != null) {
1420                 mAtmInternal.setProfilerInfo(profilerInfo);
1421             }
1422         }
1423 
getProfilerInfo()1424         ProfilerInfo getProfilerInfo() {
1425             return mProfilerInfo;
1426         }
1427     }
1428     final ProfileData mProfileData = new ProfileData();
1429 
1430     /**
1431      * Stores a map of process name -> agent string. When a process is started and mAgentAppMap
1432      * is not null, this map is checked and the mapped agent installed during bind-time. Note:
1433      * A non-null agent in mProfileInfo overrides this.
1434      */
1435     private @Nullable Map<String, String> mAppAgentMap = null;
1436 
1437     int mProfileType = 0;
1438     final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>();
1439     String mMemWatchDumpProcName;
1440     Uri mMemWatchDumpUri;
1441     int mMemWatchDumpPid;
1442     int mMemWatchDumpUid;
1443     private boolean mMemWatchIsUserInitiated;
1444     String mTrackAllocationApp = null;
1445     String mNativeDebuggingApp = null;
1446 
1447     final Injector mInjector;
1448 
1449     static final class ProcessChangeItem {
1450         static final int CHANGE_ACTIVITIES = 1<<0;
1451         static final int CHANGE_FOREGROUND_SERVICES = 1<<1;
1452         static final int CHANGE_CAPABILITY = 1<<2;
1453         int changes;
1454         int uid;
1455         int pid;
1456         int processState;
1457         int capability;
1458         boolean foregroundActivities;
1459         int foregroundServiceTypes;
1460     }
1461 
1462     static final class UidObserverRegistration {
1463         final int uid;
1464         final String pkg;
1465         final int which;
1466         final int cutpoint;
1467 
1468         /**
1469          * Total # of callback calls that took more than {@link #SLOW_UID_OBSERVER_THRESHOLD_MS}.
1470          * We show it in dumpsys.
1471          */
1472         int mSlowDispatchCount;
1473 
1474         /** Max time it took for each dispatch. */
1475         int mMaxDispatchTime;
1476 
1477         final SparseIntArray lastProcStates;
1478 
1479         // Please keep the enum lists in sync
1480         private static int[] ORIG_ENUMS = new int[]{
1481                 ActivityManager.UID_OBSERVER_IDLE,
1482                 ActivityManager.UID_OBSERVER_ACTIVE,
1483                 ActivityManager.UID_OBSERVER_GONE,
1484                 ActivityManager.UID_OBSERVER_PROCSTATE,
1485         };
1486         private static int[] PROTO_ENUMS = new int[]{
1487                 ActivityManagerProto.UID_OBSERVER_FLAG_IDLE,
1488                 ActivityManagerProto.UID_OBSERVER_FLAG_ACTIVE,
1489                 ActivityManagerProto.UID_OBSERVER_FLAG_GONE,
1490                 ActivityManagerProto.UID_OBSERVER_FLAG_PROCSTATE,
1491         };
1492 
UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint)1493         UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) {
1494             uid = _uid;
1495             pkg = _pkg;
1496             which = _which;
1497             cutpoint = _cutpoint;
1498             if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
1499                 lastProcStates = new SparseIntArray();
1500             } else {
1501                 lastProcStates = null;
1502             }
1503         }
1504 
dumpDebug(ProtoOutputStream proto, long fieldId)1505         void dumpDebug(ProtoOutputStream proto, long fieldId) {
1506             final long token = proto.start(fieldId);
1507             proto.write(UidObserverRegistrationProto.UID, uid);
1508             proto.write(UidObserverRegistrationProto.PACKAGE, pkg);
1509             ProtoUtils.writeBitWiseFlagsToProtoEnum(proto, UidObserverRegistrationProto.FLAGS,
1510                     which, ORIG_ENUMS, PROTO_ENUMS);
1511             proto.write(UidObserverRegistrationProto.CUT_POINT, cutpoint);
1512             if (lastProcStates != null) {
1513                 final int NI = lastProcStates.size();
1514                 for (int i=0; i<NI; i++) {
1515                     final long pToken = proto.start(UidObserverRegistrationProto.LAST_PROC_STATES);
1516                     proto.write(UidObserverRegistrationProto.ProcState.UID, lastProcStates.keyAt(i));
1517                     proto.write(UidObserverRegistrationProto.ProcState.STATE, lastProcStates.valueAt(i));
1518                     proto.end(pToken);
1519                 }
1520             }
1521             proto.end(token);
1522         }
1523     }
1524 
1525     // TODO: Move below 4 members and code to ProcessList
1526     final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>();
1527     ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
1528 
1529     final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>();
1530     final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();
1531 
1532     final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>();
1533     UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];
1534 
1535     final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>();
1536     final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>();
1537 
1538     OomAdjObserver mCurOomAdjObserver;
1539     int mCurOomAdjUid;
1540 
1541     interface OomAdjObserver {
onOomAdjMessage(String msg)1542         void onOomAdjMessage(String msg);
1543     }
1544 
1545     final AnrHelper mAnrHelper = new AnrHelper();
1546 
1547     /**
1548      * Runtime CPU use collection thread.  This object's lock is used to
1549      * perform synchronization with the thread (notifying it to run).
1550      */
1551     final Thread mProcessCpuThread;
1552 
1553     /**
1554      * Used to collect per-process CPU use for ANRs, battery stats, etc.
1555      * Must acquire this object's lock when accessing it.
1556      * NOTE: this lock will be held while doing long operations (trawling
1557      * through all processes in /proc), so it should never be acquired by
1558      * any critical paths such as when holding the main activity manager lock.
1559      */
1560     final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1561             MONITOR_THREAD_CPU_USAGE);
1562     final AtomicLong mLastCpuTime = new AtomicLong(0);
1563     final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1564     final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1);
1565 
1566     long mLastWriteTime = 0;
1567 
1568     /** Set to true after the system has finished booting. */
1569     volatile boolean mBooted = false;
1570 
1571     /**
1572      * Current boot phase.
1573      */
1574     int mBootPhase;
1575 
1576     @VisibleForTesting
1577     public WindowManagerService mWindowManager;
1578     WindowManagerInternal mWmInternal;
1579     @VisibleForTesting
1580     public ActivityTaskManagerService mActivityTaskManager;
1581     @VisibleForTesting
1582     public ActivityTaskManagerInternal mAtmInternal;
1583     UriGrantsManagerInternal mUgmInternal;
1584     @VisibleForTesting
1585     public final ActivityManagerInternal mInternal;
1586     final ActivityThread mSystemThread;
1587 
1588     private final class AppDeathRecipient implements IBinder.DeathRecipient {
1589         final ProcessRecord mApp;
1590         final int mPid;
1591         final IApplicationThread mAppThread;
1592 
AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1593         AppDeathRecipient(ProcessRecord app, int pid,
1594                 IApplicationThread thread) {
1595             if (DEBUG_ALL) Slog.v(
1596                 TAG, "New death recipient " + this
1597                  + " for thread " + thread.asBinder());
1598             mApp = app;
1599             mPid = pid;
1600             mAppThread = thread;
1601         }
1602 
1603         @Override
binderDied()1604         public void binderDied() {
1605             if (DEBUG_ALL) Slog.v(
1606                 TAG, "Death received in " + this
1607                 + " for thread " + mAppThread.asBinder());
1608             synchronized(ActivityManagerService.this) {
1609                 appDiedLocked(mApp, mPid, mAppThread, true, null);
1610             }
1611         }
1612     }
1613 
1614     static final int SHOW_ERROR_UI_MSG = 1;
1615     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1616     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1617     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1618     static final int SERVICE_TIMEOUT_MSG = 12;
1619     static final int UPDATE_TIME_ZONE = 13;
1620     static final int PROC_START_TIMEOUT_MSG = 20;
1621     static final int KILL_APPLICATION_MSG = 22;
1622     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1623     static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
1624     static final int CLEAR_DNS_CACHE_MSG = 28;
1625     static final int UPDATE_HTTP_PROXY_MSG = 29;
1626     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1627     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1628     static final int REPORT_MEM_USAGE_MSG = 33;
1629     static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1630     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1631     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1632     static final int ABORT_DUMPHEAP_MSG = 51;
1633     static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53;
1634     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1635     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1636     static final int IDLE_UIDS_MSG = 58;
1637     static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1638     static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1639     static final int PUSH_TEMP_WHITELIST_UI_MSG = 68;
1640     static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1641     static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70;
1642     static final int KILL_APP_ZYGOTE_MSG = 71;
1643 
1644     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1645 
1646     static final String SERVICE_RECORD_KEY = "servicerecord";
1647 
1648     long mLastMemUsageReportTime = 0;
1649 
1650     /**
1651      * Flag whether the current user is a "monkey", i.e. whether
1652      * the UI is driven by a UI automation tool.
1653      */
1654     private boolean mUserIsMonkey;
1655 
1656     @VisibleForTesting
1657     public final ServiceThread mHandlerThread;
1658     final MainHandler mHandler;
1659     final Handler mUiHandler;
1660     final ServiceThread mProcStartHandlerThread;
1661     final Handler mProcStartHandler;
1662 
1663     ActivityManagerConstants mConstants;
1664 
1665     // Encapsulates the global setting "hidden_api_blacklist_exemptions"
1666     final HiddenApiSettings mHiddenApiBlacklist;
1667 
1668     private final PlatformCompat mPlatformCompat;
1669 
1670     PackageManagerInternal mPackageManagerInt;
1671     PermissionManagerServiceInternal mPermissionManagerInt;
1672 
1673     /**
1674      * Whether to force background check on all apps (for battery saver) or not.
1675      */
1676     boolean mForceBackgroundCheck;
1677 
1678     private static String sTheRealBuildSerial = Build.UNKNOWN;
1679 
1680     private ParcelFileDescriptor[] mLifeMonitorFds;
1681 
1682     static final HostingRecord sNullHostingRecord = new HostingRecord(null);
1683     /**
1684      * Used to notify activity lifecycle events.
1685      */
1686     @Nullable ContentCaptureManagerInternal mContentCaptureService;
1687 
1688     final class UiHandler extends Handler {
UiHandler()1689         public UiHandler() {
1690             super(com.android.server.UiThread.get().getLooper(), null, true);
1691         }
1692 
1693         @Override
handleMessage(Message msg)1694         public void handleMessage(Message msg) {
1695             switch (msg.what) {
1696                 case SHOW_ERROR_UI_MSG: {
1697                     mAppErrors.handleShowAppErrorUi(msg);
1698                     ensureBootCompleted();
1699                 } break;
1700                 case SHOW_NOT_RESPONDING_UI_MSG: {
1701                     mAppErrors.handleShowAnrUi(msg);
1702                     ensureBootCompleted();
1703                 } break;
1704                 case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1705                     HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1706                     synchronized (ActivityManagerService.this) {
1707                         ProcessRecord proc = (ProcessRecord) data.get("app");
1708                         if (proc == null) {
1709                             Slog.e(TAG, "App not found when showing strict mode dialog.");
1710                             break;
1711                         }
1712                         if (proc.getDialogController().hasViolationDialogs()) {
1713                             Slog.e(TAG, "App already has strict mode dialog: " + proc);
1714                             return;
1715                         }
1716                         AppErrorResult res = (AppErrorResult) data.get("result");
1717                         if (mAtmInternal.showStrictModeViolationDialog()) {
1718                             proc.getDialogController().showViolationDialogs(res);
1719                         } else {
1720                             // The device is asleep, so just pretend that the user
1721                             // saw a crash dialog and hit "force quit".
1722                             res.set(0);
1723                         }
1724                     }
1725                     ensureBootCompleted();
1726                 } break;
1727                 case WAIT_FOR_DEBUGGER_UI_MSG: {
1728                     synchronized (ActivityManagerService.this) {
1729                         ProcessRecord app = (ProcessRecord) msg.obj;
1730                         if (msg.arg1 != 0) {
1731                             if (!app.waitedForDebugger) {
1732                                 app.getDialogController().showDebugWaitingDialogs();
1733                                 app.waitedForDebugger = true;
1734                             }
1735                         } else {
1736                             app.getDialogController().clearWaitingDialog();
1737                         }
1738                     }
1739                 } break;
1740                 case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1741                     dispatchProcessesChanged();
1742                     break;
1743                 }
1744                 case DISPATCH_PROCESS_DIED_UI_MSG: {
1745                     final int pid = msg.arg1;
1746                     final int uid = msg.arg2;
1747                     dispatchProcessDied(pid, uid);
1748                     break;
1749                 }
1750                 case DISPATCH_UIDS_CHANGED_UI_MSG: {
1751                     if (false) { // DO NOT SUBMIT WITH TRUE
1752                         maybeTriggerWatchdog();
1753                     }
1754                     dispatchUidsChanged();
1755                 } break;
1756                 case DISPATCH_OOM_ADJ_OBSERVER_MSG: {
1757                     dispatchOomAdjObserver((String) msg.obj);
1758                 } break;
1759                 case PUSH_TEMP_WHITELIST_UI_MSG: {
1760                     pushTempWhitelist();
1761                 } break;
1762             }
1763         }
1764     }
1765 
1766     final class MainHandler extends Handler {
MainHandler(Looper looper)1767         public MainHandler(Looper looper) {
1768             super(looper, null, true);
1769         }
1770 
1771         @Override
handleMessage(Message msg)1772         public void handleMessage(Message msg) {
1773             switch (msg.what) {
1774             case GC_BACKGROUND_PROCESSES_MSG: {
1775                 synchronized (ActivityManagerService.this) {
1776                     performAppGcsIfAppropriateLocked();
1777                 }
1778             } break;
1779             case SERVICE_TIMEOUT_MSG: {
1780                 mServices.serviceTimeout((ProcessRecord)msg.obj);
1781             } break;
1782             case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1783                 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj);
1784             } break;
1785             case SERVICE_FOREGROUND_CRASH_MSG: {
1786                 mServices.serviceForegroundCrash(
1787                     (ProcessRecord) msg.obj, msg.getData().getCharSequence(SERVICE_RECORD_KEY));
1788             } break;
1789             case UPDATE_TIME_ZONE: {
1790                 synchronized (ActivityManagerService.this) {
1791                     for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) {
1792                         ProcessRecord r = mProcessList.mLruProcesses.get(i);
1793                         if (r.thread != null) {
1794                             try {
1795                                 r.thread.updateTimeZone();
1796                             } catch (RemoteException ex) {
1797                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
1798                             }
1799                         }
1800                     }
1801                 }
1802             } break;
1803             case CLEAR_DNS_CACHE_MSG: {
1804                 synchronized (ActivityManagerService.this) {
1805                     mProcessList.clearAllDnsCacheLocked();
1806                 }
1807             } break;
1808             case UPDATE_HTTP_PROXY_MSG: {
1809                 mProcessList.setAllHttpProxy();
1810             } break;
1811             case PROC_START_TIMEOUT_MSG: {
1812                 ProcessRecord app = (ProcessRecord)msg.obj;
1813                 synchronized (ActivityManagerService.this) {
1814                     processStartTimedOutLocked(app);
1815                 }
1816             } break;
1817             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1818                 ProcessRecord app = (ProcessRecord)msg.obj;
1819                 synchronized (ActivityManagerService.this) {
1820                     processContentProviderPublishTimedOutLocked(app);
1821                 }
1822             } break;
1823             case KILL_APPLICATION_MSG: {
1824                 synchronized (ActivityManagerService.this) {
1825                     final int appId = msg.arg1;
1826                     final int userId = msg.arg2;
1827                     Bundle bundle = (Bundle)msg.obj;
1828                     String pkg = bundle.getString("pkg");
1829                     String reason = bundle.getString("reason");
1830                     forceStopPackageLocked(pkg, appId, false, false, true, false,
1831                             false, userId, reason);
1832                 }
1833             } break;
1834                 case KILL_APP_ZYGOTE_MSG: {
1835                     synchronized (ActivityManagerService.this) {
1836                         final AppZygote appZygote = (AppZygote) msg.obj;
1837                         mProcessList.killAppZygoteIfNeededLocked(appZygote, false /* force */);
1838                     }
1839                 } break;
1840             case CHECK_EXCESSIVE_POWER_USE_MSG: {
1841                 synchronized (ActivityManagerService.this) {
1842                     checkExcessivePowerUsageLocked();
1843                     removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
1844                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
1845                     sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
1846                 }
1847             } break;
1848             case REPORT_MEM_USAGE_MSG: {
1849                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
1850                 Thread thread = new Thread() {
1851                     @Override public void run() {
1852                         reportMemUsage(memInfos);
1853                     }
1854                 };
1855                 thread.start();
1856                 break;
1857             }
1858             case UPDATE_TIME_PREFERENCE_MSG: {
1859                 // The user's time format preference might have changed.
1860                 // For convenience we re-use the Intent extra values.
1861                 synchronized (ActivityManagerService.this) {
1862                     mProcessList.updateAllTimePrefsLocked(msg.arg1);
1863                 }
1864                 break;
1865             }
1866             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1867                 final int uid = msg.arg1;
1868                 final byte[] firstPacket = (byte[]) msg.obj;
1869 
1870                 synchronized (mPidsSelfLocked) {
1871                     for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1872                         final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1873                         if (p.uid == uid && p.thread != null) {
1874                             try {
1875                                 p.thread.notifyCleartextNetwork(firstPacket);
1876                             } catch (RemoteException ignored) {
1877                             }
1878                         }
1879                     }
1880                 }
1881                 break;
1882             }
1883             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1884                 final String procName;
1885                 final int uid;
1886                 final long memLimit;
1887                 final String reportPackage;
1888                 final boolean isUserInitiated;
1889                 synchronized (ActivityManagerService.this) {
1890                     uid = mMemWatchDumpUid;
1891                     procName = mMemWatchDumpProcName;
1892                     Pair<Long, String> val = mMemWatchProcesses.get(procName, uid);
1893                     if (val == null) {
1894                         val = mMemWatchProcesses.get(procName, 0);
1895                     }
1896                     if (val != null) {
1897                         memLimit = val.first;
1898                         reportPackage = val.second;
1899                     } else {
1900                         memLimit = 0;
1901                         reportPackage = null;
1902                     }
1903                     isUserInitiated = mMemWatchIsUserInitiated;
1904 
1905                     mMemWatchDumpUri = null;
1906                     mMemWatchDumpProcName = null;
1907                     mMemWatchDumpPid = -1;
1908                     mMemWatchDumpUid = -1;
1909                 }
1910                 if (procName == null) {
1911                     return;
1912                 }
1913 
1914                 if (DEBUG_PSS) Slog.d(TAG_PSS,
1915                         "Showing dump heap notification from " + procName + "/" + uid);
1916 
1917                 Intent dumpFinishedIntent = new Intent(ACTION_HEAP_DUMP_FINISHED);
1918                 // Send this only to the Shell package.
1919                 dumpFinishedIntent.setPackage("com.android.shell");
1920                 dumpFinishedIntent.putExtra(Intent.EXTRA_UID, uid);
1921                 dumpFinishedIntent.putExtra(EXTRA_HEAP_DUMP_IS_USER_INITIATED, isUserInitiated);
1922                 dumpFinishedIntent.putExtra(EXTRA_HEAP_DUMP_SIZE_BYTES, memLimit);
1923                 dumpFinishedIntent.putExtra(EXTRA_HEAP_DUMP_REPORT_PACKAGE, reportPackage);
1924                 dumpFinishedIntent.putExtra(EXTRA_HEAP_DUMP_PROCESS_NAME, procName);
1925 
1926                 mContext.sendBroadcastAsUser(dumpFinishedIntent,
1927                         UserHandle.getUserHandleForUid(uid));
1928             } break;
1929             case ABORT_DUMPHEAP_MSG: {
1930                 String procName = (String) msg.obj;
1931                 if (procName != null) {
1932                     synchronized (ActivityManagerService.this) {
1933                         if (procName.equals(mMemWatchDumpProcName)) {
1934                             mMemWatchDumpProcName = null;
1935                             mMemWatchDumpUri = null;
1936                             mMemWatchDumpPid = -1;
1937                             mMemWatchDumpUid = -1;
1938                         }
1939                     }
1940                 }
1941             } break;
1942             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
1943                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
1944                 try {
1945                     connection.shutdown();
1946                 } catch (RemoteException e) {
1947                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
1948                 }
1949                 // Only a UiAutomation can set this flag and now that
1950                 // it is finished we make sure it is reset to its default.
1951                 mUserIsMonkey = false;
1952             } break;
1953             case IDLE_UIDS_MSG: {
1954                 idleUids();
1955             } break;
1956             case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
1957                 synchronized (ActivityManagerService.this) {
1958                     mProcessList.handleAllTrustStorageUpdateLocked();
1959                 }
1960             } break;
1961             }
1962         }
1963     }
1964 
1965     static final int COLLECT_PSS_BG_MSG = 1;
1966     static final int DEFER_PSS_MSG = 2;
1967     static final int STOP_DEFERRING_PSS_MSG = 3;
1968 
1969     final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
1970         @Override
1971         public void handleMessage(Message msg) {
1972             switch (msg.what) {
1973             case COLLECT_PSS_BG_MSG: {
1974                 long start = SystemClock.uptimeMillis();
1975                 MemInfoReader memInfo = null;
1976                 synchronized (ActivityManagerService.this) {
1977                     if (mFullPssPending) {
1978                         mFullPssPending = false;
1979                         memInfo = new MemInfoReader();
1980                     }
1981                 }
1982                 if (memInfo != null) {
1983                     updateCpuStatsNow();
1984                     long nativeTotalPss = 0;
1985                     final List<ProcessCpuTracker.Stats> stats;
1986                     synchronized (mProcessCpuTracker) {
1987                         stats = mProcessCpuTracker.getStats( (st)-> {
1988                             return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID;
1989                         });
1990                     }
1991                     final int N = stats.size();
1992                     for (int j = 0; j < N; j++) {
1993                         synchronized (mPidsSelfLocked) {
1994                             if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) {
1995                                 // This is one of our own processes; skip it.
1996                                 continue;
1997                             }
1998                         }
1999                         nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null);
2000                     }
2001                     memInfo.readMemInfo();
2002                     synchronized (ActivityManagerService.this) {
2003                         if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in "
2004                                 + (SystemClock.uptimeMillis()-start) + "ms");
2005                         final long cachedKb = memInfo.getCachedSizeKb();
2006                         final long freeKb = memInfo.getFreeSizeKb();
2007                         final long zramKb = memInfo.getZramTotalSizeKb();
2008                         final long kernelKb = memInfo.getKernelUsedSizeKb();
2009                         EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
2010                                 kernelKb*1024, nativeTotalPss*1024);
2011                         mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
2012                                 nativeTotalPss);
2013                     }
2014                 }
2015 
2016                 int num = 0;
2017                 long[] tmp = new long[3];
2018                 do {
2019                     ProcessRecord proc;
2020                     int procState;
2021                     int statType;
2022                     int pid = -1;
2023                     long lastPssTime;
2024                     synchronized (ActivityManagerService.this) {
2025                         if (mPendingPssProcesses.size() <= 0) {
2026                             if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS,
2027                                     "Collected pss of " + num + " processes in "
2028                                     + (SystemClock.uptimeMillis() - start) + "ms");
2029                             mPendingPssProcesses.clear();
2030                             return;
2031                         }
2032                         proc = mPendingPssProcesses.remove(0);
2033                         procState = proc.pssProcState;
2034                         statType = proc.pssStatType;
2035                         lastPssTime = proc.lastPssTime;
2036                         long now = SystemClock.uptimeMillis();
2037                         if (proc.thread != null && procState == proc.setProcState
2038                                 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
2039                                         < now) {
2040                             pid = proc.pid;
2041                         } else {
2042                             ProcessList.abortNextPssTime(proc.procStateMemTracker);
2043                             if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid +
2044                                     ": still need " +
2045                                     (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE-now) +
2046                                     "ms until safe");
2047                             proc = null;
2048                             pid = 0;
2049                         }
2050                     }
2051                     if (proc != null) {
2052                         long startTime = SystemClock.currentThreadTimeMillis();
2053                         // skip background PSS calculation of apps that are capturing
2054                         // camera imagery
2055                         final boolean usingCamera = isCameraActiveForUid(proc.uid);
2056                         long pss = usingCamera ? 0 : Debug.getPss(pid, tmp, null);
2057                         long endTime = SystemClock.currentThreadTimeMillis();
2058                         synchronized (ActivityManagerService.this) {
2059                             if (pss != 0 && proc.thread != null && proc.setProcState == procState
2060                                     && proc.pid == pid && proc.lastPssTime == lastPssTime) {
2061                                 num++;
2062                                 ProcessList.commitNextPssTime(proc.procStateMemTracker);
2063                                 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1], tmp[2],
2064                                         statType, endTime-startTime, SystemClock.uptimeMillis());
2065                             } else {
2066                                 ProcessList.abortNextPssTime(proc.procStateMemTracker);
2067                                 if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid +
2068                                         ": " + (proc.thread == null ? "NO_THREAD " : "") +
2069                                         (usingCamera ? "CAMERA " : "") +
2070                                         (proc.pid != pid ? "PID_CHANGED " : "") +
2071                                         " initState=" + procState + " curState=" +
2072                                         proc.setProcState + " " +
2073                                         (proc.lastPssTime != lastPssTime ? "TIME_CHANGED" : ""));
2074                             }
2075                         }
2076                     }
2077                 } while (true);
2078             }
2079 
2080             case DEFER_PSS_MSG: {
2081                 deferPssForActivityStart();
2082             } break;
2083 
2084             case STOP_DEFERRING_PSS_MSG: {
2085                 final int nesting = mActivityStartingNesting.decrementAndGet();
2086                 if (nesting <= 0) {
2087                     if (DEBUG_PSS) {
2088                         Slog.d(TAG_PSS, "PSS activity start deferral interval ended; now "
2089                                 + nesting);
2090                     }
2091                     if (nesting < 0) {
2092                         Slog.wtf(TAG, "Activity start nesting undercount!");
2093                         mActivityStartingNesting.incrementAndGet();
2094                     }
2095                 } else {
2096                     if (DEBUG_PSS) {
2097                         Slog.d(TAG_PSS, "Still deferring PSS, nesting=" + nesting);
2098                     }
2099                 }
2100             }
2101             break;
2102 
2103             }
2104         }
2105     };
2106 
setSystemProcess()2107     public void setSystemProcess() {
2108         try {
2109             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2110                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2111             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2112             ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2113                     DUMP_FLAG_PRIORITY_HIGH);
2114             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2115             ServiceManager.addService("dbinfo", new DbBinder(this));
2116             if (MONITOR_CPU_USAGE) {
2117                 ServiceManager.addService("cpuinfo", new CpuBinder(this),
2118                         /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2119             }
2120             ServiceManager.addService("permission", new PermissionController(this));
2121             ServiceManager.addService("processinfo", new ProcessInfoService(this));
2122             ServiceManager.addService("cacheinfo", new CacheBinder(this));
2123 
2124             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2125                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2126             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2127 
2128             synchronized (this) {
2129                 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
2130                         false,
2131                         0,
2132                         new HostingRecord("system"));
2133                 app.setPersistent(true);
2134                 app.pid = app.mPidForCompact = MY_PID;
2135                 app.getWindowProcessController().setPid(MY_PID);
2136                 app.maxAdj = ProcessList.SYSTEM_ADJ;
2137                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2138                 addPidLocked(app);
2139                 mProcessList.updateLruProcessLocked(app, false, null);
2140                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2141             }
2142         } catch (PackageManager.NameNotFoundException e) {
2143             throw new RuntimeException(
2144                     "Unable to find android system package", e);
2145         }
2146 
2147         // Start watching app ops after we and the package manager are up and running.
2148         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2149                 new IAppOpsCallback.Stub() {
2150                     @Override public void opChanged(int op, int uid, String packageName) {
2151                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2152                             if (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
2153                                     != AppOpsManager.MODE_ALLOWED) {
2154                                 runInBackgroundDisabled(uid);
2155                             }
2156                         }
2157                     }
2158                 });
2159 
2160         final int[] cameraOp = {AppOpsManager.OP_CAMERA};
2161         mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
2162             @Override
2163             public void opActiveChanged(int op, int uid, String packageName, boolean active) {
2164                 cameraActiveChanged(uid, active);
2165             }
2166         });
2167     }
2168 
setWindowManager(WindowManagerService wm)2169     public void setWindowManager(WindowManagerService wm) {
2170         synchronized (this) {
2171             mWindowManager = wm;
2172             mWmInternal = LocalServices.getService(WindowManagerInternal.class);
2173             mActivityTaskManager.setWindowManager(wm);
2174         }
2175     }
2176 
setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)2177     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2178         mUsageStatsService = usageStatsManager;
2179         mActivityTaskManager.setUsageStatsManager(usageStatsManager);
2180     }
2181 
2182     /**
2183      * Sets the internal content capture manager service.
2184      *
2185      * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock.
2186      */
setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2187     public void setContentCaptureManager(
2188             @Nullable ContentCaptureManagerInternal contentCaptureManager) {
2189         mContentCaptureService = contentCaptureManager;
2190     }
2191 
startObservingNativeCrashes()2192     public void startObservingNativeCrashes() {
2193         final NativeCrashListener ncl = new NativeCrashListener(this);
2194         ncl.start();
2195     }
2196 
getAppOpsService()2197     public IAppOpsService getAppOpsService() {
2198         return mAppOpsService;
2199     }
2200 
2201     static class MemBinder extends Binder {
2202         ActivityManagerService mActivityManagerService;
2203         private final PriorityDump.PriorityDumper mPriorityDumper =
2204                 new PriorityDump.PriorityDumper() {
2205             @Override
2206             public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args,
2207                     boolean asProto) {
2208                 dump(fd, pw, new String[] {"-a"}, asProto);
2209             }
2210 
2211             @Override
2212             public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
2213                 mActivityManagerService.dumpApplicationMemoryUsage(
2214                         fd, pw, "  ", args, false, null, asProto);
2215             }
2216         };
2217 
MemBinder(ActivityManagerService activityManagerService)2218         MemBinder(ActivityManagerService activityManagerService) {
2219             mActivityManagerService = activityManagerService;
2220         }
2221 
2222         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2223         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2224             try {
2225                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2226 
2227                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2228                         "meminfo", pw)) return;
2229                 PriorityDump.dump(mPriorityDumper, fd, pw, args);
2230             } finally {
2231                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2232             }
2233         }
2234     }
2235 
2236     static class GraphicsBinder extends Binder {
2237         ActivityManagerService mActivityManagerService;
GraphicsBinder(ActivityManagerService activityManagerService)2238         GraphicsBinder(ActivityManagerService activityManagerService) {
2239             mActivityManagerService = activityManagerService;
2240         }
2241 
2242         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2243         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2244             try {
2245                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2246 
2247                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2248                         "gfxinfo", pw)) return;
2249                 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2250             } finally {
2251                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2252             }
2253         }
2254     }
2255 
2256     static class DbBinder extends Binder {
2257         ActivityManagerService mActivityManagerService;
DbBinder(ActivityManagerService activityManagerService)2258         DbBinder(ActivityManagerService activityManagerService) {
2259             mActivityManagerService = activityManagerService;
2260         }
2261 
2262         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2263         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2264             try {
2265                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2266 
2267                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2268                         "dbinfo", pw)) return;
2269                 mActivityManagerService.dumpDbInfo(fd, pw, args);
2270             } finally {
2271                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2272             }
2273         }
2274     }
2275 
2276     static class CpuBinder extends Binder {
2277         ActivityManagerService mActivityManagerService;
2278         private final PriorityDump.PriorityDumper mPriorityDumper =
2279                 new PriorityDump.PriorityDumper() {
2280             @Override
2281             public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
2282                     boolean asProto) {
2283                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2284                         "cpuinfo", pw)) return;
2285                 synchronized (mActivityManagerService.mProcessCpuTracker) {
2286                     if (asProto) {
2287                         mActivityManagerService.mProcessCpuTracker.dumpProto(fd);
2288                         return;
2289                     }
2290                     pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2291                     pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2292                             SystemClock.uptimeMillis()));
2293                 }
2294             }
2295         };
2296 
CpuBinder(ActivityManagerService activityManagerService)2297         CpuBinder(ActivityManagerService activityManagerService) {
2298             mActivityManagerService = activityManagerService;
2299         }
2300 
2301         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2302         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2303             PriorityDump.dump(mPriorityDumper, fd, pw, args);
2304         }
2305     }
2306 
2307     static class CacheBinder extends Binder {
2308         ActivityManagerService mActivityManagerService;
2309 
CacheBinder(ActivityManagerService activityManagerService)2310         CacheBinder(ActivityManagerService activityManagerService) {
2311             mActivityManagerService = activityManagerService;
2312         }
2313 
2314         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2315         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2316             try {
2317                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
2318 
2319                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2320                         "cacheinfo", pw)) {
2321                     return;
2322                 }
2323 
2324                 mActivityManagerService.dumpBinderCacheContents(fd, pw, args);
2325             } finally {
2326                 mActivityManagerService.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
2327             }
2328         }
2329     }
2330 
2331     public static final class Lifecycle extends SystemService {
2332         private final ActivityManagerService mService;
2333         private static ActivityTaskManagerService sAtm;
2334 
Lifecycle(Context context)2335         public Lifecycle(Context context) {
2336             super(context);
2337             mService = new ActivityManagerService(context, sAtm);
2338         }
2339 
startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2340         public static ActivityManagerService startService(
2341                 SystemServiceManager ssm, ActivityTaskManagerService atm) {
2342             sAtm = atm;
2343             return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2344         }
2345 
2346         @Override
onStart()2347         public void onStart() {
2348             mService.start();
2349         }
2350 
2351         @Override
onBootPhase(int phase)2352         public void onBootPhase(int phase) {
2353             mService.mBootPhase = phase;
2354             if (phase == PHASE_SYSTEM_SERVICES_READY) {
2355                 mService.mBatteryStatsService.systemServicesReady();
2356                 mService.mServices.systemServicesReady();
2357             } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
2358                 mService.startBroadcastObservers();
2359             } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2360                 mService.mPackageWatchdog.onPackagesReady();
2361             }
2362         }
2363 
2364         @Override
onCleanupUser(int userId)2365         public void onCleanupUser(int userId) {
2366             mService.mBatteryStatsService.onCleanupUser(userId);
2367         }
2368 
getService()2369         public ActivityManagerService getService() {
2370             return mService;
2371         }
2372     }
2373 
maybeLogUserspaceRebootEvent()2374     private void maybeLogUserspaceRebootEvent() {
2375         if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) {
2376             return;
2377         }
2378         final int userId = mUserController.getCurrentUserId();
2379         if (userId != UserHandle.USER_SYSTEM) {
2380             // Only log for user0.
2381             return;
2382         }
2383         // TODO(b/148767783): should we check all profiles under user0?
2384         UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId),
2385                 BackgroundThread.getExecutor());
2386     }
2387 
2388     /**
2389      * Encapsulates global settings related to hidden API enforcement behaviour, including tracking
2390      * the latest value via a content observer.
2391      */
2392     static class HiddenApiSettings extends ContentObserver
2393             implements DeviceConfig.OnPropertiesChangedListener {
2394 
2395         private final Context mContext;
2396         private boolean mBlacklistDisabled;
2397         private String mExemptionsStr;
2398         private List<String> mExemptions = Collections.emptyList();
2399         private int mLogSampleRate = -1;
2400         private int mStatslogSampleRate = -1;
2401         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
2402 
2403         /**
2404          * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
2405          * the range 0 to 0x10000 inclusive.
2406          *
2407          * @hide
2408          */
2409         public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE =
2410                 "hidden_api_access_log_sampling_rate";
2411 
2412         /**
2413          * Sampling rate for hidden API access event logging with statslog, as an integer in the
2414          * range 0 to 0x10000 inclusive.
2415          *
2416          * @hide
2417          */
2418         public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
2419                 "hidden_api_access_statslog_sampling_rate";
2420 
onPropertiesChanged(DeviceConfig.Properties properties)2421         public void onPropertiesChanged(DeviceConfig.Properties properties) {
2422             int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0x0);
2423             if (logSampleRate < 0 || logSampleRate > 0x10000) {
2424                 logSampleRate = -1;
2425             }
2426             if (logSampleRate != -1 && logSampleRate != mLogSampleRate) {
2427                 mLogSampleRate = logSampleRate;
2428                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
2429             }
2430 
2431             int statslogSampleRate =
2432                     properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
2433             if (statslogSampleRate < 0 || statslogSampleRate > 0x10000) {
2434                 statslogSampleRate = -1;
2435             }
2436             if (statslogSampleRate != -1 && statslogSampleRate != mStatslogSampleRate) {
2437                 mStatslogSampleRate = statslogSampleRate;
2438                 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
2439             }
2440         }
2441 
HiddenApiSettings(Handler handler, Context context)2442         public HiddenApiSettings(Handler handler, Context context) {
2443             super(handler);
2444             mContext = context;
2445         }
2446 
registerObserver()2447         public void registerObserver() {
2448             mContext.getContentResolver().registerContentObserver(
2449                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
2450                     false,
2451                     this);
2452             mContext.getContentResolver().registerContentObserver(
2453                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
2454                     false,
2455                     this);
2456             DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT,
2457                     mContext.getMainExecutor(), this);
2458             update();
2459         }
2460 
update()2461         private void update() {
2462             String exemptions = Settings.Global.getString(mContext.getContentResolver(),
2463                     Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS);
2464             if (!TextUtils.equals(exemptions, mExemptionsStr)) {
2465                 mExemptionsStr = exemptions;
2466                 if ("*".equals(exemptions)) {
2467                     mBlacklistDisabled = true;
2468                     mExemptions = Collections.emptyList();
2469                 } else {
2470                     mBlacklistDisabled = false;
2471                     mExemptions = TextUtils.isEmpty(exemptions)
2472                             ? Collections.emptyList()
2473                             : Arrays.asList(exemptions.split(","));
2474                 }
2475                 if (!ZYGOTE_PROCESS.setApiBlacklistExemptions(mExemptions)) {
2476                   Slog.e(TAG, "Failed to set API blacklist exemptions!");
2477                   // leave mExemptionsStr as is, so we don't try to send the same list again.
2478                   mExemptions = Collections.emptyList();
2479                 }
2480             }
2481             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
2482         }
2483 
getValidEnforcementPolicy(String settingsKey)2484         private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) {
2485             int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey,
2486                     ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT);
2487             if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) {
2488                 return policy;
2489             } else {
2490                 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
2491             }
2492         }
2493 
isDisabled()2494         boolean isDisabled() {
2495             return mBlacklistDisabled;
2496         }
2497 
getPolicy()2498         @HiddenApiEnforcementPolicy int getPolicy() {
2499             return mPolicy;
2500         }
2501 
onChange(boolean selfChange)2502         public void onChange(boolean selfChange) {
2503             update();
2504         }
2505     }
2506 
getAppOpsManager()2507     AppOpsManager getAppOpsManager() {
2508         if (mAppOpsManager == null) {
2509             mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
2510         }
2511         return mAppOpsManager;
2512     }
2513 
2514     /**
2515      * Provides the basic functionality for activity task related tests when a handler thread is
2516      * given to initialize the dependency members.
2517      */
2518     @VisibleForTesting
ActivityManagerService(Injector injector, ServiceThread handlerThread)2519     public ActivityManagerService(Injector injector, ServiceThread handlerThread) {
2520         final boolean hasHandlerThread = handlerThread != null;
2521         mInjector = injector;
2522         mContext = mInjector.getContext();
2523         mUiContext = null;
2524         mAppErrors = null;
2525         mPackageWatchdog = null;
2526         mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */);
2527         mBatteryStatsService = null;
2528         mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null;
2529         mHandlerThread = handlerThread;
2530         mConstants = hasHandlerThread
2531                 ? new ActivityManagerConstants(mContext, this, mHandler) : null;
2532         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
2533         mPlatformCompat = null;
2534         mProcessList = injector.getProcessList(this);
2535         mProcessList.init(this, activeUids, mPlatformCompat);
2536         mLowMemDetector = null;
2537         mOomAdjuster = hasHandlerThread
2538                 ? new OomAdjuster(this, mProcessList, activeUids, handlerThread) : null;
2539 
2540         mIntentFirewall = hasHandlerThread
2541                 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null;
2542         mProcessCpuThread = null;
2543         mProcessStats = null;
2544         mProviderMap = null;
2545         // For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from
2546         // {@link ActivityStackSupervisor#cleanUpRemovedTaskLocked}.
2547         mServices = hasHandlerThread ? new ActiveServices(this) : null;
2548         mSystemThread = null;
2549         mUiHandler = injector.getUiHandler(null /* service */);
2550         mUserController = hasHandlerThread ? new UserController(this) : null;
2551         mPendingIntentController = hasHandlerThread
2552                 ? new PendingIntentController(handlerThread.getLooper(), mUserController,
2553                         mConstants) : null;
2554         mProcStartHandlerThread = null;
2555         mProcStartHandler = null;
2556         mHiddenApiBlacklist = null;
2557         mFactoryTest = FACTORY_TEST_OFF;
2558         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2559         mInternal = new LocalService();
2560         mPendingStartActivityUids = new PendingStartActivityUids(mContext);
2561     }
2562 
2563     // Note: This method is invoked on the main thread but may need to attach various
2564     // handlers to other threads.  So take care to be explicit about the looper.
ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2565     public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
2566         LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2567         mInjector = new Injector(systemContext);
2568         mContext = systemContext;
2569 
2570         mFactoryTest = FactoryTest.getMode();
2571         mSystemThread = ActivityThread.currentActivityThread();
2572         mUiContext = mSystemThread.getSystemUiContext();
2573 
2574         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2575 
2576         mHandlerThread = new ServiceThread(TAG,
2577                 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2578         mHandlerThread.start();
2579         mHandler = new MainHandler(mHandlerThread.getLooper());
2580         mUiHandler = mInjector.getUiHandler(this);
2581 
2582         mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2583                 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2584         mProcStartHandlerThread.start();
2585         mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
2586 
2587         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2588         final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2589         mPlatformCompat = (PlatformCompat) ServiceManager.getService(
2590                 Context.PLATFORM_COMPAT_SERVICE);
2591         mProcessList = mInjector.getProcessList(this);
2592         mProcessList.init(this, activeUids, mPlatformCompat);
2593         mLowMemDetector = new LowMemDetector(this);
2594         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2595 
2596         // Broadcast policy parameters
2597         final BroadcastConstants foreConstants = new BroadcastConstants(
2598                 Settings.Global.BROADCAST_FG_CONSTANTS);
2599         foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2600 
2601         final BroadcastConstants backConstants = new BroadcastConstants(
2602                 Settings.Global.BROADCAST_BG_CONSTANTS);
2603         backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2604 
2605         final BroadcastConstants offloadConstants = new BroadcastConstants(
2606                 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2607         offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2608         // by default, no "slow" policy in this queue
2609         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2610 
2611         mEnableOffloadQueue = SystemProperties.getBoolean(
2612                 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
2613 
2614         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2615                 "foreground", foreConstants, false);
2616         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2617                 "background", backConstants, true);
2618         mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
2619                 "offload", offloadConstants, true);
2620         mBroadcastQueues[0] = mFgBroadcastQueue;
2621         mBroadcastQueues[1] = mBgBroadcastQueue;
2622         mBroadcastQueues[2] = mOffloadBroadcastQueue;
2623 
2624         mServices = new ActiveServices(this);
2625         mProviderMap = new ProviderMap(this);
2626         mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2627         mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2628 
2629         final File systemDir = SystemServiceManager.ensureSystemDir();
2630 
2631         // TODO: Move creation of battery stats service outside of activity manager service.
2632         mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
2633                 BackgroundThread.get().getHandler());
2634         mBatteryStatsService.getActiveStatistics().readLocked();
2635         mBatteryStatsService.scheduleWriteToDisk();
2636         mOnBattery = DEBUG_POWER ? true
2637                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2638         mBatteryStatsService.getActiveStatistics().setCallback(this);
2639         mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2640 
2641         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2642 
2643         mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2644 
2645         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2646 
2647         mUserController = new UserController(this);
2648 
2649         mPendingIntentController = new PendingIntentController(
2650                 mHandlerThread.getLooper(), mUserController, mConstants);
2651 
2652         if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
2653             mUseFifoUiScheduling = true;
2654         }
2655 
2656         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2657         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2658 
2659         mActivityTaskManager = atm;
2660         mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2661                 DisplayThread.get().getLooper());
2662         mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2663 
2664         mProcessCpuThread = new Thread("CpuTracker") {
2665             @Override
2666             public void run() {
2667                 synchronized (mProcessCpuTracker) {
2668                     mProcessCpuInitLatch.countDown();
2669                     mProcessCpuTracker.init();
2670                 }
2671                 while (true) {
2672                     try {
2673                         try {
2674                             synchronized(this) {
2675                                 final long now = SystemClock.uptimeMillis();
2676                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2677                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2678                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2679                                 //        + ", write delay=" + nextWriteDelay);
2680                                 if (nextWriteDelay < nextCpuDelay) {
2681                                     nextCpuDelay = nextWriteDelay;
2682                                 }
2683                                 if (nextCpuDelay > 0) {
2684                                     mProcessCpuMutexFree.set(true);
2685                                     this.wait(nextCpuDelay);
2686                                 }
2687                             }
2688                         } catch (InterruptedException e) {
2689                         }
2690                         updateCpuStatsNow();
2691                     } catch (Exception e) {
2692                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
2693                     }
2694                 }
2695             }
2696         };
2697 
2698         mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2699 
2700         Watchdog.getInstance().addMonitor(this);
2701         Watchdog.getInstance().addThread(mHandler);
2702 
2703         // bind background threads to little cores
2704         // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2705         // make sure we've already adjusted system_server's internal view of itself first
2706         updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2707         try {
2708             Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2709                     Process.THREAD_GROUP_SYSTEM);
2710             Process.setThreadGroupAndCpuset(
2711                     mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
2712                     Process.THREAD_GROUP_SYSTEM);
2713         } catch (Exception e) {
2714             Slog.w(TAG, "Setting background thread cpuset failed");
2715         }
2716 
2717         mInternal = new LocalService();
2718         mPendingStartActivityUids = new PendingStartActivityUids(mContext);
2719     }
2720 
setSystemServiceManager(SystemServiceManager mgr)2721     public void setSystemServiceManager(SystemServiceManager mgr) {
2722         mSystemServiceManager = mgr;
2723     }
2724 
setInstaller(Installer installer)2725     public void setInstaller(Installer installer) {
2726         mInstaller = installer;
2727     }
2728 
start()2729     private void start() {
2730         removeAllProcessGroups();
2731         mProcessCpuThread.start();
2732 
2733         mBatteryStatsService.publish();
2734         mAppOpsService.publish();
2735         Slog.d("AppOps", "AppOpsService published");
2736         LocalServices.addService(ActivityManagerInternal.class, mInternal);
2737         mActivityTaskManager.onActivityManagerInternalAdded();
2738         mPendingIntentController.onActivityManagerInternalAdded();
2739         // Wait for the synchronized block started in mProcessCpuThread,
2740         // so that any other access to mProcessCpuTracker from main thread
2741         // will be blocked during mProcessCpuTracker initialization.
2742         try {
2743             mProcessCpuInitLatch.await();
2744         } catch (InterruptedException e) {
2745             Slog.wtf(TAG, "Interrupted wait during start", e);
2746             Thread.currentThread().interrupt();
2747             throw new IllegalStateException("Interrupted wait during start");
2748         }
2749     }
2750 
initPowerManagement()2751     public void initPowerManagement() {
2752         mActivityTaskManager.onInitPowerManagement();
2753         mBatteryStatsService.initPowerManagement();
2754         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2755     }
2756 
getBackgroundLaunchBroadcasts()2757     private ArraySet<String> getBackgroundLaunchBroadcasts() {
2758         if (mBackgroundLaunchBroadcasts == null) {
2759             mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2760         }
2761         return mBackgroundLaunchBroadcasts;
2762     }
2763 
2764     /**
2765      * Ensures that the given package name has an explicit set of allowed associations.
2766      * If it does not, give it an empty set.
2767      */
requireAllowedAssociationsLocked(String packageName)2768     void requireAllowedAssociationsLocked(String packageName) {
2769         ensureAllowedAssociations();
2770         if (mAllowedAssociations.get(packageName) == null) {
2771             mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName,
2772                     new ArraySet<>(), /* isDebuggable = */ false));
2773         }
2774     }
2775 
2776     /**
2777      * Returns true if the package {@code pkg1} running under user handle {@code uid1} is
2778      * allowed association with the package {@code pkg2} running under user handle {@code uid2}.
2779      * <p> If either of the packages are running as  part of the core system, then the
2780      * association is implicitly allowed.
2781      */
validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2782     boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) {
2783         ensureAllowedAssociations();
2784         // Interactions with the system uid are always allowed, since that is the core system
2785         // that everyone needs to be able to interact with. Also allow reflexive associations
2786         // within the same uid.
2787         if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID
2788                 || UserHandle.getAppId(uid2) == SYSTEM_UID) {
2789             return true;
2790         }
2791 
2792         // Check for association on both source and target packages.
2793         PackageAssociationInfo pai = mAllowedAssociations.get(pkg1);
2794         if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) {
2795             return false;
2796         }
2797         pai = mAllowedAssociations.get(pkg2);
2798         if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) {
2799             return false;
2800         }
2801         // If no explicit associations are provided in the manifest, then assume the app is
2802         // allowed associations with any package.
2803         return true;
2804     }
2805 
2806     /** Sets up allowed associations for system prebuilt packages from system config (if needed). */
ensureAllowedAssociations()2807     private void ensureAllowedAssociations() {
2808         if (mAllowedAssociations == null) {
2809             ArrayMap<String, ArraySet<String>> allowedAssociations =
2810                     SystemConfig.getInstance().getAllowedAssociations();
2811             mAllowedAssociations = new ArrayMap<>(allowedAssociations.size());
2812             PackageManagerInternal pm = getPackageManagerInternalLocked();
2813             for (int i = 0; i < allowedAssociations.size(); i++) {
2814                 final String pkg = allowedAssociations.keyAt(i);
2815                 final ArraySet<String> asc = allowedAssociations.valueAt(i);
2816 
2817                 // Query latest debuggable flag from package-manager.
2818                 boolean isDebuggable = false;
2819                 try {
2820                     ApplicationInfo ai = AppGlobals.getPackageManager()
2821                             .getApplicationInfo(pkg, MATCH_ALL, 0);
2822                     if (ai != null) {
2823                         isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2824                     }
2825                 } catch (RemoteException e) {
2826                     /* ignore */
2827                 }
2828                 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable));
2829             }
2830         }
2831     }
2832 
2833     /** Updates allowed associations for app info (specifically, based on debuggability).  */
updateAssociationForApp(ApplicationInfo appInfo)2834     private void updateAssociationForApp(ApplicationInfo appInfo) {
2835         ensureAllowedAssociations();
2836         PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName);
2837         if (pai != null) {
2838             pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
2839         }
2840     }
2841 
2842     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)2843     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2844             throws RemoteException {
2845         if (code == SYSPROPS_TRANSACTION) {
2846             // We need to tell all apps about the system property change.
2847             ArrayList<IBinder> procs = new ArrayList<IBinder>();
2848             synchronized (this) {
2849                 final int NP = mProcessList.mProcessNames.getMap().size();
2850                 for (int ip = 0; ip < NP; ip++) {
2851                     SparseArray<ProcessRecord> apps =
2852                             mProcessList.mProcessNames.getMap().valueAt(ip);
2853                     final int NA = apps.size();
2854                     for (int ia = 0; ia < NA; ia++) {
2855                         ProcessRecord app = apps.valueAt(ia);
2856                         if (app.thread != null) {
2857                             procs.add(app.thread.asBinder());
2858                         }
2859                     }
2860                 }
2861             }
2862 
2863             int N = procs.size();
2864             for (int i=0; i<N; i++) {
2865                 Parcel data2 = Parcel.obtain();
2866                 try {
2867                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2868                             Binder.FLAG_ONEWAY);
2869                 } catch (RemoteException e) {
2870                 }
2871                 data2.recycle();
2872             }
2873         }
2874         try {
2875             return super.onTransact(code, data, reply, flags);
2876         } catch (RuntimeException e) {
2877             // The activity manager only throws certain exceptions intentionally, so let's
2878             // log all others.
2879             if (!(e instanceof SecurityException
2880                     || e instanceof IllegalArgumentException
2881                     || e instanceof IllegalStateException)) {
2882                 Slog.wtf(TAG, "Activity Manager Crash."
2883                         + " UID:" + Binder.getCallingUid()
2884                         + " PID:" + Binder.getCallingPid()
2885                         + " TRANS:" + code, e);
2886             }
2887             throw e;
2888         }
2889     }
2890 
updateCpuStats()2891     void updateCpuStats() {
2892         final long now = SystemClock.uptimeMillis();
2893         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2894             return;
2895         }
2896         if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2897             synchronized (mProcessCpuThread) {
2898                 mProcessCpuThread.notify();
2899             }
2900         }
2901     }
2902 
updateCpuStatsNow()2903     void updateCpuStatsNow() {
2904         synchronized (mProcessCpuTracker) {
2905             mProcessCpuMutexFree.set(false);
2906             final long now = SystemClock.uptimeMillis();
2907             boolean haveNewCpuStats = false;
2908 
2909             if (MONITOR_CPU_USAGE &&
2910                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2911                 mLastCpuTime.set(now);
2912                 mProcessCpuTracker.update();
2913                 if (mProcessCpuTracker.hasGoodLastStats()) {
2914                     haveNewCpuStats = true;
2915                     //Slog.i(TAG, mProcessCpu.printCurrentState());
2916                     //Slog.i(TAG, "Total CPU usage: "
2917                     //        + mProcessCpu.getTotalCpuPercent() + "%");
2918 
2919                     // Slog the cpu usage if the property is set.
2920                     if ("true".equals(SystemProperties.get("events.cpu"))) {
2921                         int user = mProcessCpuTracker.getLastUserTime();
2922                         int system = mProcessCpuTracker.getLastSystemTime();
2923                         int iowait = mProcessCpuTracker.getLastIoWaitTime();
2924                         int irq = mProcessCpuTracker.getLastIrqTime();
2925                         int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2926                         int idle = mProcessCpuTracker.getLastIdleTime();
2927 
2928                         int total = user + system + iowait + irq + softIrq + idle;
2929                         if (total == 0) total = 1;
2930 
2931                         EventLogTags.writeCpu(
2932                                 ((user + system + iowait + irq + softIrq) * 100) / total,
2933                                 (user * 100) / total,
2934                                 (system * 100) / total,
2935                                 (iowait * 100) / total,
2936                                 (irq * 100) / total,
2937                                 (softIrq * 100) / total);
2938                     }
2939                 }
2940             }
2941 
2942             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
2943             synchronized(bstats) {
2944                 synchronized(mPidsSelfLocked) {
2945                     if (haveNewCpuStats) {
2946                         if (bstats.startAddingCpuLocked()) {
2947                             int totalUTime = 0;
2948                             int totalSTime = 0;
2949                             final int N = mProcessCpuTracker.countStats();
2950                             for (int i=0; i<N; i++) {
2951                                 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
2952                                 if (!st.working) {
2953                                     continue;
2954                                 }
2955                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
2956                                 totalUTime += st.rel_utime;
2957                                 totalSTime += st.rel_stime;
2958                                 if (pr != null) {
2959                                     BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
2960                                     if (ps == null || !ps.isActive()) {
2961                                         pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
2962                                                 pr.info.uid, pr.processName);
2963                                     }
2964                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2965                                     pr.curCpuTime += st.rel_utime + st.rel_stime;
2966                                     if (pr.lastCpuTime == 0) {
2967                                         pr.lastCpuTime = pr.curCpuTime;
2968                                     }
2969                                 } else {
2970                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
2971                                     if (ps == null || !ps.isActive()) {
2972                                         st.batteryStats = ps = bstats.getProcessStatsLocked(
2973                                                 bstats.mapUid(st.uid), st.name);
2974                                     }
2975                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2976                                 }
2977                             }
2978                             final int userTime = mProcessCpuTracker.getLastUserTime();
2979                             final int systemTime = mProcessCpuTracker.getLastSystemTime();
2980                             final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime();
2981                             final int irqTime = mProcessCpuTracker.getLastIrqTime();
2982                             final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime();
2983                             final int idleTime = mProcessCpuTracker.getLastIdleTime();
2984                             bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime,
2985                                     systemTime, iowaitTime, irqTime, softIrqTime, idleTime);
2986                         }
2987                     }
2988                 }
2989 
2990                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2991                     mLastWriteTime = now;
2992                     mBatteryStatsService.scheduleWriteToDisk();
2993                 }
2994             }
2995         }
2996     }
2997 
2998     @Override
batteryNeedsCpuUpdate()2999     public void batteryNeedsCpuUpdate() {
3000         updateCpuStatsNow();
3001     }
3002 
3003     @Override
batteryPowerChanged(boolean onBattery)3004     public void batteryPowerChanged(boolean onBattery) {
3005         // When plugging in, update the CPU stats first before changing
3006         // the plug state.
3007         updateCpuStatsNow();
3008         synchronized (this) {
3009             synchronized(mPidsSelfLocked) {
3010                 mOnBattery = DEBUG_POWER ? true : onBattery;
3011             }
3012             mOomAdjProfiler.batteryPowerChanged(onBattery);
3013         }
3014     }
3015 
3016     @Override
batteryStatsReset()3017     public void batteryStatsReset() {
3018         mOomAdjProfiler.reset();
3019     }
3020 
3021     @Override
batterySendBroadcast(Intent intent)3022     public void batterySendBroadcast(Intent intent) {
3023         synchronized (this) {
3024             broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
3025                     OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
3026                     Binder.getCallingPid(), UserHandle.USER_ALL);
3027         }
3028     }
3029 
3030     /**
3031      * Initialize the application bind args. These are passed to each
3032      * process when the bindApplication() IPC is sent to the process. They're
3033      * lazily setup to make sure the services are running when they're asked for.
3034      */
getCommonServicesLocked(boolean isolated)3035     private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
3036         // Isolated processes won't get this optimization, so that we don't
3037         // violate the rules about which services they have access to.
3038         if (isolated) {
3039             if (mIsolatedAppBindArgs == null) {
3040                 mIsolatedAppBindArgs = new ArrayMap<>(1);
3041                 addServiceToMap(mIsolatedAppBindArgs, "package");
3042                 addServiceToMap(mIsolatedAppBindArgs, "permissionmgr");
3043             }
3044             return mIsolatedAppBindArgs;
3045         }
3046 
3047         if (mAppBindArgs == null) {
3048             mAppBindArgs = new ArrayMap<>();
3049 
3050             // Add common services.
3051             // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too.
3052             // Enable the check in ApplicationThread.bindApplication() to make sure.
3053             addServiceToMap(mAppBindArgs, "package");
3054             addServiceToMap(mAppBindArgs, "permissionmgr");
3055             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
3056             addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE);
3057             addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE);
3058             addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE);
3059             addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE);
3060             addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE);
3061             addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
3062             addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
3063             addServiceToMap(mAppBindArgs, "graphicsstats");
3064             addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
3065             addServiceToMap(mAppBindArgs, "content");
3066             addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
3067             addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
3068             addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
3069             addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
3070             addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
3071             addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
3072             addServiceToMap(mAppBindArgs, "mount");
3073         }
3074         return mAppBindArgs;
3075     }
3076 
addServiceToMap(ArrayMap<String, IBinder> map, String name)3077     private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) {
3078         final IBinder service = ServiceManager.getService(name);
3079         if (service != null) {
3080             map.put(name, service);
3081             if (false) {
3082                 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache.");
3083             }
3084         }
3085     }
3086 
3087     @Override
setFocusedStack(int stackId)3088     public void setFocusedStack(int stackId) {
3089         mActivityTaskManager.setFocusedStack(stackId);
3090     }
3091 
3092     /** Sets the task stack listener that gets callbacks when a task stack changes. */
3093     @Override
registerTaskStackListener(ITaskStackListener listener)3094     public void registerTaskStackListener(ITaskStackListener listener) {
3095         mActivityTaskManager.registerTaskStackListener(listener);
3096     }
3097 
3098     /**
3099      * Unregister a task stack listener so that it stops receiving callbacks.
3100      */
3101     @Override
unregisterTaskStackListener(ITaskStackListener listener)3102     public void unregisterTaskStackListener(ITaskStackListener listener) {
3103         mActivityTaskManager.unregisterTaskStackListener(listener);
3104     }
3105 
updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)3106     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
3107             ProcessRecord client) {
3108         mProcessList.updateLruProcessLocked(app, activityChange, client);
3109     }
3110 
removeLruProcessLocked(ProcessRecord app)3111     final void removeLruProcessLocked(ProcessRecord app) {
3112         mProcessList.removeLruProcessLocked(app);
3113     }
3114 
getProcessRecordLocked(String processName, int uid, boolean keepIfLarge)3115     final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
3116         return mProcessList.getProcessRecordLocked(processName, uid, keepIfLarge);
3117     }
3118 
getProcessNames()3119     final ProcessMap<ProcessRecord> getProcessNames() {
3120         return mProcessList.mProcessNames;
3121     }
3122 
notifyPackageUse(String packageName, int reason)3123     void notifyPackageUse(String packageName, int reason) {
3124         synchronized(this) {
3125             getPackageManagerInternalLocked().notifyPackageUse(packageName, reason);
3126         }
3127     }
3128 
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)3129     boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
3130             String processName, String abiOverride, int uid, Runnable crashHandler) {
3131         synchronized(this) {
3132             ApplicationInfo info = new ApplicationInfo();
3133             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
3134             // For isolated processes, the former contains the parent's uid and the latter the
3135             // actual uid of the isolated process.
3136             // In the special case introduced by this method (which is, starting an isolated
3137             // process directly from the SystemServer without an actual parent app process) the
3138             // closest thing to a parent's uid is SYSTEM_UID.
3139             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
3140             // the |isolated| logic in the ProcessRecord constructor.
3141             info.uid = SYSTEM_UID;
3142             info.processName = processName;
3143             info.className = entryPoint;
3144             info.packageName = "android";
3145             info.seInfoUser = SELinuxUtil.COMPLETE_STR;
3146             info.targetSdkVersion = Build.VERSION.SDK_INT;
3147             ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */,
3148                     false /* knownToBeDead */, 0 /* intentFlags */,
3149                     sNullHostingRecord  /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY,
3150                     true /* allowWhileBooting */, true /* isolated */,
3151                     uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
3152                     crashHandler);
3153             return proc != null;
3154         }
3155     }
3156 
3157     @GuardedBy("this")
startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge)3158     final ProcessRecord startProcessLocked(String processName,
3159             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3160             HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
3161             boolean isolated, boolean keepIfLarge) {
3162         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
3163                 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
3164                 keepIfLarge, null /* ABI override */, null /* entryPoint */,
3165                 null /* entryPointArgs */, null /* crashHandler */);
3166     }
3167 
isAllowedWhileBooting(ApplicationInfo ai)3168     boolean isAllowedWhileBooting(ApplicationInfo ai) {
3169         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
3170     }
3171 
3172     /**
3173      * Update battery stats on the activity' usage.
3174      * @param activity
3175      * @param uid
3176      * @param userId
3177      * @param resumed
3178      */
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)3179     void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) {
3180         if (DEBUG_SWITCH) {
3181             Slog.d(TAG_SWITCH,
3182                     "updateBatteryStats: comp=" + activity + "res=" + resumed);
3183         }
3184         final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3185         FrameworkStatsLog.write(FrameworkStatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED,
3186                 uid, activity.getPackageName(), activity.getShortClassName(),
3187                 resumed ? FrameworkStatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__FOREGROUND :
3188                         FrameworkStatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__BACKGROUND);
3189         synchronized (stats) {
3190             if (resumed) {
3191                 stats.noteActivityResumedLocked(uid);
3192             } else {
3193                 stats.noteActivityPausedLocked(uid);
3194             }
3195         }
3196     }
3197 
3198     /**
3199      * Update UsageStas on the activity's usage.
3200      * @param activity
3201      * @param userId
3202      * @param event
3203      * @param appToken ActivityRecord's appToken.
3204      * @param taskRoot Task's root
3205      */
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)3206     public void updateActivityUsageStats(ComponentName activity, int userId, int event,
3207             IBinder appToken, ComponentName taskRoot) {
3208         if (DEBUG_SWITCH) {
3209             Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp="
3210                     + activity + " hash=" + appToken.hashCode() + " event=" + event);
3211         }
3212         synchronized (this) {
3213             if (mUsageStatsService != null) {
3214                 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(),
3215                         taskRoot);
3216             }
3217         }
3218         if (mContentCaptureService != null && (event == Event.ACTIVITY_PAUSED
3219                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED
3220                 || event == Event.ACTIVITY_DESTROYED)) {
3221             mContentCaptureService.notifyActivityEvent(userId, activity, event);
3222         }
3223     }
3224 
3225     /**
3226      * Update UsageStats on this package's usage.
3227      * @param packageName
3228      * @param userId
3229      * @param event
3230      */
updateActivityUsageStats(String packageName, int userId, int event)3231     public void updateActivityUsageStats(String packageName, int userId, int event) {
3232         if (DEBUG_SWITCH) {
3233             Slog.d(TAG_SWITCH, "updateActivityUsageStats: package="
3234                     + packageName + " event=" + event);
3235         }
3236         synchronized (this) {
3237             if (mUsageStatsService != null) {
3238                 mUsageStatsService.reportEvent(packageName, userId, event);
3239             }
3240         }
3241     }
3242 
3243     /**
3244      * Update Usages on this foreground service's usage.
3245      * @param service
3246      * @param userId
3247      * @param started
3248      */
updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3249     void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) {
3250         if (DEBUG_SWITCH) {
3251             Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp="
3252                     + service + " started=" + started);
3253         }
3254         synchronized (this) {
3255             if (mUsageStatsService != null) {
3256                 mUsageStatsService.reportEvent(service, userId,
3257                         started ? UsageEvents.Event.FOREGROUND_SERVICE_START
3258                                 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null);
3259             }
3260         }
3261     }
3262 
compatibilityInfoForPackage(ApplicationInfo ai)3263     CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
3264         return mAtmInternal.compatibilityInfoForPackage(ai);
3265     }
3266 
enforceNotIsolatedCaller(String caller)3267     /* package */ void enforceNotIsolatedCaller(String caller) {
3268         if (UserHandle.isIsolated(Binder.getCallingUid())) {
3269             throw new SecurityException("Isolated process not allowed to call " + caller);
3270         }
3271     }
3272 
3273     @Override
setPackageScreenCompatMode(String packageName, int mode)3274     public void setPackageScreenCompatMode(String packageName, int mode) {
3275         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
3276     }
3277 
hasUsageStatsPermission(String callingPackage)3278     private boolean hasUsageStatsPermission(String callingPackage) {
3279         final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS,
3280                 Binder.getCallingUid(), callingPackage, null, false, "", false);
3281         if (mode == AppOpsManager.MODE_DEFAULT) {
3282             return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3283                     == PackageManager.PERMISSION_GRANTED;
3284         }
3285         return mode == AppOpsManager.MODE_ALLOWED;
3286     }
3287 
3288     @Override
getPackageProcessState(String packageName, String callingPackage)3289     public int getPackageProcessState(String packageName, String callingPackage) {
3290         if (!hasUsageStatsPermission(callingPackage)) {
3291             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
3292                     "getPackageProcessState");
3293         }
3294 
3295         int procState = PROCESS_STATE_NONEXISTENT;
3296         synchronized (this) {
3297             for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) {
3298                 final ProcessRecord proc = mProcessList.mLruProcesses.get(i);
3299                 if (procState > proc.setProcState) {
3300                     if (proc.pkgList.containsKey(packageName) ||
3301                             (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) {
3302                         procState = proc.setProcState;
3303                     }
3304                 }
3305             }
3306         }
3307         return procState;
3308     }
3309 
3310     @Override
setProcessMemoryTrimLevel(String process, int userId, int level)3311     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
3312             throws RemoteException {
3313         if (!isCallerShell()) {
3314             EventLog.writeEvent(0x534e4554, 160390416, Binder.getCallingUid(), "");
3315             throw new SecurityException("Only shell can call it");
3316         }
3317         synchronized (this) {
3318             final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
3319             if (app == null) {
3320                 throw new IllegalArgumentException("Unknown process: " + process);
3321             }
3322             if (app.thread == null) {
3323                 throw new IllegalArgumentException("Process has no app thread");
3324             }
3325             if (app.trimMemoryLevel >= level) {
3326                 throw new IllegalArgumentException(
3327                         "Unable to set a higher trim level than current level");
3328             }
3329             if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
3330                     app.getCurProcState() > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) {
3331                 throw new IllegalArgumentException("Unable to set a background trim level "
3332                     + "on a foreground process");
3333             }
3334             app.thread.scheduleTrimMemory(level);
3335             app.trimMemoryLevel = level;
3336             return true;
3337         }
3338     }
3339 
dispatchProcessesChanged()3340     private void dispatchProcessesChanged() {
3341         int N;
3342         synchronized (this) {
3343             N = mPendingProcessChanges.size();
3344             if (mActiveProcessChanges.length < N) {
3345                 mActiveProcessChanges = new ProcessChangeItem[N];
3346             }
3347             mPendingProcessChanges.toArray(mActiveProcessChanges);
3348             mPendingProcessChanges.clear();
3349             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3350                     "*** Delivering " + N + " process changes");
3351         }
3352 
3353         int i = mProcessObservers.beginBroadcast();
3354         while (i > 0) {
3355             i--;
3356             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3357             if (observer != null) {
3358                 try {
3359                     for (int j=0; j<N; j++) {
3360                         ProcessChangeItem item = mActiveProcessChanges[j];
3361                         if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
3362                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3363                                     "ACTIVITIES CHANGED pid=" + item.pid + " uid="
3364                                     + item.uid + ": " + item.foregroundActivities);
3365                             observer.onForegroundActivitiesChanged(item.pid, item.uid,
3366                                     item.foregroundActivities);
3367                         }
3368                         if ((item.changes & ProcessChangeItem.CHANGE_FOREGROUND_SERVICES) != 0) {
3369                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3370                                     "FOREGROUND SERVICES CHANGED pid=" + item.pid + " uid="
3371                                             + item.uid + ": " + item.foregroundServiceTypes);
3372                             observer.onForegroundServicesChanged(item.pid, item.uid,
3373                                     item.foregroundServiceTypes);
3374                         }
3375                     }
3376                 } catch (RemoteException e) {
3377                 }
3378             }
3379         }
3380         mProcessObservers.finishBroadcast();
3381 
3382         synchronized (this) {
3383             for (int j=0; j<N; j++) {
3384                 mAvailProcessChanges.add(mActiveProcessChanges[j]);
3385             }
3386         }
3387     }
3388 
3389     @GuardedBy("this")
enqueueProcessChangeItemLocked(int pid, int uid)3390     ProcessChangeItem enqueueProcessChangeItemLocked(int pid, int uid) {
3391         int i = mPendingProcessChanges.size()-1;
3392         ActivityManagerService.ProcessChangeItem item = null;
3393         while (i >= 0) {
3394             item = mPendingProcessChanges.get(i);
3395             if (item.pid == pid) {
3396                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3397                         "Re-using existing item: " + item);
3398                 break;
3399             }
3400             i--;
3401         }
3402 
3403         if (i < 0) {
3404             // No existing item in pending changes; need a new one.
3405             final int NA = mAvailProcessChanges.size();
3406             if (NA > 0) {
3407                 item = mAvailProcessChanges.remove(NA-1);
3408                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3409                         "Retrieving available item: " + item);
3410             } else {
3411                 item = new ActivityManagerService.ProcessChangeItem();
3412                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3413                         "Allocating new item: " + item);
3414             }
3415             item.changes = 0;
3416             item.pid = pid;
3417             item.uid = uid;
3418             if (mPendingProcessChanges.size() == 0) {
3419                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3420                         "*** Enqueueing dispatch processes changed!");
3421                 mUiHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED_UI_MSG)
3422                         .sendToTarget();
3423             }
3424             mPendingProcessChanges.add(item);
3425         }
3426 
3427         return item;
3428     }
3429 
dispatchProcessDied(int pid, int uid)3430     private void dispatchProcessDied(int pid, int uid) {
3431         int i = mProcessObservers.beginBroadcast();
3432         while (i > 0) {
3433             i--;
3434             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3435             if (observer != null) {
3436                 try {
3437                     observer.onProcessDied(pid, uid);
3438                 } catch (RemoteException e) {
3439                 }
3440             }
3441         }
3442         mProcessObservers.finishBroadcast();
3443     }
3444 
3445     @VisibleForTesting
dispatchUidsChanged()3446     void dispatchUidsChanged() {
3447         int N;
3448         synchronized (this) {
3449             N = mPendingUidChanges.size();
3450             if (mActiveUidChanges.length < N) {
3451                 mActiveUidChanges = new UidRecord.ChangeItem[N];
3452             }
3453             for (int i=0; i<N; i++) {
3454                 final UidRecord.ChangeItem change = mPendingUidChanges.get(i);
3455                 mActiveUidChanges[i] = change;
3456                 if (change.uidRecord != null) {
3457                     change.uidRecord.pendingChange = null;
3458                     change.uidRecord = null;
3459                 }
3460             }
3461             mPendingUidChanges.clear();
3462             if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3463                     "*** Delivering " + N + " uid changes");
3464         }
3465 
3466         mUidChangeDispatchCount += N;
3467         int i = mUidObservers.beginBroadcast();
3468         while (i > 0) {
3469             i--;
3470             dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i),
3471                     (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N);
3472         }
3473         mUidObservers.finishBroadcast();
3474 
3475         if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) {
3476             for (int j = 0; j < N; ++j) {
3477                 final UidRecord.ChangeItem item = mActiveUidChanges[j];
3478                 if ((item.change & UidRecord.CHANGE_GONE) != 0) {
3479                     mValidateUids.remove(item.uid);
3480                 } else {
3481                     UidRecord validateUid = mValidateUids.get(item.uid);
3482                     if (validateUid == null) {
3483                         validateUid = new UidRecord(item.uid);
3484                         mValidateUids.put(item.uid, validateUid);
3485                     }
3486                     if ((item.change & UidRecord.CHANGE_IDLE) != 0) {
3487                         validateUid.idle = true;
3488                     } else if ((item.change & UidRecord.CHANGE_ACTIVE) != 0) {
3489                         validateUid.idle = false;
3490                     }
3491                     validateUid.setCurProcState(validateUid.setProcState = item.processState);
3492                     validateUid.curCapability = validateUid.setCapability = item.capability;
3493                     validateUid.lastDispatchedProcStateSeq = item.procStateSeq;
3494                 }
3495             }
3496         }
3497 
3498         synchronized (this) {
3499             for (int j = 0; j < N; j++) {
3500                 mAvailUidChanges.add(mActiveUidChanges[j]);
3501             }
3502         }
3503     }
3504 
dispatchUidsChangedForObserver(IUidObserver observer, UidObserverRegistration reg, int changesSize)3505     private void dispatchUidsChangedForObserver(IUidObserver observer,
3506             UidObserverRegistration reg, int changesSize) {
3507         if (observer == null) {
3508             return;
3509         }
3510         try {
3511             for (int j = 0; j < changesSize; j++) {
3512                 UidRecord.ChangeItem item = mActiveUidChanges[j];
3513                 final int change = item.change;
3514                 if (change == UidRecord.CHANGE_PROCSTATE &&
3515                         (reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) == 0) {
3516                     // No-op common case: no significant change, the observer is not
3517                     // interested in all proc state changes.
3518                     continue;
3519                 }
3520                 final long start = SystemClock.uptimeMillis();
3521                 if ((change & UidRecord.CHANGE_IDLE) != 0) {
3522                     if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) {
3523                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3524                                 "UID idle uid=" + item.uid);
3525                         observer.onUidIdle(item.uid, item.ephemeral);
3526                     }
3527                 } else if ((change & UidRecord.CHANGE_ACTIVE) != 0) {
3528                     if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
3529                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3530                                 "UID active uid=" + item.uid);
3531                         observer.onUidActive(item.uid);
3532                     }
3533                 }
3534                 if ((reg.which & ActivityManager.UID_OBSERVER_CACHED) != 0) {
3535                     if ((change & UidRecord.CHANGE_CACHED) != 0) {
3536                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3537                                 "UID cached uid=" + item.uid);
3538                         observer.onUidCachedChanged(item.uid, true);
3539                     } else if ((change & UidRecord.CHANGE_UNCACHED) != 0) {
3540                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3541                                 "UID active uid=" + item.uid);
3542                         observer.onUidCachedChanged(item.uid, false);
3543                     }
3544                 }
3545                 if ((change & UidRecord.CHANGE_GONE) != 0) {
3546                     if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) {
3547                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3548                                 "UID gone uid=" + item.uid);
3549                         observer.onUidGone(item.uid, item.ephemeral);
3550                     }
3551                     if (reg.lastProcStates != null) {
3552                         reg.lastProcStates.delete(item.uid);
3553                     }
3554                 } else {
3555                     if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
3556                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3557                                 "UID CHANGED uid=" + item.uid
3558                                         + ": " + item.processState + ": " + item.capability);
3559                         boolean doReport = true;
3560                         if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
3561                             final int lastState = reg.lastProcStates.get(item.uid,
3562                                     ActivityManager.PROCESS_STATE_UNKNOWN);
3563                             if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) {
3564                                 final boolean lastAboveCut = lastState <= reg.cutpoint;
3565                                 final boolean newAboveCut = item.processState <= reg.cutpoint;
3566                                 doReport = lastAboveCut != newAboveCut;
3567                             } else {
3568                                 doReport = item.processState != PROCESS_STATE_NONEXISTENT;
3569                             }
3570                         }
3571                         if (doReport) {
3572                             if (reg.lastProcStates != null) {
3573                                 reg.lastProcStates.put(item.uid, item.processState);
3574                             }
3575                             observer.onUidStateChanged(item.uid, item.processState,
3576                                     item.procStateSeq, item.capability);
3577                         }
3578                     }
3579                 }
3580                 final int duration = (int) (SystemClock.uptimeMillis() - start);
3581                 if (reg.mMaxDispatchTime < duration) {
3582                     reg.mMaxDispatchTime = duration;
3583                 }
3584                 if (duration >= SLOW_UID_OBSERVER_THRESHOLD_MS) {
3585                     reg.mSlowDispatchCount++;
3586                 }
3587             }
3588         } catch (RemoteException e) {
3589         }
3590     }
3591 
dispatchOomAdjObserver(String msg)3592     void dispatchOomAdjObserver(String msg) {
3593         OomAdjObserver observer;
3594         synchronized (this) {
3595             observer = mCurOomAdjObserver;
3596         }
3597 
3598         if (observer != null) {
3599             observer.onOomAdjMessage(msg);
3600         }
3601     }
3602 
setOomAdjObserver(int uid, OomAdjObserver observer)3603     void setOomAdjObserver(int uid, OomAdjObserver observer) {
3604         synchronized (this) {
3605             mCurOomAdjUid = uid;
3606             mCurOomAdjObserver = observer;
3607         }
3608     }
3609 
clearOomAdjObserver()3610     void clearOomAdjObserver() {
3611         synchronized (this) {
3612             mCurOomAdjUid = -1;
3613             mCurOomAdjObserver = null;
3614         }
3615     }
3616 
reportOomAdjMessageLocked(String tag, String msg)3617     void reportOomAdjMessageLocked(String tag, String msg) {
3618         Slog.d(tag, msg);
3619         if (mCurOomAdjObserver != null) {
3620             mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3621         }
3622     }
3623 
reportUidInfoMessageLocked(String tag, String msg, int uid)3624     void reportUidInfoMessageLocked(String tag, String msg, int uid) {
3625         Slog.i(TAG, msg);
3626         if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) {
3627             mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3628         }
3629 
3630     }
3631 
3632     /**
3633      * @deprecated use {@link #startActivityWithFeature} instead
3634      */
3635     @Deprecated
3636     @Override
startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3637     public int startActivity(IApplicationThread caller, String callingPackage,
3638             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3639             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
3640         return mActivityTaskManager.startActivity(caller, callingPackage, null, intent,
3641                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3642     }
3643 
3644     @Override
startActivityWithFeature(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3645     public int startActivityWithFeature(IApplicationThread caller, String callingPackage,
3646             String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
3647             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
3648             Bundle bOptions) {
3649         return mActivityTaskManager.startActivity(caller, callingPackage, callingFeatureId, intent,
3650                 resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3651     }
3652 
3653     /**
3654      * @deprecated use {@link #startActivityAsUserWithFeature} instead
3655      */
3656     @Deprecated
3657     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3658     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3659             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3660             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3661         return startActivityAsUserWithFeature(caller, callingPackage, null, intent, resolvedType,
3662                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId);
3663     }
3664 
3665     @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)3666     public final int startActivityAsUserWithFeature(IApplicationThread caller,
3667             String callingPackage, String callingFeatureId, Intent intent, String resolvedType,
3668             IBinder resultTo, String resultWho, int requestCode, int startFlags,
3669             ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3670         return mActivityTaskManager.startActivityAsUser(caller, callingPackage,
3671                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
3672                     startFlags, profilerInfo, bOptions, userId);
3673     }
3674 
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)3675     WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3676             @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
3677             String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
3678             Bundle bOptions, int userId) {
3679             return mActivityTaskManager.startActivityAndWait(caller, callingPackage,
3680                     callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode,
3681                     startFlags, profilerInfo, bOptions, userId);
3682     }
3683 
3684     @Override
startActivityFromRecents(int taskId, Bundle bOptions)3685     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
3686         return mActivityTaskManager.startActivityFromRecents(taskId, bOptions);
3687     }
3688 
3689     @Override
startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver, IRecentsAnimationRunner recentsAnimationRunner)3690     public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
3691             IRecentsAnimationRunner recentsAnimationRunner) {
3692         mActivityTaskManager.startRecentsActivity(
3693                 intent, assistDataReceiver, recentsAnimationRunner);
3694     }
3695 
3696     @Override
cancelRecentsAnimation(boolean restoreHomeStackPosition)3697     public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
3698         mActivityTaskManager.cancelRecentsAnimation(restoreHomeStackPosition);
3699     }
3700 
3701     /**
3702      * This is the internal entry point for handling Activity.finish().
3703      *
3704      * @param token The Binder token referencing the Activity we want to finish.
3705      * @param resultCode Result code, if any, from this Activity.
3706      * @param resultData Result data (Intent), if any, from this Activity.
3707      * @param finishTask Whether to finish the task associated with this Activity.
3708      *
3709      * @return Returns true if the activity successfully finished, or false if it is still running.
3710      */
3711     @Override
finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3712     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
3713             int finishTask) {
3714         return mActivityTaskManager.finishActivity(token, resultCode, resultData, finishTask);
3715     }
3716 
3717     @Override
setRequestedOrientation(IBinder token, int requestedOrientation)3718     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
3719         mActivityTaskManager.setRequestedOrientation(token, requestedOrientation);
3720     }
3721 
3722     @Override
finishHeavyWeightApp()3723     public final void finishHeavyWeightApp() {
3724         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3725                 != PackageManager.PERMISSION_GRANTED) {
3726             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3727                     + Binder.getCallingPid()
3728                     + ", uid=" + Binder.getCallingUid()
3729                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3730             Slog.w(TAG, msg);
3731             throw new SecurityException(msg);
3732         }
3733         mAtmInternal.finishHeavyWeightApp();
3734     }
3735 
3736     @Override
crashApplication(int uid, int initialPid, String packageName, int userId, String message, boolean force)3737     public void crashApplication(int uid, int initialPid, String packageName, int userId,
3738             String message, boolean force) {
3739         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3740                 != PackageManager.PERMISSION_GRANTED) {
3741             String msg = "Permission Denial: crashApplication() from pid="
3742                     + Binder.getCallingPid()
3743                     + ", uid=" + Binder.getCallingUid()
3744                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3745             Slog.w(TAG, msg);
3746             throw new SecurityException(msg);
3747         }
3748 
3749         synchronized(this) {
3750             mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId,
3751                     message, force);
3752         }
3753     }
3754 
3755     /**
3756      * Main function for removing an existing process from the activity manager
3757      * as a result of that process going away.  Clears out all connections
3758      * to the process.
3759      */
3760     @GuardedBy("this")
handleAppDiedLocked(ProcessRecord app, boolean restarting, boolean allowRestart)3761     final void handleAppDiedLocked(ProcessRecord app,
3762             boolean restarting, boolean allowRestart) {
3763         int pid = app.pid;
3764         boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
3765                 false /*replacingPid*/);
3766         if (!kept && !restarting) {
3767             removeLruProcessLocked(app);
3768             if (pid > 0) {
3769                 ProcessList.remove(pid);
3770             }
3771         }
3772 
3773         if (mProfileData.getProfileProc() == app) {
3774             clearProfilerLocked();
3775         }
3776 
3777         mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
3778             Slog.w(TAG, "Crash of app " + app.processName
3779                     + " running instrumentation " + app.getActiveInstrumentation().mClass);
3780             Bundle info = new Bundle();
3781             info.putString("shortMsg", "Process crashed.");
3782             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3783         });
3784     }
3785 
getRecordForAppLocked(IApplicationThread thread)3786     ProcessRecord getRecordForAppLocked(IApplicationThread thread) {
3787         if (thread == null) {
3788             return null;
3789         }
3790 
3791         ProcessRecord record = mProcessList.getLRURecordForAppLocked(thread);
3792         if (record != null) return record;
3793 
3794         // Validation: if it isn't in the LRU list, it shouldn't exist, but let's
3795         // double-check that.
3796         final IBinder threadBinder = thread.asBinder();
3797         final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
3798                 mProcessList.mProcessNames.getMap();
3799         for (int i = pmap.size()-1; i >= 0; i--) {
3800             final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
3801             for (int j = procs.size()-1; j >= 0; j--) {
3802                 final ProcessRecord proc = procs.valueAt(j);
3803                 if (proc.thread != null && proc.thread.asBinder() == threadBinder) {
3804                     Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
3805                             + proc);
3806                     return proc;
3807                 }
3808             }
3809         }
3810 
3811         return null;
3812     }
3813 
doLowMemReportIfNeededLocked(ProcessRecord dyingProc)3814     final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
3815         // If there are no longer any background processes running,
3816         // and the app that died was not running instrumentation,
3817         // then tell everyone we are now low on memory.
3818         if (!mProcessList.haveBackgroundProcessLocked()) {
3819             boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
3820             if (doReport) {
3821                 long now = SystemClock.uptimeMillis();
3822                 if (now < (mLastMemUsageReportTime+5*60*1000)) {
3823                     doReport = false;
3824                 } else {
3825                     mLastMemUsageReportTime = now;
3826                 }
3827             }
3828             final ArrayList<ProcessMemInfo> memInfos
3829                     = doReport ? new ArrayList<ProcessMemInfo>(mProcessList.getLruSizeLocked())
3830                     : null;
3831             EventLogTags.writeAmLowMemory(mProcessList.getLruSizeLocked());
3832             long now = SystemClock.uptimeMillis();
3833             for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) {
3834                 ProcessRecord rec = mProcessList.mLruProcesses.get(i);
3835                 if (rec == dyingProc || rec.thread == null) {
3836                     continue;
3837                 }
3838                 if (doReport) {
3839                     memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
3840                             rec.setProcState, rec.adjType, rec.makeAdjReason()));
3841                 }
3842                 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) {
3843                     // The low memory report is overriding any current
3844                     // state for a GC request.  Make sure to do
3845                     // heavy/important/visible/foreground processes first.
3846                     if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
3847                         rec.lastRequestedGc = 0;
3848                     } else {
3849                         rec.lastRequestedGc = rec.lastLowMemory;
3850                     }
3851                     rec.reportLowMemory = true;
3852                     rec.lastLowMemory = now;
3853                     mProcessesToGc.remove(rec);
3854                     addProcessToGcListLocked(rec);
3855                 }
3856             }
3857             if (doReport) {
3858                 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
3859                 mHandler.sendMessage(msg);
3860             }
3861             scheduleAppGcsLocked();
3862         }
3863     }
3864 
3865     @GuardedBy("this")
appDiedLocked(ProcessRecord app, String reason)3866     final void appDiedLocked(ProcessRecord app, String reason) {
3867         appDiedLocked(app, app.pid, app.thread, false, reason);
3868     }
3869 
3870     @GuardedBy("this")
appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied, String reason)3871     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
3872             boolean fromBinderDied, String reason) {
3873         // First check if this ProcessRecord is actually active for the pid.
3874         synchronized (mPidsSelfLocked) {
3875             ProcessRecord curProc = mPidsSelfLocked.get(pid);
3876             if (curProc != app) {
3877                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
3878                 return;
3879             }
3880         }
3881 
3882         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3883         synchronized (stats) {
3884             stats.noteProcessDiedLocked(app.info.uid, pid);
3885         }
3886 
3887         if (!app.killed) {
3888             if (!fromBinderDied) {
3889                 killProcessQuiet(pid);
3890                 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_OTHER,
3891                         ApplicationExitInfo.SUBREASON_UNKNOWN, reason);
3892             }
3893             ProcessList.killProcessGroup(app.uid, pid);
3894             app.killed = true;
3895         }
3896 
3897         // Clean up already done if the process has been re-started.
3898         if (app.pid == pid && app.thread != null &&
3899                 app.thread.asBinder() == thread.asBinder()) {
3900             boolean doLowMem = app.getActiveInstrumentation() == null;
3901             boolean doOomAdj = doLowMem;
3902             if (!app.killedByAm) {
3903                 reportUidInfoMessageLocked(TAG,
3904                         "Process " + app.processName + " (pid " + pid + ") has died: "
3905                                 + ProcessList.makeOomAdjString(app.setAdj, true) + " "
3906                                 + ProcessList.makeProcStateString(app.setProcState), app.info.uid);
3907                 mAllowLowerMemLevel = true;
3908             } else {
3909                 // Note that we always want to do oom adj to update our state with the
3910                 // new number of procs.
3911                 mAllowLowerMemLevel = false;
3912                 doLowMem = false;
3913             }
3914             EventLogTags.writeAmProcDied(app.userId, app.pid, app.processName, app.setAdj,
3915                     app.setProcState);
3916             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3917                 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
3918             handleAppDiedLocked(app, false, true);
3919 
3920             if (doOomAdj) {
3921                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
3922             }
3923             if (doLowMem) {
3924                 doLowMemReportIfNeededLocked(app);
3925             }
3926         } else if (app.pid != pid) {
3927             // A new process has already been started.
3928             reportUidInfoMessageLocked(TAG,
3929                     "Process " + app.processName + " (pid " + pid
3930                             + ") has died and restarted (pid " + app.pid + ").", app.info.uid);
3931 
3932             EventLogTags.writeAmProcDied(app.userId, app.pid, app.processName, app.setAdj,
3933                     app.setProcState);
3934         } else if (DEBUG_PROCESSES) {
3935             Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
3936                     + thread.asBinder());
3937         }
3938 
3939         // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal
3940         // for pulling memory stats of other running processes when this process died.
3941         if (!hasMemcg()) {
3942             FrameworkStatsLog.write(FrameworkStatsLog.APP_DIED, SystemClock.elapsedRealtime());
3943         }
3944     }
3945 
3946     /**
3947      * If a stack trace dump file is configured, dump process stack traces.
3948      * @param firstPids of dalvik VM processes to dump stack traces for first
3949      * @param lastPids of dalvik VM processes to dump stack traces for last
3950      * @param nativePids optional list of native pids to dump stack crawls
3951      * @param logExceptionCreatingFile optional writer to which we log errors creating the file
3952      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile)3953     public static File dumpStackTraces(ArrayList<Integer> firstPids,
3954             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3955             ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile) {
3956         return dumpStackTraces(firstPids, processCpuTracker, lastPids, nativePids,
3957                 logExceptionCreatingFile, null);
3958     }
3959 
3960     /**
3961      * @param firstPidOffsets Optional, when it's set, it receives the start/end offset
3962      *                        of the very first pid to be dumped.
3963      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile, long[] firstPidOffsets)3964     /* package */ static File dumpStackTraces(ArrayList<Integer> firstPids,
3965             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3966             ArrayList<Integer> nativePids, StringWriter logExceptionCreatingFile,
3967             long[] firstPidOffsets) {
3968         ArrayList<Integer> extraPids = null;
3969 
3970         Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids);
3971 
3972         // Measure CPU usage as soon as we're called in order to get a realistic sampling
3973         // of the top users at the time of the request.
3974         if (processCpuTracker != null) {
3975             processCpuTracker.init();
3976             try {
3977                 Thread.sleep(200);
3978             } catch (InterruptedException ignored) {
3979             }
3980 
3981             processCpuTracker.update();
3982 
3983             // We'll take the stack crawls of just the top apps using CPU.
3984             final int N = processCpuTracker.countWorkingStats();
3985             extraPids = new ArrayList<>();
3986             for (int i = 0; i < N && extraPids.size() < 5; i++) {
3987                 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
3988                 if (lastPids.indexOfKey(stats.pid) >= 0) {
3989                     if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid);
3990 
3991                     extraPids.add(stats.pid);
3992                 } else {
3993                     Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: "
3994                             + stats.pid);
3995                 }
3996             }
3997         }
3998 
3999         final File tracesDir = new File(ANR_TRACE_DIR);
4000         // Each set of ANR traces is written to a separate file and dumpstate will process
4001         // all such files and add them to a captured bug report if they're recent enough.
4002         maybePruneOldTraces(tracesDir);
4003 
4004         // NOTE: We should consider creating the file in native code atomically once we've
4005         // gotten rid of the old scheme of dumping and lot of the code that deals with paths
4006         // can be removed.
4007         File tracesFile;
4008         try {
4009             tracesFile = createAnrDumpFile(tracesDir);
4010         } catch (IOException e) {
4011             Slog.w(TAG, "Exception creating ANR dump file:", e);
4012             if (logExceptionCreatingFile != null) {
4013                 logExceptionCreatingFile.append("----- Exception creating ANR dump file -----\n");
4014                 e.printStackTrace(new PrintWriter(logExceptionCreatingFile));
4015             }
4016             return null;
4017         }
4018 
4019         Pair<Long, Long> offsets = dumpStackTraces(
4020                 tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids);
4021         if (firstPidOffsets != null) {
4022             if (offsets == null) {
4023                 firstPidOffsets[0] = firstPidOffsets[1] = -1;
4024             } else {
4025                 firstPidOffsets[0] = offsets.first; // Start offset to the ANR trace file
4026                 firstPidOffsets[1] = offsets.second; // End offset to the ANR trace file
4027             }
4028         }
4029         return tracesFile;
4030     }
4031 
4032     @GuardedBy("ActivityManagerService.class")
4033     private static SimpleDateFormat sAnrFileDateFormat;
4034     static final String ANR_FILE_PREFIX = "anr_";
4035 
createAnrDumpFile(File tracesDir)4036     private static synchronized File createAnrDumpFile(File tracesDir) throws IOException {
4037         if (sAnrFileDateFormat == null) {
4038             sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
4039         }
4040 
4041         final String formattedDate = sAnrFileDateFormat.format(new Date());
4042         final File anrFile = new File(tracesDir, ANR_FILE_PREFIX + formattedDate);
4043 
4044         if (anrFile.createNewFile()) {
4045             FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw-------
4046             return anrFile;
4047         } else {
4048             throw new IOException("Unable to create ANR dump file: createNewFile failed");
4049         }
4050     }
4051 
4052     /**
4053      * Prune all trace files that are more than a day old.
4054      *
4055      * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a
4056      * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now
4057      * since it's the system_server that creates trace files for most ANRs.
4058      */
maybePruneOldTraces(File tracesDir)4059     private static void maybePruneOldTraces(File tracesDir) {
4060         final File[] files = tracesDir.listFiles();
4061         if (files == null) return;
4062 
4063         final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64);
4064         final long now = System.currentTimeMillis();
4065         Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
4066         for (int i = 0; i < files.length; ++i) {
4067             if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) {
4068                 if (!files[i].delete()) {
4069                     Slog.w(TAG, "Unable to prune stale trace file: " + files[i]);
4070                 }
4071             }
4072         }
4073     }
4074 
4075     /**
4076      * Dump java traces for process {@code pid} to the specified file. If java trace dumping
4077      * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies
4078      * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent
4079      * attempting to obtain native traces in the case of a failure. Returns the total time spent
4080      * capturing traces.
4081      */
dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)4082     private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) {
4083         final long timeStart = SystemClock.elapsedRealtime();
4084         boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName,
4085                 (int) (timeoutMs / 1000));
4086         if (javaSuccess) {
4087             // Check that something is in the file, actually. Try-catch should not be necessary,
4088             // but better safe than sorry.
4089             try {
4090                 long size = new File(fileName).length();
4091                 if (size < JAVA_DUMP_MINIMUM_SIZE) {
4092                     Slog.w(TAG, "Successfully created Java ANR file is empty!");
4093                     javaSuccess = false;
4094                 }
4095             } catch (Exception e) {
4096                 Slog.w(TAG, "Unable to get ANR file size", e);
4097                 javaSuccess = false;
4098             }
4099         }
4100         if (!javaSuccess) {
4101             Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump.");
4102             if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName,
4103                     (NATIVE_DUMP_TIMEOUT_MS / 1000))) {
4104                 Slog.w(TAG, "Native stack dump failed!");
4105             }
4106         }
4107 
4108         return SystemClock.elapsedRealtime() - timeStart;
4109     }
4110 
4111     /**
4112      * @return The start/end offset of the trace of the very first PID
4113      */
dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)4114     public static Pair<Long, Long> dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids,
4115             ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) {
4116 
4117         Slog.i(TAG, "Dumping to " + tracesFile);
4118 
4119         // We don't need any sort of inotify based monitoring when we're dumping traces via
4120         // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full
4121         // control of all writes to the file in question.
4122 
4123         // We must complete all stack dumps within 20 seconds.
4124         long remainingTime = 20 * 1000;
4125 
4126         // As applications are usually interested with the ANR stack traces, but we can't share with
4127         // them the stack traces other than their own stacks. So after the very first PID is
4128         // dumped, remember the current file size.
4129         long firstPidStart = -1;
4130         long firstPidEnd = -1;
4131 
4132         // First collect all of the stacks of the most important pids.
4133         if (firstPids != null) {
4134             int num = firstPids.size();
4135             for (int i = 0; i < num; i++) {
4136                 final int pid = firstPids.get(i);
4137                 // We don't copy ANR traces from the system_server intentionally.
4138                 final boolean firstPid = i == 0 && MY_PID != pid;
4139                 File tf = null;
4140                 if (firstPid) {
4141                     tf = new File(tracesFile);
4142                     firstPidStart = tf.exists() ? tf.length() : 0;
4143                 }
4144 
4145                 Slog.i(TAG, "Collecting stacks for pid " + pid);
4146                 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile,
4147                                                                 remainingTime);
4148 
4149                 remainingTime -= timeTaken;
4150                 if (remainingTime <= 0) {
4151                     Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + pid
4152                             + "); deadline exceeded.");
4153                     return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
4154                 }
4155 
4156                 if (firstPid) {
4157                     firstPidEnd = tf.length();
4158                 }
4159                 if (DEBUG_ANR) {
4160                     Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms");
4161                 }
4162             }
4163         }
4164 
4165         // Next collect the stacks of the native pids
4166         if (nativePids != null) {
4167             for (int pid : nativePids) {
4168                 Slog.i(TAG, "Collecting stacks for native pid " + pid);
4169                 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime);
4170 
4171                 final long start = SystemClock.elapsedRealtime();
4172                 Debug.dumpNativeBacktraceToFileTimeout(
4173                         pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000));
4174                 final long timeTaken = SystemClock.elapsedRealtime() - start;
4175 
4176                 remainingTime -= timeTaken;
4177                 if (remainingTime <= 0) {
4178                     Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid +
4179                         "); deadline exceeded.");
4180                     return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
4181                 }
4182 
4183                 if (DEBUG_ANR) {
4184                     Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms");
4185                 }
4186             }
4187         }
4188 
4189         // Lastly, dump stacks for all extra PIDs from the CPU tracker.
4190         if (extraPids != null) {
4191             for (int pid : extraPids) {
4192                 Slog.i(TAG, "Collecting stacks for extra pid " + pid);
4193 
4194                 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime);
4195 
4196                 remainingTime -= timeTaken;
4197                 if (remainingTime <= 0) {
4198                     Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid +
4199                             "); deadline exceeded.");
4200                     return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
4201                 }
4202 
4203                 if (DEBUG_ANR) {
4204                     Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms");
4205                 }
4206             }
4207         }
4208         Slog.i(TAG, "Done dumping");
4209         return firstPidStart >= 0 ? new Pair<>(firstPidStart, firstPidEnd) : null;
4210     }
4211 
4212     @Override
clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)4213     public boolean clearApplicationUserData(final String packageName, boolean keepState,
4214             final IPackageDataObserver observer, int userId) {
4215         enforceNotIsolatedCaller("clearApplicationUserData");
4216         int uid = Binder.getCallingUid();
4217         int pid = Binder.getCallingPid();
4218         final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false,
4219                 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
4220 
4221         final ApplicationInfo appInfo;
4222         final boolean isInstantApp;
4223 
4224         long callingId = Binder.clearCallingIdentity();
4225         try {
4226             IPackageManager pm = AppGlobals.getPackageManager();
4227             synchronized(this) {
4228                 // Instant packages are not protected
4229                 if (getPackageManagerInternalLocked().isPackageDataProtected(
4230                         resolvedUserId, packageName)) {
4231                     throw new SecurityException(
4232                             "Cannot clear data for a protected package: " + packageName);
4233                 }
4234 
4235                 ApplicationInfo applicationInfo = null;
4236                 try {
4237                     applicationInfo = pm.getApplicationInfo(packageName,
4238                             MATCH_UNINSTALLED_PACKAGES, resolvedUserId);
4239                 } catch (RemoteException e) {
4240                     /* ignore */
4241                 }
4242                 appInfo = applicationInfo;
4243 
4244                 final boolean clearingOwnUidData = appInfo != null && appInfo.uid == uid;
4245 
4246                 if (!clearingOwnUidData && checkComponentPermission(permission.CLEAR_APP_USER_DATA,
4247                         pid, uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
4248                     throw new SecurityException("PID " + pid + " does not have permission "
4249                             + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
4250                             + " of package " + packageName);
4251                 }
4252 
4253                 final boolean hasInstantMetadata = getPackageManagerInternalLocked()
4254                         .hasInstantApplicationMetadata(packageName, resolvedUserId);
4255                 final boolean isUninstalledAppWithoutInstantMetadata =
4256                         (appInfo == null && !hasInstantMetadata);
4257                 isInstantApp = (appInfo != null && appInfo.isInstantApp())
4258                         || hasInstantMetadata;
4259                 final boolean canAccessInstantApps = checkComponentPermission(
4260                         permission.ACCESS_INSTANT_APPS, pid, uid, -1, true)
4261                         == PackageManager.PERMISSION_GRANTED;
4262 
4263                 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp
4264                         && !canAccessInstantApps)) {
4265                     Slog.w(TAG, "Invalid packageName: " + packageName);
4266                     if (observer != null) {
4267                         try {
4268                             observer.onRemoveCompleted(packageName, false);
4269                         } catch (RemoteException e) {
4270                             Slog.i(TAG, "Observer no longer exists.");
4271                         }
4272                     }
4273                     return false;
4274                 }
4275 
4276                 if (appInfo != null) {
4277                     forceStopPackageLocked(packageName, appInfo.uid, "clear data");
4278                     mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId);
4279                 }
4280             }
4281 
4282             final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
4283                 @Override
4284                 public void onRemoveCompleted(String packageName, boolean succeeded)
4285                         throws RemoteException {
4286                     if (appInfo != null) {
4287                         synchronized (ActivityManagerService.this) {
4288                             finishForceStopPackageLocked(packageName, appInfo.uid);
4289                         }
4290                     }
4291                     final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4292                             Uri.fromParts("package", packageName, null));
4293                     intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4294                     intent.putExtra(Intent.EXTRA_UID, (appInfo != null) ? appInfo.uid : -1);
4295                     intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId);
4296                     if (isInstantApp) {
4297                         intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
4298                         broadcastIntentInPackage("android", null, SYSTEM_UID, uid, pid, intent,
4299                                 null, null, 0, null, null, permission.ACCESS_INSTANT_APPS, null,
4300                                 false, false, resolvedUserId, false);
4301                     } else {
4302                         broadcastIntentInPackage("android", null, SYSTEM_UID, uid, pid, intent,
4303                                 null, null, 0, null, null, null, null, false, false, resolvedUserId,
4304                                 false);
4305                     }
4306 
4307                     if (observer != null) {
4308                         observer.onRemoveCompleted(packageName, succeeded);
4309                     }
4310                 }
4311             };
4312 
4313             try {
4314                 // Clear application user data
4315                 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId);
4316 
4317                 if (appInfo != null) {
4318                     // Restore already established notification state and permission grants,
4319                     // so it told us to keep those intact -- it's about to emplace app data
4320                     // that is appropriate for those bits of system state.
4321                     if (!keepState) {
4322                         // Remove all permissions granted from/to this package
4323                         mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId,
4324                                 true, false);
4325 
4326                         // Reset notification state
4327                         INotificationManager inm = NotificationManager.getService();
4328                         inm.clearData(packageName, appInfo.uid, uid == appInfo.uid);
4329                     }
4330 
4331                     // Clear its scheduled jobs
4332                     JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
4333                     js.cancelJobsForUid(appInfo.uid, "clear data");
4334 
4335                     // Clear its pending alarms
4336                     AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class);
4337                     ami.removeAlarmsForUid(appInfo.uid);
4338                 }
4339             } catch (RemoteException e) {
4340             }
4341         } finally {
4342             Binder.restoreCallingIdentity(callingId);
4343         }
4344         return true;
4345     }
4346 
4347     @Override
killBackgroundProcesses(final String packageName, int userId)4348     public void killBackgroundProcesses(final String packageName, int userId) {
4349         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4350                 != PackageManager.PERMISSION_GRANTED &&
4351                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4352                         != PackageManager.PERMISSION_GRANTED) {
4353             String msg = "Permission Denial: killBackgroundProcesses() from pid="
4354                     + Binder.getCallingPid()
4355                     + ", uid=" + Binder.getCallingUid()
4356                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4357             Slog.w(TAG, msg);
4358             throw new SecurityException(msg);
4359         }
4360 
4361         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4362                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
4363         final int[] userIds = mUserController.expandUserId(userId);
4364 
4365         long callingId = Binder.clearCallingIdentity();
4366         try {
4367             IPackageManager pm = AppGlobals.getPackageManager();
4368             for (int targetUserId : userIds) {
4369                 int appId = -1;
4370                 try {
4371                     appId = UserHandle.getAppId(
4372                             pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
4373                                     targetUserId));
4374                 } catch (RemoteException e) {
4375                 }
4376                 if (appId == -1) {
4377                     Slog.w(TAG, "Invalid packageName: " + packageName);
4378                     return;
4379                 }
4380                 synchronized (this) {
4381                     mProcessList.killPackageProcessesLocked(packageName, appId, targetUserId,
4382                             ProcessList.SERVICE_ADJ, ApplicationExitInfo.REASON_USER_REQUESTED,
4383                             ApplicationExitInfo.SUBREASON_UNKNOWN, "kill background");
4384                 }
4385             }
4386         } finally {
4387             Binder.restoreCallingIdentity(callingId);
4388         }
4389     }
4390 
4391     @Override
killAllBackgroundProcesses()4392     public void killAllBackgroundProcesses() {
4393         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4394                 != PackageManager.PERMISSION_GRANTED) {
4395             final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4396                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4397                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4398             Slog.w(TAG, msg);
4399             throw new SecurityException(msg);
4400         }
4401 
4402         final long callingId = Binder.clearCallingIdentity();
4403         try {
4404             synchronized (this) {
4405                 // Allow memory level to go down (the flag needs to be set before updating oom adj)
4406                 // because this method is also used to simulate low memory.
4407                 mAllowLowerMemLevel = true;
4408                 mProcessList.killPackageProcessesLocked(null /* packageName */, -1 /* appId */,
4409                         UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ,
4410                         ApplicationExitInfo.REASON_USER_REQUESTED,
4411                         ApplicationExitInfo.SUBREASON_UNKNOWN,
4412                         "kill all background");
4413 
4414                 doLowMemReportIfNeededLocked(null);
4415             }
4416         } finally {
4417             Binder.restoreCallingIdentity(callingId);
4418         }
4419     }
4420 
4421     /**
4422      * Kills all background processes, except those matching any of the
4423      * specified properties.
4424      *
4425      * @param minTargetSdk the target SDK version at or above which to preserve
4426      *                     processes, or {@code -1} to ignore the target SDK
4427      * @param maxProcState the process state at or below which to preserve
4428      *                     processes, or {@code -1} to ignore the process state
4429      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)4430     void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
4431         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4432                 != PackageManager.PERMISSION_GRANTED) {
4433             final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
4434                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4435                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4436             Slog.w(TAG, msg);
4437             throw new SecurityException(msg);
4438         }
4439 
4440         final long callingId = Binder.clearCallingIdentity();
4441         try {
4442             synchronized (this) {
4443                 mProcessList.killAllBackgroundProcessesExceptLocked(minTargetSdk, maxProcState);
4444             }
4445         } finally {
4446             Binder.restoreCallingIdentity(callingId);
4447         }
4448     }
4449 
4450     @Override
forceStopPackage(final String packageName, int userId)4451     public void forceStopPackage(final String packageName, int userId) {
4452         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4453                 != PackageManager.PERMISSION_GRANTED) {
4454             String msg = "Permission Denial: forceStopPackage() from pid="
4455                     + Binder.getCallingPid()
4456                     + ", uid=" + Binder.getCallingUid()
4457                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4458             Slog.w(TAG, msg);
4459             throw new SecurityException(msg);
4460         }
4461         final int callingPid = Binder.getCallingPid();
4462         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
4463                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
4464         long callingId = Binder.clearCallingIdentity();
4465         try {
4466             IPackageManager pm = AppGlobals.getPackageManager();
4467             synchronized(this) {
4468                 int[] users = userId == UserHandle.USER_ALL
4469                         ? mUserController.getUsers() : new int[] { userId };
4470                 for (int user : users) {
4471                     if (getPackageManagerInternalLocked().isPackageStateProtected(
4472                             packageName, user)) {
4473                         Slog.w(TAG, "Ignoring request to force stop protected package "
4474                                 + packageName + " u" + user);
4475                         return;
4476                     }
4477 
4478                     int pkgUid = -1;
4479                     try {
4480                         pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
4481                                 user);
4482                     } catch (RemoteException e) {
4483                     }
4484                     if (pkgUid == -1) {
4485                         Slog.w(TAG, "Invalid packageName: " + packageName);
4486                         continue;
4487                     }
4488                     try {
4489                         pm.setPackageStoppedState(packageName, true, user);
4490                     } catch (RemoteException e) {
4491                     } catch (IllegalArgumentException e) {
4492                         Slog.w(TAG, "Failed trying to unstop package "
4493                                 + packageName + ": " + e);
4494                     }
4495                     if (mUserController.isUserRunning(user, 0)) {
4496                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
4497                         finishForceStopPackageLocked(packageName, pkgUid);
4498                     }
4499                 }
4500             }
4501         } finally {
4502             Binder.restoreCallingIdentity(callingId);
4503         }
4504     }
4505 
4506     @Override
addPackageDependency(String packageName)4507     public void addPackageDependency(String packageName) {
4508         synchronized (this) {
4509             int callingPid = Binder.getCallingPid();
4510             if (callingPid == myPid()) {
4511                 //  Yeah, um, no.
4512                 return;
4513             }
4514             ProcessRecord proc;
4515             synchronized (mPidsSelfLocked) {
4516                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
4517             }
4518             if (proc != null) {
4519                 if (proc.pkgDeps == null) {
4520                     proc.pkgDeps = new ArraySet<String>(1);
4521                 }
4522                 proc.pkgDeps.add(packageName);
4523             }
4524         }
4525     }
4526 
4527     /*
4528      * The pkg name and app id have to be specified.
4529      */
4530     @Override
killApplication(String pkg, int appId, int userId, String reason)4531     public void killApplication(String pkg, int appId, int userId, String reason) {
4532         if (pkg == null) {
4533             return;
4534         }
4535         // Make sure the uid is valid.
4536         if (appId < 0) {
4537             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
4538             return;
4539         }
4540         int callerUid = Binder.getCallingUid();
4541         // Only the system server can kill an application
4542         if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
4543             // Post an aysnc message to kill the application
4544             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4545             msg.arg1 = appId;
4546             msg.arg2 = userId;
4547             Bundle bundle = new Bundle();
4548             bundle.putString("pkg", pkg);
4549             bundle.putString("reason", reason);
4550             msg.obj = bundle;
4551             mHandler.sendMessage(msg);
4552         } else {
4553             throw new SecurityException(callerUid + " cannot kill pkg: " +
4554                     pkg);
4555         }
4556     }
4557 
4558     @Override
closeSystemDialogs(String reason)4559     public void closeSystemDialogs(String reason) {
4560         mAtmInternal.closeSystemDialogs(reason);
4561     }
4562 
4563     @Override
getProcessMemoryInfo(int[] pids)4564     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
4565         enforceNotIsolatedCaller("getProcessMemoryInfo");
4566 
4567         final long now = SystemClock.uptimeMillis();
4568         final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME;
4569 
4570         final int callingPid = Binder.getCallingPid();
4571         final int callingUid = Binder.getCallingUid();
4572         final int callingUserId = UserHandle.getUserId(callingUid);
4573         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4574                 callingUid) == PackageManager.PERMISSION_GRANTED;
4575         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4576         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4577                 "getProcessMemoryInfo", callingPid, callingUid);
4578 
4579         // Check if the caller is actually instrumented and from shell, if it's true, we may lift
4580         // the throttle of PSS info sampling.
4581         boolean isCallerInstrumentedFromShell = false;
4582         synchronized (mPidsSelfLocked) {
4583             ProcessRecord caller = mPidsSelfLocked.get(callingPid);
4584             if (caller != null) {
4585                 final ActiveInstrumentation instr = caller.getActiveInstrumentation();
4586                 isCallerInstrumentedFromShell = instr != null
4587                         && (instr.mSourceUid == SHELL_UID || instr.mSourceUid == ROOT_UID);
4588             }
4589         }
4590 
4591         Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4592         for (int i=pids.length-1; i>=0; i--) {
4593             infos[i] = new Debug.MemoryInfo();
4594             final ProcessRecord proc;
4595             final int oomAdj;
4596             synchronized (this) {
4597                 synchronized (mPidsSelfLocked) {
4598                     proc = mPidsSelfLocked.get(pids[i]);
4599                     oomAdj = proc != null ? proc.setAdj : 0;
4600                 }
4601             }
4602             final int targetUid = (proc != null) ? proc.uid : -1;
4603             final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1;
4604 
4605             if (callingUid != targetUid) {
4606                 if (!allUids) {
4607                     continue; // Not allowed to see other UIDs.
4608                 }
4609 
4610                 if (!allUsers && (targetUserId != callingUserId)) {
4611                     continue; // Not allowed to see other users.
4612                 }
4613             }
4614             if (proc != null && proc.lastMemInfoTime >= lastNow && proc.lastMemInfo != null
4615                     && !isCallerInstrumentedFromShell) {
4616                 // It hasn't been long enough that we want to take another sample; return
4617                 // the last one.
4618                 infos[i].set(proc.lastMemInfo);
4619                 continue;
4620             }
4621             final long startTime = SystemClock.currentThreadTimeMillis();
4622             final Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
4623             Debug.getMemoryInfo(pids[i], memInfo);
4624             final long endTime = SystemClock.currentThreadTimeMillis();
4625             infos[i].set(memInfo);
4626             if (proc != null) {
4627                 synchronized (this) {
4628                     proc.lastMemInfo = memInfo;
4629                     proc.lastMemInfoTime = SystemClock.uptimeMillis();
4630                     if (proc.thread != null && proc.setAdj == oomAdj) {
4631                         // Record this for posterity if the process has been stable.
4632                         proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
4633                                 infos[i].getTotalUss(), infos[i].getTotalRss(), false,
4634                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, endTime - startTime,
4635                                 proc.pkgList.mPkgList);
4636                         for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) {
4637                             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
4638                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
4639                                     proc.info.uid,
4640                                     holder.state.getName(),
4641                                     holder.state.getPackage(),
4642                                     infos[i].getTotalPss(),
4643                                     infos[i].getTotalUss(),
4644                                     infos[i].getTotalRss(),
4645                                     ProcessStats.ADD_PSS_EXTERNAL_SLOW,
4646                                     endTime-startTime,
4647                                     holder.appVersion);
4648                         }
4649                     }
4650                 }
4651             }
4652         }
4653         return infos;
4654     }
4655 
4656     @Override
getProcessPss(int[] pids)4657     public long[] getProcessPss(int[] pids) {
4658         enforceNotIsolatedCaller("getProcessPss");
4659 
4660         final int callingPid = Binder.getCallingPid();
4661         final int callingUid = Binder.getCallingUid();
4662         final int userId = UserHandle.getUserId(callingUid);
4663         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4664                 callingUid) == PackageManager.PERMISSION_GRANTED;
4665         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4666         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4667                 "getProcessPss", callingPid, callingUid);
4668 
4669         long[] pss = new long[pids.length];
4670         for (int i=pids.length-1; i>=0; i--) {
4671             ProcessRecord proc;
4672             int oomAdj;
4673             synchronized (this) {
4674                 synchronized (mPidsSelfLocked) {
4675                     proc = mPidsSelfLocked.get(pids[i]);
4676                     oomAdj = proc != null ? proc.setAdj : 0;
4677                 }
4678             }
4679             if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) {
4680                 // The caller is not allow to get information about this other process...
4681                 // just leave it empty.
4682                 continue;
4683             }
4684             long[] tmpUss = new long[3];
4685             long startTime = SystemClock.currentThreadTimeMillis();
4686             pss[i] = Debug.getPss(pids[i], tmpUss, null);
4687             long endTime = SystemClock.currentThreadTimeMillis();
4688             if (proc != null) {
4689                 synchronized (this) {
4690                     if (proc.thread != null && proc.setAdj == oomAdj) {
4691                         // Record this for posterity if the process has been stable.
4692                         proc.baseProcessTracker.addPss(pss[i], tmpUss[0], tmpUss[2], false,
4693                                 ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime, proc.pkgList.mPkgList);
4694                         for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) {
4695                             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
4696                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
4697                                     proc.info.uid,
4698                                     holder.state.getName(),
4699                                     holder.state.getPackage(),
4700                                     pss[i], tmpUss[0], tmpUss[2],
4701                                     ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime,
4702                                     holder.appVersion);
4703                         }
4704                     }
4705                 }
4706             }
4707         }
4708         return pss;
4709     }
4710 
4711     @Override
killApplicationProcess(String processName, int uid)4712     public void killApplicationProcess(String processName, int uid) {
4713         if (processName == null) {
4714             return;
4715         }
4716 
4717         int callerUid = Binder.getCallingUid();
4718         // Only the system server can kill an application
4719         if (callerUid == SYSTEM_UID) {
4720             synchronized (this) {
4721                 ProcessRecord app = getProcessRecordLocked(processName, uid, true);
4722                 if (app != null && app.thread != null) {
4723                     try {
4724                         app.thread.scheduleSuicide();
4725                     } catch (RemoteException e) {
4726                         // If the other end already died, then our work here is done.
4727                     }
4728                 } else {
4729                     Slog.w(TAG, "Process/uid not found attempting kill of "
4730                             + processName + " / " + uid);
4731                 }
4732             }
4733         } else {
4734             throw new SecurityException(callerUid + " cannot kill app process: " +
4735                     processName);
4736         }
4737     }
4738 
4739     @GuardedBy("this")
forceStopPackageLocked(final String packageName, int uid, String reason)4740     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
4741         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
4742                 false, true, false, false, UserHandle.getUserId(uid), reason);
4743     }
4744 
4745     @GuardedBy("this")
finishForceStopPackageLocked(final String packageName, int uid)4746     private void finishForceStopPackageLocked(final String packageName, int uid) {
4747         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4748                 Uri.fromParts("package", packageName, null));
4749         if (!mProcessesReady) {
4750             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4751                     | Intent.FLAG_RECEIVER_FOREGROUND);
4752         }
4753         intent.putExtra(Intent.EXTRA_UID, uid);
4754         intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
4755         broadcastIntentLocked(null, null, null, intent,
4756                 null, null, 0, null, null, null, OP_NONE,
4757                 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
4758                 Binder.getCallingPid(), UserHandle.getUserId(uid));
4759     }
4760 
cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4761     private void cleanupDisabledPackageComponentsLocked(
4762             String packageName, int userId, String[] changedClasses) {
4763 
4764         Set<String> disabledClasses = null;
4765         boolean packageDisabled = false;
4766         IPackageManager pm = AppGlobals.getPackageManager();
4767 
4768         if (changedClasses == null) {
4769             // Nothing changed...
4770             return;
4771         }
4772 
4773         // Determine enable/disable state of the package and its components.
4774         int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4775         for (int i = changedClasses.length - 1; i >= 0; i--) {
4776             final String changedClass = changedClasses[i];
4777 
4778             if (changedClass.equals(packageName)) {
4779                 try {
4780                     // Entire package setting changed
4781                     enabled = pm.getApplicationEnabledSetting(packageName,
4782                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4783                 } catch (Exception e) {
4784                     // No such package/component; probably racing with uninstall.  In any
4785                     // event it means we have nothing further to do here.
4786                     return;
4787                 }
4788                 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4789                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4790                 if (packageDisabled) {
4791                     // Entire package is disabled.
4792                     // No need to continue to check component states.
4793                     disabledClasses = null;
4794                     break;
4795                 }
4796             } else {
4797                 try {
4798                     enabled = pm.getComponentEnabledSetting(
4799                             new ComponentName(packageName, changedClass),
4800                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4801                 } catch (Exception e) {
4802                     // As above, probably racing with uninstall.
4803                     return;
4804                 }
4805                 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4806                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
4807                     if (disabledClasses == null) {
4808                         disabledClasses = new ArraySet<>(changedClasses.length);
4809                     }
4810                     disabledClasses.add(changedClass);
4811                 }
4812             }
4813         }
4814 
4815         if (!packageDisabled && disabledClasses == null) {
4816             // Nothing to do here...
4817             return;
4818         }
4819 
4820         mAtmInternal.cleanupDisabledPackageComponents(
4821                 packageName, disabledClasses, userId, mBooted);
4822 
4823         // Clean-up disabled services.
4824         mServices.bringDownDisabledPackageServicesLocked(
4825                 packageName, disabledClasses, userId, false /* evenPersistent */, true /* doIt */);
4826 
4827         // Clean-up disabled providers.
4828         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4829         mProviderMap.collectPackageProvidersLocked(
4830                 packageName, disabledClasses, true, false, userId, providers);
4831         for (int i = providers.size() - 1; i >= 0; i--) {
4832             removeDyingProviderLocked(null, providers.get(i), true);
4833         }
4834 
4835         // Clean-up disabled broadcast receivers.
4836         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4837             mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4838                     packageName, disabledClasses, userId, true);
4839         }
4840 
4841     }
4842 
clearBroadcastQueueForUserLocked(int userId)4843     final boolean clearBroadcastQueueForUserLocked(int userId) {
4844         boolean didSomething = false;
4845         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4846             didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4847                     null, null, userId, true);
4848         }
4849         return didSomething;
4850     }
4851 
4852     @GuardedBy("this")
forceStopAppZygoteLocked(String packageName, int appId, int userId)4853     final void forceStopAppZygoteLocked(String packageName, int appId, int userId) {
4854         if (packageName == null) {
4855             return;
4856         }
4857         if (appId < 0) {
4858             try {
4859                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
4860                         .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
4861             } catch (RemoteException e) {
4862             }
4863         }
4864 
4865         mProcessList.killAppZygotesLocked(packageName, appId, userId, true /* force */);
4866     }
4867 
4868     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4869     final boolean forceStopPackageLocked(String packageName, int appId,
4870             boolean callerWillRestart, boolean purgeCache, boolean doit,
4871             boolean evenPersistent, boolean uninstalling, int userId, String reason) {
4872         int i;
4873 
4874         if (userId == UserHandle.USER_ALL && packageName == null) {
4875             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
4876         }
4877 
4878         if (appId < 0 && packageName != null) {
4879             try {
4880                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
4881                         .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
4882             } catch (RemoteException e) {
4883             }
4884         }
4885 
4886         if (doit) {
4887             if (packageName != null) {
4888                 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
4889                         + " user=" + userId + ": " + reason);
4890             } else {
4891                 Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
4892             }
4893 
4894             mAppErrors.resetProcessCrashTimeLocked(packageName == null, appId, userId);
4895         }
4896 
4897         boolean didSomething = mProcessList.killPackageProcessesLocked(packageName, appId, userId,
4898                 ProcessList.INVALID_ADJ, callerWillRestart, false /* allowRestart */, doit,
4899                 evenPersistent, true /* setRemoved */,
4900                 packageName == null ? ApplicationExitInfo.REASON_USER_STOPPED
4901                         : ApplicationExitInfo.REASON_USER_REQUESTED,
4902                 ApplicationExitInfo.SUBREASON_UNKNOWN,
4903                 (packageName == null ? ("stop user " + userId) : ("stop " + packageName))
4904                 + " due to " + reason);
4905 
4906         didSomething |=
4907                 mAtmInternal.onForceStopPackage(packageName, doit, evenPersistent, userId);
4908 
4909         if (mServices.bringDownDisabledPackageServicesLocked(
4910                 packageName, null /* filterByClasses */, userId, evenPersistent, doit)) {
4911             if (!doit) {
4912                 return true;
4913             }
4914             didSomething = true;
4915         }
4916 
4917         if (packageName == null) {
4918             // Remove all sticky broadcasts from this user.
4919             mStickyBroadcasts.remove(userId);
4920         }
4921 
4922         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4923         if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent,
4924                 userId, providers)) {
4925             if (!doit) {
4926                 return true;
4927             }
4928             didSomething = true;
4929         }
4930         for (i = providers.size() - 1; i >= 0; i--) {
4931             removeDyingProviderLocked(null, providers.get(i), true);
4932         }
4933 
4934         // Remove transient permissions granted from/to this package/user
4935         mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false);
4936 
4937         if (doit) {
4938             for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
4939                 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4940                         packageName, null, userId, doit);
4941             }
4942         }
4943 
4944         if (packageName == null || uninstalling) {
4945             didSomething |= mPendingIntentController.removePendingIntentsForPackage(
4946                     packageName, userId, appId, doit);
4947         }
4948 
4949         if (doit) {
4950             if (purgeCache && packageName != null) {
4951                 AttributeCache ac = AttributeCache.instance();
4952                 if (ac != null) {
4953                     ac.removePackage(packageName);
4954                 }
4955             }
4956             if (mBooted) {
4957                 mAtmInternal.resumeTopActivities(true /* scheduleIdle */);
4958             }
4959         }
4960 
4961         return didSomething;
4962     }
4963 
4964     @GuardedBy("this")
processContentProviderPublishTimedOutLocked(ProcessRecord app)4965     private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) {
4966         cleanupAppInLaunchingProvidersLocked(app, true);
4967         mProcessList.removeProcessLocked(app, false, true,
4968                 ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
4969                 ApplicationExitInfo.SUBREASON_UNKNOWN,
4970                 "timeout publishing content providers");
4971     }
4972 
4973     @GuardedBy("this")
processStartTimedOutLocked(ProcessRecord app)4974     private final void processStartTimedOutLocked(ProcessRecord app) {
4975         final int pid = app.pid;
4976         boolean gone = removePidIfNoThread(app);
4977 
4978         if (gone) {
4979             Slog.w(TAG, "Process " + app + " failed to attach");
4980             EventLogTags.writeAmProcessStartTimeout(app.userId, pid, app.uid, app.processName);
4981             mProcessList.removeProcessNameLocked(app.processName, app.uid);
4982             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
4983             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
4984             // Take care of any launching providers waiting for this process.
4985             cleanupAppInLaunchingProvidersLocked(app, true);
4986             // Take care of any services that are waiting for the process.
4987             mServices.processStartTimedOutLocked(app);
4988             app.kill("start timeout", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
4989             if (app.isolated) {
4990                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
4991             }
4992             removeLruProcessLocked(app);
4993             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4994             if (backupTarget != null && backupTarget.app.pid == pid) {
4995                 Slog.w(TAG, "Unattached app died before backup, skipping");
4996                 mHandler.post(new Runnable() {
4997                 @Override
4998                     public void run(){
4999                         try {
5000                             IBackupManager bm = IBackupManager.Stub.asInterface(
5001                                     ServiceManager.getService(Context.BACKUP_SERVICE));
5002                             bm.agentDisconnectedForUser(app.userId, app.info.packageName);
5003                         } catch (RemoteException e) {
5004                             // Can't happen; the backup manager is local
5005                         }
5006                     }
5007                 });
5008             }
5009             if (isPendingBroadcastProcessLocked(pid)) {
5010                 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
5011                 skipPendingBroadcastLocked(pid);
5012             }
5013         } else {
5014             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
5015         }
5016     }
5017 
5018     @GuardedBy("this")
attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)5019     private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
5020             int pid, int callingUid, long startSeq) {
5021 
5022         // Find the application record that is being attached...  either via
5023         // the pid if we are running in multiple processes, or just pull the
5024         // next app record if we are emulating process with anonymous threads.
5025         ProcessRecord app;
5026         long startTime = SystemClock.uptimeMillis();
5027         long bindApplicationTimeMillis;
5028         if (pid != MY_PID && pid >= 0) {
5029             synchronized (mPidsSelfLocked) {
5030                 app = mPidsSelfLocked.get(pid);
5031             }
5032             if (app != null && (app.startUid != callingUid || app.startSeq != startSeq)) {
5033                 String processName = null;
5034                 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
5035                 if (pending != null) {
5036                     processName = pending.processName;
5037                 }
5038                 final String msg = "attachApplicationLocked process:" + processName
5039                         + " startSeq:" + startSeq
5040                         + " pid:" + pid
5041                         + " belongs to another existing app:" + app.processName
5042                         + " startSeq:" + app.startSeq;
5043                 Slog.wtf(TAG, msg);
5044                 // SafetyNet logging for b/131105245.
5045                 EventLog.writeEvent(0x534e4554, "131105245", app.startUid, msg);
5046                 // If there is already an app occupying that pid that hasn't been cleaned up
5047                 cleanUpApplicationRecordLocked(app, false, false, -1,
5048                             true /*replacingPid*/);
5049                 removePidLocked(app);
5050                 app = null;
5051             }
5052         } else {
5053             app = null;
5054         }
5055 
5056         // It's possible that process called attachApplication before we got a chance to
5057         // update the internal state.
5058         if (app == null && startSeq > 0) {
5059             final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
5060             if (pending != null && pending.startUid == callingUid && pending.startSeq == startSeq
5061                     && mProcessList.handleProcessStartedLocked(pending, pid, pending
5062                             .isUsingWrapper(),
5063                             startSeq, true)) {
5064                 app = pending;
5065             }
5066         }
5067 
5068         if (app == null) {
5069             Slog.w(TAG, "No pending application record for pid " + pid
5070                     + " (IApplicationThread " + thread + "); dropping process");
5071             EventLogTags.writeAmDropProcess(pid);
5072             if (pid > 0 && pid != MY_PID) {
5073                 killProcessQuiet(pid);
5074                 //TODO: killProcessGroup(app.info.uid, pid);
5075                 mProcessList.noteAppKill(app, ApplicationExitInfo.REASON_INITIALIZATION_FAILURE,
5076                         ApplicationExitInfo.SUBREASON_UNKNOWN, "attach failed");
5077             } else {
5078                 try {
5079                     thread.scheduleExit();
5080                 } catch (Exception e) {
5081                     // Ignore exceptions.
5082                 }
5083             }
5084             return false;
5085         }
5086 
5087         // If this application record is still attached to a previous
5088         // process, clean it up now.
5089         if (app.thread != null) {
5090             handleAppDiedLocked(app, true, true);
5091         }
5092 
5093         // Tell the process all about itself.
5094 
5095         if (DEBUG_ALL) Slog.v(
5096                 TAG, "Binding process pid " + pid + " to record " + app);
5097 
5098         final String processName = app.processName;
5099         try {
5100             AppDeathRecipient adr = new AppDeathRecipient(
5101                     app, pid, thread);
5102             thread.asBinder().linkToDeath(adr, 0);
5103             app.deathRecipient = adr;
5104         } catch (RemoteException e) {
5105             app.resetPackageList(mProcessStats);
5106             mProcessList.startProcessLocked(app,
5107                     new HostingRecord("link fail", processName),
5108                     ZYGOTE_POLICY_FLAG_EMPTY);
5109             return false;
5110         }
5111 
5112         EventLogTags.writeAmProcBound(app.userId, app.pid, app.processName);
5113 
5114         app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;
5115         synchronized (mOomAdjuster.mCachedAppOptimizer) {
5116             app.mSetAdjForCompact = ProcessList.INVALID_ADJ;
5117         }
5118         mOomAdjuster.setAttachingSchedGroupLocked(app);
5119         app.forcingToImportant = null;
5120         updateProcessForegroundLocked(app, false, 0, false);
5121         app.hasShownUi = false;
5122         app.setDebugging(false);
5123         app.setCached(false);
5124         app.killedByAm = false;
5125         app.killed = false;
5126 
5127 
5128         // We carefully use the same state that PackageManager uses for
5129         // filtering, since we use this flag to decide if we need to install
5130         // providers when user is unlocked later
5131         app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);
5132 
5133         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5134 
5135         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
5136         List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
5137 
5138         if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
5139             Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
5140             msg.obj = app;
5141             mHandler.sendMessageDelayed(msg,
5142                     ContentResolver.CONTENT_PROVIDER_PUBLISH_TIMEOUT_MILLIS);
5143         }
5144 
5145         checkTime(startTime, "attachApplicationLocked: before bindApplication");
5146 
5147         if (!normalMode) {
5148             Slog.i(TAG, "Launching preboot mode app: " + app);
5149         }
5150 
5151         if (DEBUG_ALL) Slog.v(
5152             TAG, "New app record " + app
5153             + " thread=" + thread.asBinder() + " pid=" + pid);
5154         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
5155         try {
5156             int testMode = ApplicationThreadConstants.DEBUG_OFF;
5157             if (mDebugApp != null && mDebugApp.equals(processName)) {
5158                 testMode = mWaitForDebugger
5159                     ? ApplicationThreadConstants.DEBUG_WAIT
5160                     : ApplicationThreadConstants.DEBUG_ON;
5161                 app.setDebugging(true);
5162                 if (mDebugTransient) {
5163                     mDebugApp = mOrigDebugApp;
5164                     mWaitForDebugger = mOrigWaitForDebugger;
5165                 }
5166             }
5167 
5168             boolean enableTrackAllocation = false;
5169             if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
5170                 enableTrackAllocation = true;
5171                 mTrackAllocationApp = null;
5172             }
5173 
5174             // If the app is being launched for restore or full backup, set it up specially
5175             boolean isRestrictedBackupMode = false;
5176             if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) {
5177                 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID
5178                         && ((backupTarget.backupMode == BackupRecord.RESTORE)
5179                                 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL)
5180                                 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL));
5181             }
5182 
5183             final ActiveInstrumentation instr = app.getActiveInstrumentation();
5184 
5185             if (instr != null) {
5186                 notifyPackageUse(instr.mClass.getPackageName(),
5187                                  PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
5188             }
5189             if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc "
5190                     + processName + " with config "
5191                     + app.getWindowProcessController().getConfiguration());
5192             ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info;
5193             app.compat = compatibilityInfoForPackage(appInfo);
5194 
5195             ProfilerInfo profilerInfo = null;
5196             String preBindAgent = null;
5197             if (mProfileData.getProfileApp() != null
5198                     && mProfileData.getProfileApp().equals(processName)) {
5199                 mProfileData.setProfileProc(app);
5200                 if (mProfileData.getProfilerInfo() != null) {
5201                     // Send a profiler info object to the app if either a file is given, or
5202                     // an agent should be loaded at bind-time.
5203                     boolean needsInfo = mProfileData.getProfilerInfo().profileFile != null
5204                             || mProfileData.getProfilerInfo().attachAgentDuringBind;
5205                     profilerInfo = needsInfo
5206                             ? new ProfilerInfo(mProfileData.getProfilerInfo()) : null;
5207                     if (mProfileData.getProfilerInfo().agent != null) {
5208                         preBindAgent = mProfileData.getProfilerInfo().agent;
5209                     }
5210                 }
5211             } else if (instr != null && instr.mProfileFile != null) {
5212                 profilerInfo = new ProfilerInfo(instr.mProfileFile, null, 0, false, false,
5213                         null, false);
5214             }
5215             if (mAppAgentMap != null && mAppAgentMap.containsKey(processName)) {
5216                 // We need to do a debuggable check here. See setAgentApp for why the check is
5217                 // postponed to here.
5218                 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
5219                     String agent = mAppAgentMap.get(processName);
5220                     // Do not overwrite already requested agent.
5221                     if (profilerInfo == null) {
5222                         profilerInfo = new ProfilerInfo(null, null, 0, false, false,
5223                                 mAppAgentMap.get(processName), true);
5224                     } else if (profilerInfo.agent == null) {
5225                         profilerInfo = profilerInfo.setAgent(mAppAgentMap.get(processName), true);
5226                     }
5227                 }
5228             }
5229 
5230             if (profilerInfo != null && profilerInfo.profileFd != null) {
5231                 profilerInfo.profileFd = profilerInfo.profileFd.dup();
5232                 if (TextUtils.equals(mProfileData.getProfileApp(), processName)
5233                         && mProfileData.getProfilerInfo() != null) {
5234                     clearProfilerLocked();
5235                 }
5236             }
5237 
5238             // We deprecated Build.SERIAL and it is not accessible to
5239             // Instant Apps and target APIs higher than O MR1. Since access to the serial
5240             // is now behind a permission we push down the value.
5241             final String buildSerial = (!appInfo.isInstantApp()
5242                     && appInfo.targetSdkVersion < Build.VERSION_CODES.P)
5243                             ? sTheRealBuildSerial : Build.UNKNOWN;
5244 
5245             // Check if this is a secondary process that should be incorporated into some
5246             // currently active instrumentation.  (Note we do this AFTER all of the profiling
5247             // stuff above because profiling can currently happen only in the primary
5248             // instrumentation process.)
5249             if (mActiveInstrumentation.size() > 0 && instr == null) {
5250                 for (int i = mActiveInstrumentation.size() - 1;
5251                         i >= 0 && app.getActiveInstrumentation() == null; i--) {
5252                     ActiveInstrumentation aInstr = mActiveInstrumentation.get(i);
5253                     if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) {
5254                         if (aInstr.mTargetProcesses.length == 0) {
5255                             // This is the wildcard mode, where every process brought up for
5256                             // the target instrumentation should be included.
5257                             if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) {
5258                                 app.setActiveInstrumentation(aInstr);
5259                                 aInstr.mRunningProcesses.add(app);
5260                             }
5261                         } else {
5262                             for (String proc : aInstr.mTargetProcesses) {
5263                                 if (proc.equals(app.processName)) {
5264                                     app.setActiveInstrumentation(aInstr);
5265                                     aInstr.mRunningProcesses.add(app);
5266                                     break;
5267                                 }
5268                             }
5269                         }
5270                     }
5271                 }
5272             }
5273 
5274             // If we were asked to attach an agent on startup, do so now, before we're binding
5275             // application code.
5276             if (preBindAgent != null) {
5277                 thread.attachAgent(preBindAgent);
5278             }
5279             if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
5280                 thread.attachStartupAgents(app.info.dataDir);
5281             }
5282 
5283             // Figure out whether the app needs to run in autofill compat mode.
5284             AutofillOptions autofillOptions = null;
5285             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
5286                 final AutofillManagerInternal afm = LocalServices.getService(
5287                         AutofillManagerInternal.class);
5288                 if (afm != null) {
5289                     autofillOptions = afm.getAutofillOptions(
5290                             app.info.packageName, app.info.longVersionCode, app.userId);
5291                 }
5292             }
5293             ContentCaptureOptions contentCaptureOptions = null;
5294             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
5295                 final ContentCaptureManagerInternal ccm =
5296                         LocalServices.getService(ContentCaptureManagerInternal.class);
5297                 if (ccm != null) {
5298                     contentCaptureOptions = ccm.getOptionsForPackage(app.userId,
5299                             app.info.packageName);
5300                 }
5301             }
5302 
5303             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
5304             bindApplicationTimeMillis = SystemClock.elapsedRealtime();
5305             mAtmInternal.preBindApplication(app.getWindowProcessController());
5306             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
5307             if (mPlatformCompat != null) {
5308                 mPlatformCompat.resetReporting(app.info);
5309             }
5310             final ProviderInfoList providerList = ProviderInfoList.fromList(providers);
5311             if (app.isolatedEntryPoint != null) {
5312                 // This is an isolated process which should just call an entry point instead of
5313                 // being bound to an application.
5314                 thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
5315             } else if (instr2 != null) {
5316                 thread.bindApplication(processName, appInfo, providerList,
5317                         instr2.mClass,
5318                         profilerInfo, instr2.mArguments,
5319                         instr2.mWatcher,
5320                         instr2.mUiAutomationConnection, testMode,
5321                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
5322                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
5323                         new Configuration(app.getWindowProcessController().getConfiguration()),
5324                         app.compat, getCommonServicesLocked(app.isolated),
5325                         mCoreSettingsObserver.getCoreSettingsLocked(),
5326                         buildSerial, autofillOptions, contentCaptureOptions,
5327                         app.mDisabledCompatChanges);
5328             } else {
5329                 thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
5330                         null, null, null, testMode,
5331                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
5332                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
5333                         new Configuration(app.getWindowProcessController().getConfiguration()),
5334                         app.compat, getCommonServicesLocked(app.isolated),
5335                         mCoreSettingsObserver.getCoreSettingsLocked(),
5336                         buildSerial, autofillOptions, contentCaptureOptions,
5337                         app.mDisabledCompatChanges);
5338             }
5339             if (profilerInfo != null) {
5340                 profilerInfo.closeFd();
5341                 profilerInfo = null;
5342             }
5343 
5344             // Make app active after binding application or client may be running requests (e.g
5345             // starting activities) before it is ready.
5346             app.makeActive(thread, mProcessStats);
5347             checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
5348             mProcessList.updateLruProcessLocked(app, false, null);
5349             checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
5350             app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
5351         } catch (Exception e) {
5352             // We need kill the process group here. (b/148588589)
5353             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
5354             app.resetPackageList(mProcessStats);
5355             app.unlinkDeathRecipient();
5356             app.kill("error during bind", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
5357             handleAppDiedLocked(app, false, true);
5358             return false;
5359         }
5360 
5361         // Remove this record from the list of starting applications.
5362         mPersistentStartingProcesses.remove(app);
5363         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
5364                 "Attach application locked removing on hold: " + app);
5365         mProcessesOnHold.remove(app);
5366 
5367         boolean badApp = false;
5368         boolean didSomething = false;
5369 
5370         // See if the top visible activity is waiting to run in this process...
5371         if (normalMode) {
5372             try {
5373                 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
5374             } catch (Exception e) {
5375                 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
5376                 badApp = true;
5377             }
5378         }
5379 
5380         // Find any services that should be running in this process...
5381         if (!badApp) {
5382             try {
5383                 didSomething |= mServices.attachApplicationLocked(app, processName);
5384                 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
5385             } catch (Exception e) {
5386                 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
5387                 badApp = true;
5388             }
5389         }
5390 
5391         // Check if a next-broadcast receiver is in this process...
5392         if (!badApp && isPendingBroadcastProcessLocked(pid)) {
5393             try {
5394                 didSomething |= sendPendingBroadcastsLocked(app);
5395                 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
5396             } catch (Exception e) {
5397                 // If the app died trying to launch the receiver we declare it 'bad'
5398                 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
5399                 badApp = true;
5400             }
5401         }
5402 
5403         // Check whether the next backup agent is in this process...
5404         if (!badApp && backupTarget != null && backupTarget.app == app) {
5405             if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
5406                     "New app is backup target, launching agent for " + app);
5407             notifyPackageUse(backupTarget.appInfo.packageName,
5408                              PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
5409             try {
5410                 thread.scheduleCreateBackupAgent(backupTarget.appInfo,
5411                         compatibilityInfoForPackage(backupTarget.appInfo),
5412                         backupTarget.backupMode, backupTarget.userId);
5413             } catch (Exception e) {
5414                 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
5415                 badApp = true;
5416             }
5417         }
5418 
5419         if (badApp) {
5420             app.kill("error during init", ApplicationExitInfo.REASON_INITIALIZATION_FAILURE, true);
5421             handleAppDiedLocked(app, false, true);
5422             return false;
5423         }
5424 
5425         if (!didSomething) {
5426             updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
5427             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
5428         }
5429 
5430         FrameworkStatsLog.write(
5431                 FrameworkStatsLog.PROCESS_START_TIME,
5432                 app.info.uid,
5433                 app.pid,
5434                 app.info.packageName,
5435                 FrameworkStatsLog.PROCESS_START_TIME__TYPE__COLD,
5436                 app.startTime,
5437                 (int) (bindApplicationTimeMillis - app.startTime),
5438                 (int) (SystemClock.elapsedRealtime() - app.startTime),
5439                 app.hostingRecord.getType(),
5440                 (app.hostingRecord.getName() != null ? app.hostingRecord.getName() : ""));
5441         return true;
5442     }
5443 
5444     @Override
attachApplication(IApplicationThread thread, long startSeq)5445     public final void attachApplication(IApplicationThread thread, long startSeq) {
5446         if (thread == null) {
5447             throw new SecurityException("Invalid application interface");
5448         }
5449         synchronized (this) {
5450             int callingPid = Binder.getCallingPid();
5451             final int callingUid = Binder.getCallingUid();
5452             final long origId = Binder.clearCallingIdentity();
5453             attachApplicationLocked(thread, callingPid, callingUid, startSeq);
5454             Binder.restoreCallingIdentity(origId);
5455         }
5456     }
5457 
5458     @Override
showBootMessage(final CharSequence msg, final boolean always)5459     public void showBootMessage(final CharSequence msg, final boolean always) {
5460         if (Binder.getCallingUid() != myUid()) {
5461             throw new SecurityException();
5462         }
5463         mWindowManager.showBootMessage(msg, always);
5464     }
5465 
finishBooting()5466     final void finishBooting() {
5467         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
5468                 Trace.TRACE_TAG_ACTIVITY_MANAGER);
5469         t.traceBegin("FinishBooting");
5470 
5471         synchronized (this) {
5472             if (!mBootAnimationComplete) {
5473                 mCallFinishBooting = true;
5474                 return;
5475             }
5476             mCallFinishBooting = false;
5477         }
5478 
5479         // Let the ART runtime in zygote and system_server know that the boot completed.
5480         ZYGOTE_PROCESS.bootCompleted();
5481         VMRuntime.bootCompleted();
5482 
5483         IntentFilter pkgFilter = new IntentFilter();
5484         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
5485         pkgFilter.addDataScheme("package");
5486         mContext.registerReceiver(new BroadcastReceiver() {
5487             @Override
5488             public void onReceive(Context context, Intent intent) {
5489                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
5490                 if (pkgs != null) {
5491                     for (String pkg : pkgs) {
5492                         synchronized (ActivityManagerService.this) {
5493                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
5494                                     0, "query restart")) {
5495                                 setResultCode(Activity.RESULT_OK);
5496                                 return;
5497                             }
5498                         }
5499                     }
5500                 }
5501             }
5502         }, pkgFilter);
5503 
5504         // Inform checkpointing systems of success
5505         try {
5506             // This line is needed to CTS test for the correct exception handling
5507             // See b/138952436#comment36 for context
5508             Slog.i(TAG, "About to commit checkpoint");
5509             IStorageManager storageManager = PackageHelper.getStorageManager();
5510             storageManager.commitChanges();
5511         } catch (Exception e) {
5512             PowerManager pm = (PowerManager)
5513                      mInjector.getContext().getSystemService(Context.POWER_SERVICE);
5514             pm.reboot("Checkpoint commit failed");
5515         }
5516 
5517         // Let system services know.
5518         mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED);
5519 
5520         synchronized (this) {
5521             // Ensure that any processes we had put on hold are now started
5522             // up.
5523             final int NP = mProcessesOnHold.size();
5524             if (NP > 0) {
5525                 ArrayList<ProcessRecord> procs =
5526                     new ArrayList<ProcessRecord>(mProcessesOnHold);
5527                 for (int ip=0; ip<NP; ip++) {
5528                     if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: "
5529                             + procs.get(ip));
5530                     mProcessList.startProcessLocked(procs.get(ip),
5531                             new HostingRecord("on-hold"),
5532                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
5533                 }
5534             }
5535             if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5536                 return;
5537             }
5538             // Start looking for apps that are abusing wake locks.
5539             Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
5540             mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
5541             // Check if we are performing userspace reboot before setting sys.boot_completed to
5542             // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys
5543             // .boot_completed is 1.
5544             if (InitProperties.userspace_reboot_in_progress().orElse(false)) {
5545                 UserspaceRebootLogger.noteUserspaceRebootSuccess();
5546             }
5547             // Tell anyone interested that we are done booting!
5548             SystemProperties.set("sys.boot_completed", "1");
5549 
5550             // And trigger dev.bootcomplete if we are not showing encryption progress
5551             if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse(""))
5552                     || "".equals(VoldProperties.encrypt_progress().orElse(""))) {
5553                 SystemProperties.set("dev.bootcomplete", "1");
5554             }
5555             mUserController.sendBootCompleted(
5556                     new IIntentReceiver.Stub() {
5557                         @Override
5558                         public void performReceive(Intent intent, int resultCode,
5559                                 String data, Bundle extras, boolean ordered,
5560                                 boolean sticky, int sendingUser) {
5561                             synchronized (ActivityManagerService.this) {
5562                                 mOomAdjuster.mCachedAppOptimizer.compactAllSystem();
5563                                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
5564                             }
5565                         }
5566                     });
5567             maybeLogUserspaceRebootEvent();
5568             mUserController.scheduleStartProfiles();
5569         }
5570         // UART is on if init's console service is running, send a warning notification.
5571         showConsoleNotificationIfActive();
5572 
5573         t.traceEnd();
5574     }
5575 
showConsoleNotificationIfActive()5576     private void showConsoleNotificationIfActive() {
5577         if (!SystemProperties.get("init.svc.console").equals("running")) {
5578             return;
5579         }
5580         String title = mContext
5581                 .getString(com.android.internal.R.string.console_running_notification_title);
5582         String message = mContext
5583                 .getString(com.android.internal.R.string.console_running_notification_message);
5584         Notification notification =
5585                 new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
5586                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
5587                         .setWhen(0)
5588                         .setOngoing(true)
5589                         .setTicker(title)
5590                         .setDefaults(0)  // please be quiet
5591                         .setColor(mContext.getColor(
5592                                 com.android.internal.R.color
5593                                         .system_notification_accent_color))
5594                         .setContentTitle(title)
5595                         .setContentText(message)
5596                         .setVisibility(Notification.VISIBILITY_PUBLIC)
5597                         .build();
5598 
5599         NotificationManager notificationManager =
5600                 mContext.getSystemService(NotificationManager.class);
5601         notificationManager.notifyAsUser(
5602                 null, SystemMessage.NOTE_SERIAL_CONSOLE_ENABLED, notification, UserHandle.ALL);
5603 
5604     }
5605 
5606     @Override
bootAnimationComplete()5607     public void bootAnimationComplete() {
5608         final boolean callFinishBooting;
5609         synchronized (this) {
5610             callFinishBooting = mCallFinishBooting;
5611             mBootAnimationComplete = true;
5612         }
5613         if (callFinishBooting) {
5614             finishBooting();
5615         }
5616     }
5617 
ensureBootCompleted()5618     final void ensureBootCompleted() {
5619         boolean booting;
5620         boolean enableScreen;
5621         synchronized (this) {
5622             booting = mBooting;
5623             mBooting = false;
5624             enableScreen = !mBooted;
5625             mBooted = true;
5626         }
5627 
5628         if (booting) {
5629             finishBooting();
5630         }
5631 
5632         if (enableScreen) {
5633             mAtmInternal.enableScreenAfterBoot(mBooted);
5634         }
5635     }
5636 
5637     /**
5638      * @deprecated Use {@link #getIntentSenderWithFeature} instead
5639      */
5640     @Deprecated
5641     @Override
getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5642     public IIntentSender getIntentSender(int type,
5643             String packageName, IBinder token, String resultWho,
5644             int requestCode, Intent[] intents, String[] resolvedTypes,
5645             int flags, Bundle bOptions, int userId) {
5646         return getIntentSenderWithFeature(type, packageName, null, token, resultWho, requestCode,
5647                 intents, resolvedTypes, flags, bOptions, userId);
5648     }
5649 
5650     @Override
getIntentSenderWithFeature(int type, String packageName, String featureId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5651     public IIntentSender getIntentSenderWithFeature(int type, String packageName, String featureId,
5652             IBinder token, String resultWho, int requestCode, Intent[] intents,
5653             String[] resolvedTypes, int flags, Bundle bOptions, int userId) {
5654         // NOTE: The service lock isn't held in this method because nothing in the method requires
5655         // the service lock to be held.
5656 
5657         enforceNotIsolatedCaller("getIntentSender");
5658         // Refuse possible leaked file descriptors
5659         if (intents != null) {
5660             if (intents.length < 1) {
5661                 throw new IllegalArgumentException("Intents array length must be >= 1");
5662             }
5663             for (int i=0; i<intents.length; i++) {
5664                 Intent intent = intents[i];
5665                 if (intent != null) {
5666                     if (intent.hasFileDescriptors()) {
5667                         throw new IllegalArgumentException("File descriptors passed in Intent");
5668                     }
5669                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
5670                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5671                         throw new IllegalArgumentException(
5672                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5673                     }
5674                     intents[i] = new Intent(intent);
5675                 }
5676             }
5677             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
5678                 throw new IllegalArgumentException(
5679                         "Intent array length does not match resolvedTypes length");
5680             }
5681         }
5682         if (bOptions != null) {
5683             if (bOptions.hasFileDescriptors()) {
5684                 throw new IllegalArgumentException("File descriptors passed in options");
5685             }
5686         }
5687 
5688         int callingUid = Binder.getCallingUid();
5689         int origUserId = userId;
5690         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
5691                 type == ActivityManager.INTENT_SENDER_BROADCAST,
5692                 ALLOW_NON_FULL, "getIntentSender", null);
5693         if (origUserId == UserHandle.USER_CURRENT) {
5694             // We don't want to evaluate this until the pending intent is
5695             // actually executed.  However, we do want to always do the
5696             // security checking for it above.
5697             userId = UserHandle.USER_CURRENT;
5698         }
5699         try {
5700             if (callingUid != 0 && callingUid != SYSTEM_UID) {
5701                 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
5702                         MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callingUid));
5703                 if (!UserHandle.isSameApp(callingUid, uid)) {
5704                     String msg = "Permission Denial: getIntentSender() from pid="
5705                         + Binder.getCallingPid()
5706                         + ", uid=" + Binder.getCallingUid()
5707                         + ", (need uid=" + uid + ")"
5708                         + " is not allowed to send as package " + packageName;
5709                     Slog.w(TAG, msg);
5710                     throw new SecurityException(msg);
5711                 }
5712             }
5713 
5714             if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5715                 return mAtmInternal.getIntentSender(type, packageName, featureId, callingUid,
5716                         userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5717                         bOptions);
5718             }
5719             return mPendingIntentController.getIntentSender(type, packageName, featureId,
5720                     callingUid, userId, token, resultWho, requestCode, intents, resolvedTypes,
5721                     flags, bOptions);
5722         } catch (RemoteException e) {
5723             throw new SecurityException(e);
5724         }
5725     }
5726 
5727     @Override
sendIntentSender(IIntentSender target, IBinder whitelistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5728     public int sendIntentSender(IIntentSender target, IBinder whitelistToken, int code,
5729             Intent intent, String resolvedType,
5730             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
5731         if (target instanceof PendingIntentRecord) {
5732             return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType,
5733                     whitelistToken, finishedReceiver, requiredPermission, options);
5734         } else {
5735             if (intent == null) {
5736                 // Weird case: someone has given us their own custom IIntentSender, and now
5737                 // they have someone else trying to send to it but of course this isn't
5738                 // really a PendingIntent, so there is no base Intent, and the caller isn't
5739                 // supplying an Intent... but we never want to dispatch a null Intent to
5740                 // a receiver, so um...  let's make something up.
5741                 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
5742                 intent = new Intent(Intent.ACTION_MAIN);
5743             }
5744             try {
5745                 target.send(code, intent, resolvedType, whitelistToken, null,
5746                         requiredPermission, options);
5747             } catch (RemoteException e) {
5748             }
5749             // Platform code can rely on getting a result back when the send is done, but if
5750             // this intent sender is from outside of the system we can't rely on it doing that.
5751             // So instead we don't give it the result receiver, and instead just directly
5752             // report the finish immediately.
5753             if (finishedReceiver != null) {
5754                 try {
5755                     finishedReceiver.performReceive(intent, 0,
5756                             null, null, false, false, UserHandle.getCallingUserId());
5757                 } catch (RemoteException e) {
5758                 }
5759             }
5760             return 0;
5761         }
5762     }
5763 
5764     @Override
cancelIntentSender(IIntentSender sender)5765     public void cancelIntentSender(IIntentSender sender) {
5766         mPendingIntentController.cancelIntentSender(sender);
5767     }
5768 
5769     @Override
getPackageForIntentSender(IIntentSender pendingResult)5770     public String getPackageForIntentSender(IIntentSender pendingResult) {
5771         if (!(pendingResult instanceof PendingIntentRecord)) {
5772             return null;
5773         }
5774         try {
5775             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5776             return res.key.packageName;
5777         } catch (ClassCastException e) {
5778         }
5779         return null;
5780     }
5781 
5782     @Override
registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5783     public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) {
5784         mPendingIntentController.registerIntentSenderCancelListener(sender, receiver);
5785     }
5786 
5787     @Override
unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5788     public void unregisterIntentSenderCancelListener(IIntentSender sender,
5789             IResultReceiver receiver) {
5790         mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver);
5791     }
5792 
5793     @Override
getUidForIntentSender(IIntentSender sender)5794     public int getUidForIntentSender(IIntentSender sender) {
5795         if (sender instanceof PendingIntentRecord) {
5796             try {
5797                 PendingIntentRecord res = (PendingIntentRecord)sender;
5798                 return res.uid;
5799             } catch (ClassCastException e) {
5800             }
5801         }
5802         return -1;
5803     }
5804 
5805     @Override
isIntentSenderTargetedToPackage(IIntentSender pendingResult)5806     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5807         if (!(pendingResult instanceof PendingIntentRecord)) {
5808             return false;
5809         }
5810         try {
5811             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5812             if (res.key.allIntents == null) {
5813                 return false;
5814             }
5815             for (int i=0; i<res.key.allIntents.length; i++) {
5816                 Intent intent = res.key.allIntents[i];
5817                 if (intent.getPackage() != null && intent.getComponent() != null) {
5818                     return false;
5819                 }
5820             }
5821             return true;
5822         } catch (ClassCastException e) {
5823         }
5824         return false;
5825     }
5826 
5827     @Override
isIntentSenderAnActivity(IIntentSender pendingResult)5828     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
5829         if (!(pendingResult instanceof PendingIntentRecord)) {
5830             return false;
5831         }
5832         try {
5833             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5834             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
5835                 return true;
5836             }
5837             return false;
5838         } catch (ClassCastException e) {
5839         }
5840         return false;
5841     }
5842 
5843     @Override
isIntentSenderAForegroundService(IIntentSender pendingResult)5844     public boolean isIntentSenderAForegroundService(IIntentSender pendingResult) {
5845         if (pendingResult instanceof PendingIntentRecord) {
5846             final PendingIntentRecord res = (PendingIntentRecord) pendingResult;
5847             return res.key.type == ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE;
5848         }
5849         return false;
5850     }
5851 
5852     @Override
isIntentSenderABroadcast(IIntentSender pendingResult)5853     public boolean isIntentSenderABroadcast(IIntentSender pendingResult) {
5854         if (pendingResult instanceof PendingIntentRecord) {
5855             final PendingIntentRecord res = (PendingIntentRecord) pendingResult;
5856             return res.key.type == ActivityManager.INTENT_SENDER_BROADCAST;
5857         }
5858         return false;
5859     }
5860 
5861     @Override
getIntentForIntentSender(IIntentSender pendingResult)5862     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
5863         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5864                 "getIntentForIntentSender()");
5865         if (!(pendingResult instanceof PendingIntentRecord)) {
5866             return null;
5867         }
5868         try {
5869             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5870             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
5871         } catch (ClassCastException e) {
5872         }
5873         return null;
5874     }
5875 
5876     @Override
getTagForIntentSender(IIntentSender pendingResult, String prefix)5877     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
5878         if (!(pendingResult instanceof PendingIntentRecord)) {
5879             return null;
5880         }
5881         try {
5882             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5883             synchronized (this) {
5884                 return getTagForIntentSenderLocked(res, prefix);
5885             }
5886         } catch (ClassCastException e) {
5887         }
5888         return null;
5889     }
5890 
getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5891     String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
5892         final Intent intent = res.key.requestIntent;
5893         if (intent != null) {
5894             if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
5895                     || res.lastTagPrefix.equals(prefix))) {
5896                 return res.lastTag;
5897             }
5898             res.lastTagPrefix = prefix;
5899             final StringBuilder sb = new StringBuilder(128);
5900             if (prefix != null) {
5901                 sb.append(prefix);
5902             }
5903             if (intent.getAction() != null) {
5904                 sb.append(intent.getAction());
5905             } else if (intent.getComponent() != null) {
5906                 intent.getComponent().appendShortString(sb);
5907             } else {
5908                 sb.append("?");
5909             }
5910             return res.lastTag = sb.toString();
5911         }
5912         return null;
5913     }
5914 
5915     @Override
setProcessLimit(int max)5916     public void setProcessLimit(int max) {
5917         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5918                 "setProcessLimit()");
5919         synchronized (this) {
5920             mConstants.setOverrideMaxCachedProcesses(max);
5921         }
5922         trimApplications(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
5923     }
5924 
5925     @Override
getProcessLimit()5926     public int getProcessLimit() {
5927         synchronized (this) {
5928             return mConstants.getOverrideMaxCachedProcesses();
5929         }
5930     }
5931 
importanceTokenDied(ImportanceToken token)5932     void importanceTokenDied(ImportanceToken token) {
5933         synchronized (ActivityManagerService.this) {
5934             ProcessRecord pr = null;
5935             synchronized (mPidsSelfLocked) {
5936                 ImportanceToken cur
5937                     = mImportantProcesses.get(token.pid);
5938                 if (cur != token) {
5939                     return;
5940                 }
5941                 mImportantProcesses.remove(token.pid);
5942                 pr = mPidsSelfLocked.get(token.pid);
5943                 if (pr == null) {
5944                     return;
5945                 }
5946                 pr.forcingToImportant = null;
5947                 updateProcessForegroundLocked(pr, false, 0, false);
5948             }
5949             updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5950         }
5951     }
5952 
5953     @Override
setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5954     public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
5955         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5956                 "setProcessImportant()");
5957         synchronized(this) {
5958             boolean changed = false;
5959 
5960             ProcessRecord pr = null;
5961             synchronized (mPidsSelfLocked) {
5962                 pr = mPidsSelfLocked.get(pid);
5963                 if (pr == null && isForeground) {
5964                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5965                     return;
5966                 }
5967                 ImportanceToken oldToken = mImportantProcesses.get(pid);
5968                 if (oldToken != null) {
5969                     oldToken.token.unlinkToDeath(oldToken, 0);
5970                     mImportantProcesses.remove(pid);
5971                     if (pr != null) {
5972                         pr.forcingToImportant = null;
5973                     }
5974                     changed = true;
5975                 }
5976                 if (isForeground && token != null) {
5977                     ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
5978                         @Override
5979                         public void binderDied() {
5980                             importanceTokenDied(this);
5981                         }
5982                     };
5983                     try {
5984                         token.linkToDeath(newToken, 0);
5985                         mImportantProcesses.put(pid, newToken);
5986                         pr.forcingToImportant = newToken;
5987                         changed = true;
5988                     } catch (RemoteException e) {
5989                         // If the process died while doing this, we will later
5990                         // do the cleanup with the process death link.
5991                     }
5992                 }
5993             }
5994 
5995             if (changed) {
5996                 updateOomAdjLocked(pr, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5997             }
5998         }
5999     }
6000 
isAppForeground(int uid)6001     private boolean isAppForeground(int uid) {
6002         synchronized (this) {
6003             UidRecord uidRec = mProcessList.mActiveUids.get(uid);
6004             if (uidRec == null || uidRec.idle) {
6005                 return false;
6006             }
6007             return uidRec.getCurProcState()
6008                     <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
6009         }
6010     }
6011 
isAppBad(ApplicationInfo info)6012     private boolean isAppBad(ApplicationInfo info) {
6013         return mAppErrors.isBadProcess(info.processName, info.uid);
6014     }
6015 
6016     // NOTE: this is an internal method used by the OnShellCommand implementation only and should
6017     // be guarded by permission checking.
getUidState(int uid)6018     int getUidState(int uid) {
6019         synchronized (this) {
6020             return mProcessList.getUidProcStateLocked(uid);
6021         }
6022     }
6023 
6024     // =========================================================
6025     // PROCESS INFO
6026     // =========================================================
6027 
6028     static class ProcessInfoService extends IProcessInfoService.Stub {
6029         final ActivityManagerService mActivityManagerService;
ProcessInfoService(ActivityManagerService activityManagerService)6030         ProcessInfoService(ActivityManagerService activityManagerService) {
6031             mActivityManagerService = activityManagerService;
6032         }
6033 
6034         @Override
getProcessStatesFromPids( int[] pids, int[] states)6035         public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
6036             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
6037                     /*in*/ pids, /*out*/ states, null);
6038         }
6039 
6040         @Override
getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)6041         public void getProcessStatesAndOomScoresFromPids(
6042                 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
6043             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
6044                     /*in*/ pids, /*out*/ states, /*out*/ scores);
6045         }
6046     }
6047 
6048     /**
6049      * For each PID in the given input array, write the current process state
6050      * for that process into the states array, or -1 to indicate that no
6051      * process with the given PID exists. If scores array is provided, write
6052      * the oom score for the process into the scores array, with INVALID_ADJ
6053      * indicating the PID doesn't exist.
6054      */
getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)6055     public void getProcessStatesAndOomScoresForPIDs(
6056             /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
6057         if (scores != null) {
6058             enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
6059                     "getProcessStatesAndOomScoresForPIDs()");
6060         }
6061 
6062         if (pids == null) {
6063             throw new NullPointerException("pids");
6064         } else if (states == null) {
6065             throw new NullPointerException("states");
6066         } else if (pids.length != states.length) {
6067             throw new IllegalArgumentException("pids and states arrays have different lengths!");
6068         } else if (scores != null && pids.length != scores.length) {
6069             throw new IllegalArgumentException("pids and scores arrays have different lengths!");
6070         }
6071 
6072         synchronized (mPidsSelfLocked) {
6073             for (int i = 0; i < pids.length; i++) {
6074                 ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
6075                 if (pr != null) {
6076                     final boolean isPendingTop =
6077                                 mPendingStartActivityUids.isPendingTopPid(pr.uid, pids[i]);
6078                     states[i] = isPendingTop ? PROCESS_STATE_TOP : pr.getCurProcState();
6079                     if (scores != null) {
6080                         scores[i] = isPendingTop ? (ProcessList.FOREGROUND_APP_ADJ - 1) : pr.curAdj;
6081                     }
6082                 } else {
6083                     states[i] = PROCESS_STATE_NONEXISTENT;
6084                     if (scores != null) {
6085                         scores[i] = ProcessList.INVALID_ADJ;
6086                     }
6087                 }
6088             }
6089         }
6090     }
6091 
6092     // =========================================================
6093     // PERMISSIONS
6094     // =========================================================
6095 
6096     static class PermissionController extends IPermissionController.Stub {
6097         ActivityManagerService mActivityManagerService;
PermissionController(ActivityManagerService activityManagerService)6098         PermissionController(ActivityManagerService activityManagerService) {
6099             mActivityManagerService = activityManagerService;
6100         }
6101 
6102         @Override
checkPermission(String permission, int pid, int uid)6103         public boolean checkPermission(String permission, int pid, int uid) {
6104             return mActivityManagerService.checkPermission(permission, pid,
6105                     uid) == PackageManager.PERMISSION_GRANTED;
6106         }
6107 
6108         @Override
noteOp(String op, int uid, String packageName)6109         public int noteOp(String op, int uid, String packageName) {
6110             // TODO moltmann: Allow to specify featureId
6111             return mActivityManagerService.mAppOpsService
6112                     .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName, null,
6113                             false, "", false);
6114         }
6115 
6116         @Override
getPackagesForUid(int uid)6117         public String[] getPackagesForUid(int uid) {
6118             return mActivityManagerService.mContext.getPackageManager()
6119                     .getPackagesForUid(uid);
6120         }
6121 
6122         @Override
isRuntimePermission(String permission)6123         public boolean isRuntimePermission(String permission) {
6124             try {
6125                 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
6126                         .getPermissionInfo(permission, 0);
6127                 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
6128                         == PermissionInfo.PROTECTION_DANGEROUS;
6129             } catch (NameNotFoundException nnfe) {
6130                 Slog.e(TAG, "No such permission: "+ permission, nnfe);
6131             }
6132             return false;
6133         }
6134 
6135         @Override
getPackageUid(String packageName, int flags)6136         public int getPackageUid(String packageName, int flags) {
6137             try {
6138                 return mActivityManagerService.mContext.getPackageManager()
6139                         .getPackageUid(packageName, flags);
6140             } catch (NameNotFoundException nnfe) {
6141                 return -1;
6142             }
6143         }
6144     }
6145 
6146     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
6147         @Override
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)6148         public int checkComponentPermission(String permission, int pid, int uid,
6149                 int owningUid, boolean exported) {
6150             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
6151                     owningUid, exported);
6152         }
6153 
6154         @Override
getAMSLock()6155         public Object getAMSLock() {
6156             return ActivityManagerService.this;
6157         }
6158     }
6159 
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)6160     public static int checkComponentPermission(String permission, int pid, int uid,
6161             int owningUid, boolean exported) {
6162         if (pid == MY_PID) {
6163             return PackageManager.PERMISSION_GRANTED;
6164         }
6165         // If there is an explicit permission being checked, and this is coming from a process
6166         // that has been denied access to that permission, then just deny.  Ultimately this may
6167         // not be quite right -- it means that even if the caller would have access for another
6168         // reason (such as being the owner of the component it is trying to access), it would still
6169         // fail.  This also means the system and root uids would be able to deny themselves
6170         // access to permissions, which...  well okay. ¯\_(ツ)_/¯
6171         if (permission != null) {
6172             synchronized (sActiveProcessInfoSelfLocked) {
6173                 ProcessInfo procInfo = sActiveProcessInfoSelfLocked.get(pid);
6174                 if (procInfo != null && procInfo.deniedPermissions != null
6175                         && procInfo.deniedPermissions.contains(permission)) {
6176                     return PackageManager.PERMISSION_DENIED;
6177                 }
6178             }
6179         }
6180         return ActivityManager.checkComponentPermission(permission, uid,
6181                 owningUid, exported);
6182     }
6183 
6184     /**
6185      * As the only public entry point for permissions checking, this method
6186      * can enforce the semantic that requesting a check on a null global
6187      * permission is automatically denied.  (Internally a null permission
6188      * string is used when calling {@link #checkComponentPermission} in cases
6189      * when only uid-based security is needed.)
6190      *
6191      * This can be called with or without the global lock held.
6192      */
6193     @Override
checkPermission(String permission, int pid, int uid)6194     public int checkPermission(String permission, int pid, int uid) {
6195         if (permission == null) {
6196             return PackageManager.PERMISSION_DENIED;
6197         }
6198         return checkComponentPermission(permission, pid, uid, -1, true);
6199     }
6200 
6201     @Override
checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken)6202     public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) {
6203         if (permission == null) {
6204             return PackageManager.PERMISSION_DENIED;
6205         }
6206 
6207         // We might be performing an operation on behalf of an indirect binder
6208         // invocation, e.g. via {@link #openContentUri}.  Check and adjust the
6209         // client identity accordingly before proceeding.
6210         Identity tlsIdentity = sCallerIdentity.get();
6211         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
6212             Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
6213                     + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
6214             uid = tlsIdentity.uid;
6215             pid = tlsIdentity.pid;
6216         }
6217 
6218         return checkComponentPermission(permission, pid, uid, -1, true);
6219     }
6220 
6221     /**
6222      * Binder IPC calls go through the public entry point.
6223      * This can be called with or without the global lock held.
6224      */
checkCallingPermission(String permission)6225     int checkCallingPermission(String permission) {
6226         return checkPermission(permission,
6227                 Binder.getCallingPid(),
6228                 Binder.getCallingUid());
6229     }
6230 
6231     /**
6232      * This can be called with or without the global lock held.
6233      */
enforceCallingPermission(String permission, String func)6234     void enforceCallingPermission(String permission, String func) {
6235         if (checkCallingPermission(permission)
6236                 == PackageManager.PERMISSION_GRANTED) {
6237             return;
6238         }
6239 
6240         String msg = "Permission Denial: " + func + " from pid="
6241                 + Binder.getCallingPid()
6242                 + ", uid=" + Binder.getCallingUid()
6243                 + " requires " + permission;
6244         Slog.w(TAG, msg);
6245         throw new SecurityException(msg);
6246     }
6247 
6248     /**
6249      * This can be called with or without the global lock held.
6250      */
enforcePermission(String permission, int pid, int uid, String func)6251     void enforcePermission(String permission, int pid, int uid, String func) {
6252         if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) {
6253             return;
6254         }
6255 
6256         String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid
6257                 + " requires " + permission;
6258         Slog.w(TAG, msg);
6259         throw new SecurityException(msg);
6260     }
6261 
isAppStartModeDisabled(int uid, String packageName)6262     public boolean isAppStartModeDisabled(int uid, String packageName) {
6263         synchronized (this) {
6264             return getAppStartModeLocked(uid, packageName, 0, -1, false, true, false)
6265                     == ActivityManager.APP_START_MODE_DISABLED;
6266         }
6267     }
6268 
isInRestrictedBucket(int userId, String packageName, long nowElapsed)6269     private boolean isInRestrictedBucket(int userId, String packageName, long nowElapsed) {
6270         return UsageStatsManager.STANDBY_BUCKET_RESTRICTED
6271                 <= mUsageStatsService.getAppStandbyBucket(packageName, userId, nowElapsed);
6272     }
6273 
6274     // Unified app-op and target sdk check
appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)6275     int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
6276         // Apps that target O+ are always subject to background check
6277         if (packageTargetSdk >= Build.VERSION_CODES.O) {
6278             if (DEBUG_BACKGROUND_CHECK) {
6279                 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
6280             }
6281             return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6282         }
6283         // It's a legacy app. If it's in the RESTRICTED bucket, always restrict on battery.
6284         if (mOnBattery // Short-circuit in common case.
6285                 && mConstants.FORCE_BACKGROUND_CHECK_ON_RESTRICTED_APPS
6286                 && isInRestrictedBucket(
6287                         UserHandle.getUserId(uid), packageName, SystemClock.elapsedRealtime())) {
6288             if (DEBUG_BACKGROUND_CHECK) {
6289                 Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " in RESTRICTED bucket");
6290             }
6291             return ActivityManager.APP_START_MODE_DELAYED;
6292         }
6293         // Not in the RESTRICTED bucket so policy is based on AppOp check.
6294         int appop = getAppOpsManager().noteOpNoThrow(AppOpsManager.OP_RUN_IN_BACKGROUND,
6295                 uid, packageName, null, "");
6296         if (DEBUG_BACKGROUND_CHECK) {
6297             Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
6298         }
6299         switch (appop) {
6300             case AppOpsManager.MODE_ALLOWED:
6301                 // If force-background-check is enabled, restrict all apps that aren't whitelisted.
6302                 if (mForceBackgroundCheck &&
6303                         !UserHandle.isCore(uid) &&
6304                         !isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ true)) {
6305                     if (DEBUG_BACKGROUND_CHECK) {
6306                         Slog.i(TAG, "Force background check: " +
6307                                 uid + "/" + packageName + " restricted");
6308                     }
6309                     return ActivityManager.APP_START_MODE_DELAYED;
6310                 }
6311                 return ActivityManager.APP_START_MODE_NORMAL;
6312             case AppOpsManager.MODE_IGNORED:
6313                 return ActivityManager.APP_START_MODE_DELAYED;
6314             default:
6315                 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6316         }
6317     }
6318 
6319     // Service launch is available to apps with run-in-background exemptions but
6320     // some other background operations are not.  If we're doing a check
6321     // of service-launch policy, allow those callers to proceed unrestricted.
appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)6322     int appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
6323         // Persistent app?
6324         if (mPackageManagerInt.isPackagePersistent(packageName)) {
6325             if (DEBUG_BACKGROUND_CHECK) {
6326                 Slog.i(TAG, "App " + uid + "/" + packageName
6327                         + " is persistent; not restricted in background");
6328             }
6329             return ActivityManager.APP_START_MODE_NORMAL;
6330         }
6331 
6332         // Non-persistent but background whitelisted?
6333         if (uidOnBackgroundWhitelist(uid)) {
6334             if (DEBUG_BACKGROUND_CHECK) {
6335                 Slog.i(TAG, "App " + uid + "/" + packageName
6336                         + " on background whitelist; not restricted in background");
6337             }
6338             return ActivityManager.APP_START_MODE_NORMAL;
6339         }
6340 
6341         // Is this app on the battery whitelist?
6342         if (isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ false)) {
6343             if (DEBUG_BACKGROUND_CHECK) {
6344                 Slog.i(TAG, "App " + uid + "/" + packageName
6345                         + " on idle whitelist; not restricted in background");
6346             }
6347             return ActivityManager.APP_START_MODE_NORMAL;
6348         }
6349 
6350         // None of the service-policy criteria apply, so we apply the common criteria
6351         return appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk);
6352     }
6353 
getAppStartModeLocked(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6354     int getAppStartModeLocked(int uid, String packageName, int packageTargetSdk,
6355             int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) {
6356         if (mInternal.isPendingTopUid(uid)) {
6357             return ActivityManager.APP_START_MODE_NORMAL;
6358         }
6359         UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
6360         if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
6361                 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
6362                 + (uidRec != null ? uidRec.idle : false));
6363         if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.idle) {
6364             boolean ephemeral;
6365             if (uidRec == null) {
6366                 ephemeral = getPackageManagerInternalLocked().isPackageEphemeral(
6367                         UserHandle.getUserId(uid), packageName);
6368             } else {
6369                 ephemeral = uidRec.ephemeral;
6370             }
6371 
6372             if (ephemeral) {
6373                 // We are hard-core about ephemeral apps not running in the background.
6374                 return ActivityManager.APP_START_MODE_DISABLED;
6375             } else {
6376                 if (disabledOnly) {
6377                     // The caller is only interested in whether app starts are completely
6378                     // disabled for the given package (that is, it is an instant app).  So
6379                     // we don't need to go further, which is all just seeing if we should
6380                     // apply a "delayed" mode for a regular app.
6381                     return ActivityManager.APP_START_MODE_NORMAL;
6382                 }
6383                 final int startMode = (alwaysRestrict)
6384                         ? appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk)
6385                         : appServicesRestrictedInBackgroundLocked(uid, packageName,
6386                                 packageTargetSdk);
6387                 if (DEBUG_BACKGROUND_CHECK) {
6388                     Slog.d(TAG, "checkAllowBackground: uid=" + uid
6389                             + " pkg=" + packageName + " startMode=" + startMode
6390                             + " onwhitelist=" + isOnDeviceIdleWhitelistLocked(uid, false)
6391                             + " onwhitelist(ei)=" + isOnDeviceIdleWhitelistLocked(uid, true));
6392                 }
6393                 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
6394                     // This is an old app that has been forced into a "compatible as possible"
6395                     // mode of background check.  To increase compatibility, we will allow other
6396                     // foreground apps to cause its services to start.
6397                     if (callingPid >= 0) {
6398                         ProcessRecord proc;
6399                         synchronized (mPidsSelfLocked) {
6400                             proc = mPidsSelfLocked.get(callingPid);
6401                         }
6402                         if (proc != null &&
6403                                 !ActivityManager.isProcStateBackground(proc.getCurProcState())) {
6404                             // Whoever is instigating this is in the foreground, so we will allow it
6405                             // to go through.
6406                             return ActivityManager.APP_START_MODE_NORMAL;
6407                         }
6408                     }
6409                 }
6410                 return startMode;
6411             }
6412         }
6413         return ActivityManager.APP_START_MODE_NORMAL;
6414     }
6415 
6416     /**
6417      * @return whether a UID is in the system, user or temp doze whitelist.
6418      */
isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo)6419     boolean isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo) {
6420         final int appId = UserHandle.getAppId(uid);
6421 
6422         final int[] whitelist = allowExceptIdleToo
6423                 ? mDeviceIdleExceptIdleWhitelist
6424                 : mDeviceIdleWhitelist;
6425 
6426         return Arrays.binarySearch(whitelist, appId) >= 0
6427                 || Arrays.binarySearch(mDeviceIdleTempWhitelist, appId) >= 0
6428                 || mPendingTempWhitelist.indexOfKey(uid) >= 0;
6429     }
6430 
6431     /**
6432      * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6433      * the whitelist
6434      */
getPendingTempWhitelistTagForUidLocked(int uid)6435     String getPendingTempWhitelistTagForUidLocked(int uid) {
6436         final PendingTempWhitelist ptw = mPendingTempWhitelist.get(uid);
6437         return ptw != null ? ptw.tag : null;
6438     }
6439 
getProviderInfoLocked(String authority, @UserIdInt int userId, int pmFlags)6440     private ProviderInfo getProviderInfoLocked(String authority, @UserIdInt int userId,
6441             int pmFlags) {
6442         ProviderInfo pi = null;
6443         ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
6444         if (cpr != null) {
6445             pi = cpr.info;
6446         } else {
6447             try {
6448                 pi = AppGlobals.getPackageManager().resolveContentProvider(
6449                         authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags, userId);
6450             } catch (RemoteException ex) {
6451             }
6452         }
6453         return pi;
6454     }
6455 
6456     @VisibleForTesting
grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId)6457     public void grantImplicitAccess(int userId, Intent intent, int visibleUid, int recipientAppId) {
6458         getPackageManagerInternalLocked().
6459                 grantImplicitAccess(userId, intent, recipientAppId, visibleUid, true /*direct*/);
6460     }
6461 
6462     /**
6463      * @param uri This uri must NOT contain an embedded userId.
6464      * @param userId The userId in which the uri is to be resolved.
6465      */
6466     @Override
checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6467     public int checkUriPermission(Uri uri, int pid, int uid,
6468             final int modeFlags, int userId, IBinder callerToken) {
6469         enforceNotIsolatedCaller("checkUriPermission");
6470 
6471         // Another redirected-binder-call permissions check as in
6472         // {@link checkPermissionWithToken}.
6473         Identity tlsIdentity = sCallerIdentity.get();
6474         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
6475             uid = tlsIdentity.uid;
6476             pid = tlsIdentity.pid;
6477         }
6478 
6479         // Our own process gets to do everything.
6480         if (pid == MY_PID) {
6481             return PackageManager.PERMISSION_GRANTED;
6482         }
6483         return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, modeFlags), uid, modeFlags)
6484                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
6485     }
6486 
6487     /**
6488      * @param uri This uri must NOT contain an embedded userId.
6489      * @param userId The userId in which the uri is to be resolved.
6490      */
6491     @Override
grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6492     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
6493             final int modeFlags, int userId) {
6494         enforceNotIsolatedCaller("grantUriPermission");
6495         GrantUri grantUri = new GrantUri(userId, uri, modeFlags);
6496         synchronized(this) {
6497             final ProcessRecord r = getRecordForAppLocked(caller);
6498             if (r == null) {
6499                 throw new SecurityException("Unable to find app for caller "
6500                         + caller
6501                         + " when granting permission to uri " + grantUri);
6502             }
6503             if (targetPkg == null) {
6504                 throw new IllegalArgumentException("null target");
6505             }
6506 
6507             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
6508                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
6509                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
6510                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
6511 
6512             final Intent intent = new Intent();
6513             intent.setData(uri);
6514             intent.setFlags(modeFlags);
6515 
6516             final NeededUriGrants needed = mUgmInternal.checkGrantUriPermissionFromIntent(intent,
6517                     r.uid, targetPkg, UserHandle.getUserId(r.uid));
6518             mUgmInternal.grantUriPermissionUncheckedFromIntent(needed, null);
6519         }
6520     }
6521 
6522     /**
6523      * @param uri This uri must NOT contain an embedded userId.
6524      * @param userId The userId in which the uri is to be resolved.
6525      */
6526     @Override
revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6527     public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
6528             final int modeFlags, int userId) {
6529         enforceNotIsolatedCaller("revokeUriPermission");
6530         synchronized(this) {
6531             final ProcessRecord r = getRecordForAppLocked(caller);
6532             if (r == null) {
6533                 throw new SecurityException("Unable to find app for caller "
6534                         + caller
6535                         + " when revoking permission to uri " + uri);
6536             }
6537             if (uri == null) {
6538                 Slog.w(TAG, "revokeUriPermission: null uri");
6539                 return;
6540             }
6541 
6542             if (!Intent.isAccessUriMode(modeFlags)) {
6543                 return;
6544             }
6545 
6546             final String authority = uri.getAuthority();
6547             final ProviderInfo pi = getProviderInfoLocked(authority, userId,
6548                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
6549             if (pi == null) {
6550                 Slog.w(TAG, "No content provider found for permission revoke: "
6551                         + uri.toSafeString());
6552                 return;
6553             }
6554 
6555             mUgmInternal.revokeUriPermission(targetPackage, r.uid,
6556                     new GrantUri(userId, uri, modeFlags), modeFlags);
6557         }
6558     }
6559 
6560     @Override
showWaitingForDebugger(IApplicationThread who, boolean waiting)6561     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6562         synchronized (this) {
6563             ProcessRecord app =
6564                 who != null ? getRecordForAppLocked(who) : null;
6565             if (app == null) return;
6566 
6567             Message msg = Message.obtain();
6568             msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
6569             msg.obj = app;
6570             msg.arg1 = waiting ? 1 : 0;
6571             mUiHandler.sendMessage(msg);
6572         }
6573     }
6574 
6575     @Override
getMemoryInfo(ActivityManager.MemoryInfo outInfo)6576     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6577         mProcessList.getMemoryInfo(outInfo);
6578     }
6579 
6580     // =========================================================
6581     // TASK MANAGEMENT
6582     // =========================================================
6583 
6584     @Override
getTasks(int maxNum)6585     public List<RunningTaskInfo> getTasks(int maxNum) {
6586         return mActivityTaskManager.getTasks(maxNum);
6587     }
6588 
6589     @Override
cancelTaskWindowTransition(int taskId)6590     public void cancelTaskWindowTransition(int taskId) {
6591         mActivityTaskManager.cancelTaskWindowTransition(taskId);
6592     }
6593 
6594     @Override
setTaskResizeable(int taskId, int resizeableMode)6595     public void setTaskResizeable(int taskId, int resizeableMode) {
6596         mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);
6597     }
6598 
6599     @Override
getTaskSnapshot(int taskId, boolean isLowResolution)6600     public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean isLowResolution) {
6601         return mActivityTaskManager.getTaskSnapshot(taskId, isLowResolution);
6602     }
6603 
6604     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)6605     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
6606         mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);
6607     }
6608 
6609     @Override
getTaskBounds(int taskId)6610     public Rect getTaskBounds(int taskId) {
6611         return mActivityTaskManager.getTaskBounds(taskId);
6612     }
6613 
6614     @Override
removeStack(int stackId)6615     public void removeStack(int stackId) {
6616         mActivityTaskManager.removeStack(stackId);
6617     }
6618 
6619     @Override
removeTask(int taskId)6620     public boolean removeTask(int taskId) {
6621         return mActivityTaskManager.removeTask(taskId);
6622     }
6623 
6624     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6625     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
6626             int flags, Bundle bOptions) {
6627         mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);
6628     }
6629 
6630     /**
6631      * Attempts to move a task backwards in z-order (the order of activities within the task is
6632      * unchanged).
6633      *
6634      * There are several possible results of this call:
6635      * - if the task is locked, then we will show the lock toast
6636      * - if there is a task behind the provided task, then that task is made visible and resumed as
6637      *   this task is moved to the back
6638      * - otherwise, if there are no other tasks in the stack:
6639      *     - if this task is in the pinned stack, then we remove the stack completely, which will
6640      *       have the effect of moving the task to the top or bottom of the fullscreen stack
6641      *       (depending on whether it is visible)
6642      *     - otherwise, we simply return home and hide this task
6643      *
6644      * @param token A reference to the activity we wish to move
6645      * @param nonRoot If false then this only works if the activity is the root
6646      *                of a task; if true it will work for any activity in a task.
6647      * @return Returns true if the move completed, false if not.
6648      */
6649     @Override
moveActivityTaskToBack(IBinder token, boolean nonRoot)6650     public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
6651         return mActivityTaskManager.moveActivityTaskToBack(token, nonRoot);
6652     }
6653 
6654     @Override
moveTaskToStack(int taskId, int stackId, boolean toTop)6655     public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
6656         mActivityTaskManager.moveTaskToStack(taskId, stackId, toTop);
6657     }
6658 
6659     @Override
getRecentTasks(int maxNum, int flags, int userId)6660     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
6661             int userId) {
6662         return mActivityTaskManager.getRecentTasks(maxNum, flags, userId);
6663     }
6664 
6665     /**
6666      * Moves the top activity in the input stackId to the pinned stack.
6667      *
6668      * @param stackId Id of stack to move the top activity to pinned stack.
6669      * @param bounds Bounds to use for pinned stack.
6670      *
6671      * @return True if the top activity of the input stack was successfully moved to the pinned
6672      *          stack.
6673      */
6674     @Override
moveTopActivityToPinnedStack(int stackId, Rect bounds)6675     public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
6676         return mActivityTaskManager.moveTopActivityToPinnedStack(stackId, bounds);
6677     }
6678 
6679     @Override
positionTaskInStack(int taskId, int stackId, int position)6680     public void positionTaskInStack(int taskId, int stackId, int position) {
6681         mActivityTaskManager.positionTaskInStack(taskId, stackId, position);
6682     }
6683 
6684     @Override
getAllStackInfos()6685     public List<StackInfo> getAllStackInfos() {
6686         return mActivityTaskManager.getAllStackInfos();
6687     }
6688 
6689     @Override
getTaskForActivity(IBinder token, boolean onlyRoot)6690     public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6691         return mActivityTaskManager.getTaskForActivity(token, onlyRoot);
6692     }
6693 
6694     @Override
updateDeviceOwner(String packageName)6695     public void updateDeviceOwner(String packageName) {
6696         final int callingUid = Binder.getCallingUid();
6697         if (callingUid != 0 && callingUid != SYSTEM_UID) {
6698             throw new SecurityException("updateDeviceOwner called from non-system process");
6699         }
6700         synchronized (this) {
6701             mDeviceOwnerName = packageName;
6702         }
6703     }
6704 
6705     @Override
updateLockTaskPackages(int userId, String[] packages)6706     public void updateLockTaskPackages(int userId, String[] packages) {
6707         mActivityTaskManager.updateLockTaskPackages(userId, packages);
6708     }
6709 
6710     @Override
isInLockTaskMode()6711     public boolean isInLockTaskMode() {
6712         return mActivityTaskManager.isInLockTaskMode();
6713     }
6714 
6715     @Override
getLockTaskModeState()6716     public int getLockTaskModeState() {
6717         return mActivityTaskManager.getLockTaskModeState();
6718     }
6719 
6720     @Override
startSystemLockTaskMode(int taskId)6721     public void startSystemLockTaskMode(int taskId) throws RemoteException {
6722         mActivityTaskManager.startSystemLockTaskMode(taskId);
6723     }
6724 
6725     // =========================================================
6726     // CONTENT PROVIDERS
6727     // =========================================================
6728 
generateApplicationProvidersLocked(ProcessRecord app)6729     private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6730         List<ProviderInfo> providers = null;
6731         try {
6732             providers = AppGlobals.getPackageManager()
6733                     .queryContentProviders(app.processName, app.uid,
6734                             STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6735                                     | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
6736                     .getList();
6737         } catch (RemoteException ex) {
6738         }
6739         if (DEBUG_MU) Slog.v(TAG_MU,
6740                 "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6741         int userId = app.userId;
6742         if (providers != null) {
6743             int N = providers.size();
6744             app.pubProviders.ensureCapacity(N + app.pubProviders.size());
6745             for (int i=0; i<N; i++) {
6746                 // TODO: keep logic in sync with installEncryptionUnawareProviders
6747                 ProviderInfo cpi =
6748                     (ProviderInfo)providers.get(i);
6749                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6750                         cpi.name, cpi.flags);
6751                 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) {
6752                     // This is a singleton provider, but a user besides the
6753                     // default user is asking to initialize a process it runs
6754                     // in...  well, no, it doesn't actually run in this process,
6755                     // it runs in the process of the default user.  Get rid of it.
6756                     providers.remove(i);
6757                     N--;
6758                     i--;
6759                     continue;
6760                 }
6761 
6762                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
6763                 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
6764                 if (cpr == null) {
6765                     cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
6766                     mProviderMap.putProviderByClass(comp, cpr);
6767                 }
6768                 if (DEBUG_MU) Slog.v(TAG_MU,
6769                         "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
6770                 app.pubProviders.put(cpi.name, cpr);
6771                 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
6772                     // Don't add this if it is a platform component that is marked
6773                     // to run in multiple processes, because this is actually
6774                     // part of the framework so doesn't make sense to track as a
6775                     // separate apk in the process.
6776                     app.addPackage(cpi.applicationInfo.packageName,
6777                             cpi.applicationInfo.longVersionCode, mProcessStats);
6778                 }
6779                 notifyPackageUse(cpi.applicationInfo.packageName,
6780                                  PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
6781             }
6782         }
6783         return providers;
6784     }
6785 
6786     /**
6787      * Check if the calling UID has a possible chance at accessing the provider
6788      * at the given authority and user.
6789      */
checkContentProviderAccess(String authority, int userId)6790     public String checkContentProviderAccess(String authority, int userId) {
6791         if (userId == UserHandle.USER_ALL) {
6792             mContext.enforceCallingOrSelfPermission(
6793                     Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
6794             userId = UserHandle.getCallingUserId();
6795         }
6796 
6797         ProviderInfo cpi = null;
6798         try {
6799             cpi = AppGlobals.getPackageManager().resolveContentProvider(authority,
6800                     STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6801                             | PackageManager.MATCH_DISABLED_COMPONENTS
6802                             | PackageManager.MATCH_DIRECT_BOOT_AWARE
6803                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
6804                     userId);
6805         } catch (RemoteException ignored) {
6806         }
6807         if (cpi == null) {
6808             return "Failed to find provider " + authority + " for user " + userId
6809                     + "; expected to find a valid ContentProvider for this authority";
6810         }
6811 
6812         ProcessRecord r = null;
6813         synchronized (mPidsSelfLocked) {
6814             r = mPidsSelfLocked.get(Binder.getCallingPid());
6815         }
6816         if (r == null) {
6817             return "Failed to find PID " + Binder.getCallingPid();
6818         }
6819 
6820         synchronized (this) {
6821             return checkContentProviderPermissionLocked(cpi, r, userId, true);
6822         }
6823     }
6824 
6825     /**
6826      * Check if {@link ProcessRecord} has a possible chance at accessing the
6827      * given {@link ProviderInfo}. Final permission checking is always done
6828      * in {@link ContentProvider}.
6829      */
checkContentProviderPermissionLocked( ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser)6830     private final String checkContentProviderPermissionLocked(
6831             ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) {
6832         final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
6833         final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
6834         boolean checkedGrants = false;
6835         if (checkUser) {
6836             // Looking for cross-user grants before enforcing the typical cross-users permissions
6837             int tmpTargetUserId = mUserController.unsafeConvertIncomingUser(userId);
6838             if (tmpTargetUserId != UserHandle.getUserId(callingUid)) {
6839                 if (mUgmInternal.checkAuthorityGrants(
6840                         callingUid, cpi, tmpTargetUserId, checkUser)) {
6841                     return null;
6842                 }
6843                 checkedGrants = true;
6844             }
6845             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
6846                     ALLOW_NON_FULL, "checkContentProviderPermissionLocked " + cpi.authority, null);
6847             if (userId != tmpTargetUserId) {
6848                 // When we actually went to determine the final targer user ID, this ended
6849                 // up different than our initial check for the authority.  This is because
6850                 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to
6851                 // SELF.  So we need to re-check the grants again.
6852                 checkedGrants = false;
6853             }
6854         }
6855         if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
6856                 cpi.applicationInfo.uid, cpi.exported)
6857                 == PackageManager.PERMISSION_GRANTED) {
6858             return null;
6859         }
6860         if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
6861                 cpi.applicationInfo.uid, cpi.exported)
6862                 == PackageManager.PERMISSION_GRANTED) {
6863             return null;
6864         }
6865 
6866         PathPermission[] pps = cpi.pathPermissions;
6867         if (pps != null) {
6868             int i = pps.length;
6869             while (i > 0) {
6870                 i--;
6871                 PathPermission pp = pps[i];
6872                 String pprperm = pp.getReadPermission();
6873                 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid,
6874                         cpi.applicationInfo.uid, cpi.exported)
6875                         == PackageManager.PERMISSION_GRANTED) {
6876                     return null;
6877                 }
6878                 String ppwperm = pp.getWritePermission();
6879                 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid,
6880                         cpi.applicationInfo.uid, cpi.exported)
6881                         == PackageManager.PERMISSION_GRANTED) {
6882                     return null;
6883                 }
6884             }
6885         }
6886         if (!checkedGrants
6887                 && mUgmInternal.checkAuthorityGrants(callingUid, cpi, userId, checkUser)) {
6888             return null;
6889         }
6890 
6891         final String suffix;
6892         if (!cpi.exported) {
6893             suffix = " that is not exported from UID " + cpi.applicationInfo.uid;
6894         } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) {
6895             suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
6896         } else {
6897             suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission;
6898         }
6899         final String msg = "Permission Denial: opening provider " + cpi.name
6900                 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6901                 + ", uid=" + callingUid + ")" + suffix;
6902         Slog.w(TAG, msg);
6903         return msg;
6904     }
6905 
incProviderCountLocked(ProcessRecord r, final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, String callingPackage, String callingTag, boolean stable)6906     ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6907             final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid,
6908             String callingPackage, String callingTag, boolean stable) {
6909         if (r != null) {
6910             for (int i=0; i<r.conProviders.size(); i++) {
6911                 ContentProviderConnection conn = r.conProviders.get(i);
6912                 if (conn.provider == cpr) {
6913                     if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
6914                             "Adding provider requested by "
6915                             + r.processName + " from process "
6916                             + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6917                             + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6918                     if (stable) {
6919                         conn.stableCount++;
6920                         conn.numStableIncs++;
6921                     } else {
6922                         conn.unstableCount++;
6923                         conn.numUnstableIncs++;
6924                     }
6925                     return conn;
6926                 }
6927             }
6928             ContentProviderConnection conn = new ContentProviderConnection(cpr, r, callingPackage);
6929             conn.startAssociationIfNeeded();
6930             if (stable) {
6931                 conn.stableCount = 1;
6932                 conn.numStableIncs = 1;
6933             } else {
6934                 conn.unstableCount = 1;
6935                 conn.numUnstableIncs = 1;
6936             }
6937             cpr.connections.add(conn);
6938             r.conProviders.add(conn);
6939             startAssociationLocked(r.uid, r.processName, r.getCurProcState(),
6940                     cpr.uid, cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
6941             return conn;
6942         }
6943         cpr.addExternalProcessHandleLocked(externalProcessToken, callingUid, callingTag);
6944         return null;
6945     }
6946 
decProviderCountLocked(ContentProviderConnection conn, ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable)6947     boolean decProviderCountLocked(ContentProviderConnection conn,
6948             ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6949         if (conn != null) {
6950             cpr = conn.provider;
6951             if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
6952                     "Removing provider requested by "
6953                     + conn.client.processName + " from process "
6954                     + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6955                     + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6956             if (stable) {
6957                 conn.stableCount--;
6958             } else {
6959                 conn.unstableCount--;
6960             }
6961             if (conn.stableCount == 0 && conn.unstableCount == 0) {
6962                 conn.stopAssociation();
6963                 cpr.connections.remove(conn);
6964                 conn.client.conProviders.remove(conn);
6965                 if (conn.client.setProcState < PROCESS_STATE_LAST_ACTIVITY) {
6966                     // The client is more important than last activity -- note the time this
6967                     // is happening, so we keep the old provider process around a bit as last
6968                     // activity to avoid thrashing it.
6969                     if (cpr.proc != null) {
6970                         cpr.proc.lastProviderTime = SystemClock.uptimeMillis();
6971                     }
6972                 }
6973                 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid,
6974                         cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
6975                 return true;
6976             }
6977             return false;
6978         }
6979         cpr.removeExternalProcessHandleLocked(externalProcessToken);
6980         return false;
6981     }
6982 
checkTime(long startTime, String where)6983     void checkTime(long startTime, String where) {
6984         long now = SystemClock.uptimeMillis();
6985         if ((now-startTime) > 50) {
6986             // If we are taking more than 50ms, log about it.
6987             Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where);
6988         }
6989     }
6990 
6991     private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] {
6992             PROC_SPACE_TERM,
6993             PROC_SPACE_TERM|PROC_PARENS,
6994             PROC_SPACE_TERM|PROC_CHAR|PROC_OUT_LONG,        // 3: process state
6995     };
6996 
6997     private final long[] mProcessStateStatsLongs = new long[1];
6998 
isProcessAliveLocked(ProcessRecord proc)6999     boolean isProcessAliveLocked(ProcessRecord proc) {
7000         if (proc.pid <= 0) {
7001             if (DEBUG_OOM_ADJ) Slog.d(TAG, "Process hasn't started yet: " + proc);
7002             return false;
7003         }
7004         if (proc.procStatFile == null) {
7005             proc.procStatFile = "/proc/" + proc.pid + "/stat";
7006         }
7007         mProcessStateStatsLongs[0] = 0;
7008         if (!readProcFile(proc.procStatFile, PROCESS_STATE_STATS_FORMAT, null,
7009                 mProcessStateStatsLongs, null)) {
7010             if (DEBUG_OOM_ADJ) Slog.d(TAG, "UNABLE TO RETRIEVE STATE FOR " + proc.procStatFile);
7011             return false;
7012         }
7013         final long state = mProcessStateStatsLongs[0];
7014         if (DEBUG_OOM_ADJ) Slog.d(TAG, "RETRIEVED STATE FOR " + proc.procStatFile + ": "
7015                 + (char)state);
7016         if (state != 'Z' && state != 'X' && state != 'x' && state != 'K') {
7017             return Process.getUidForPid(proc.pid) == proc.uid;
7018         }
7019         return false;
7020     }
7021 
checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, ProviderInfo cpi)7022     private String checkContentProviderAssociation(ProcessRecord callingApp, int callingUid,
7023             ProviderInfo cpi) {
7024         if (callingApp == null) {
7025             return validateAssociationAllowedLocked(cpi.packageName, cpi.applicationInfo.uid,
7026                     null, callingUid) ? null : "<null>";
7027         }
7028         for (int i = callingApp.pkgList.size() - 1; i >= 0; i--) {
7029             if (!validateAssociationAllowedLocked(callingApp.pkgList.keyAt(i), callingApp.uid,
7030                     cpi.packageName, cpi.applicationInfo.uid)) {
7031                 return cpi.packageName;
7032             }
7033         }
7034         return null;
7035     }
7036 
getContentProviderImpl(IApplicationThread caller, String name, IBinder token, int callingUid, String callingPackage, String callingTag, boolean stable, int userId)7037     private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
7038             String name, IBinder token, int callingUid, String callingPackage, String callingTag,
7039             boolean stable, int userId) {
7040         ContentProviderRecord cpr;
7041         ContentProviderConnection conn = null;
7042         ProviderInfo cpi = null;
7043         boolean providerRunning = false;
7044 
7045         synchronized(this) {
7046             long startTime = SystemClock.uptimeMillis();
7047 
7048             ProcessRecord r = null;
7049             if (caller != null) {
7050                 r = getRecordForAppLocked(caller);
7051                 if (r == null) {
7052                     throw new SecurityException(
7053                             "Unable to find app for caller " + caller
7054                           + " (pid=" + Binder.getCallingPid()
7055                           + ") when getting content provider " + name);
7056                 }
7057             }
7058 
7059             boolean checkCrossUser = true;
7060 
7061             checkTime(startTime, "getContentProviderImpl: getProviderByName");
7062 
7063             // First check if this content provider has been published...
7064             cpr = mProviderMap.getProviderByName(name, userId);
7065             // If that didn't work, check if it exists for user 0 and then
7066             // verify that it's a singleton provider before using it.
7067             if (cpr == null && userId != UserHandle.USER_SYSTEM) {
7068                 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM);
7069                 if (cpr != null) {
7070                     cpi = cpr.info;
7071                     if (isSingleton(cpi.processName, cpi.applicationInfo,
7072                             cpi.name, cpi.flags)
7073                             && isValidSingletonCall(r == null ? callingUid : r.uid,
7074                                     cpi.applicationInfo.uid)) {
7075                         userId = UserHandle.USER_SYSTEM;
7076                         checkCrossUser = false;
7077                     } else {
7078                         cpr = null;
7079                         cpi = null;
7080                     }
7081                 }
7082             }
7083 
7084             ProcessRecord dyingProc = null;
7085             if (cpr != null && cpr.proc != null) {
7086                 providerRunning = !cpr.proc.killed;
7087 
7088                 // Note if killedByAm is also set, this means the provider process has just been
7089                 // killed by AM (in ProcessRecord.kill()), but appDiedLocked() hasn't been called
7090                 // yet. So we need to call appDiedLocked() here and let it clean up.
7091                 // (See the commit message on I2c4ba1e87c2d47f2013befff10c49b3dc337a9a7 to see
7092                 // how to test this case.)
7093                 if (cpr.proc.killed && cpr.proc.killedByAm) {
7094                     Slog.wtf(TAG, cpr.proc.toString() + " was killed by AM but isn't really dead");
7095                     // Now we are going to wait for the death before starting the new process.
7096                     dyingProc = cpr.proc;
7097                 }
7098             }
7099 
7100             if (providerRunning) {
7101                 cpi = cpr.info;
7102                 String msg;
7103 
7104                 if (r != null && cpr.canRunHere(r)) {
7105                     if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
7106                         throw new SecurityException("Content provider lookup "
7107                                 + cpr.name.flattenToShortString()
7108                                 + " failed: association not allowed with package " + msg);
7109                     }
7110                     checkTime(startTime,
7111                             "getContentProviderImpl: before checkContentProviderPermission");
7112                     if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
7113                             != null) {
7114                         throw new SecurityException(msg);
7115                     }
7116                     checkTime(startTime,
7117                             "getContentProviderImpl: after checkContentProviderPermission");
7118 
7119                     // This provider has been published or is in the process
7120                     // of being published...  but it is also allowed to run
7121                     // in the caller's process, so don't make a connection
7122                     // and just let the caller instantiate its own instance.
7123                     ContentProviderHolder holder = cpr.newHolder(null);
7124                     // don't give caller the provider object, it needs
7125                     // to make its own.
7126                     holder.provider = null;
7127                     return holder;
7128                 }
7129 
7130                 // Don't expose providers between normal apps and instant apps
7131                 try {
7132                     if (AppGlobals.getPackageManager()
7133                             .resolveContentProvider(name, 0 /*flags*/, userId) == null) {
7134                         return null;
7135                     }
7136                 } catch (RemoteException e) {
7137                 }
7138 
7139                 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
7140                     throw new SecurityException("Content provider lookup "
7141                             + cpr.name.flattenToShortString()
7142                             + " failed: association not allowed with package " + msg);
7143                 }
7144                 checkTime(startTime,
7145                         "getContentProviderImpl: before checkContentProviderPermission");
7146                 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
7147                         != null) {
7148                     throw new SecurityException(msg);
7149                 }
7150                 checkTime(startTime,
7151                         "getContentProviderImpl: after checkContentProviderPermission");
7152 
7153                 final long origId = Binder.clearCallingIdentity();
7154                 try {
7155                     checkTime(startTime, "getContentProviderImpl: incProviderCountLocked");
7156 
7157                     // Return the provider instance right away since it already exists.
7158                     conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage,
7159                             callingTag, stable);
7160                     if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
7161                         if (cpr.proc != null
7162                                 && r != null && r.setAdj <= ProcessList.PERCEPTIBLE_LOW_APP_ADJ) {
7163                             // If this is a perceptible app accessing the provider,
7164                             // make sure to count it as being accessed and thus
7165                             // back up on the LRU list.  This is good because
7166                             // content providers are often expensive to start.
7167                             checkTime(startTime, "getContentProviderImpl: before updateLruProcess");
7168                             mProcessList.updateLruProcessLocked(cpr.proc, false, null);
7169                             checkTime(startTime, "getContentProviderImpl: after updateLruProcess");
7170                         }
7171                     }
7172 
7173                     checkTime(startTime, "getContentProviderImpl: before updateOomAdj");
7174                     final int verifiedAdj = cpr.proc.verifiedAdj;
7175                     boolean success = updateOomAdjLocked(cpr.proc, true,
7176                             OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
7177                     // XXX things have changed so updateOomAdjLocked doesn't actually tell us
7178                     // if the process has been successfully adjusted.  So to reduce races with
7179                     // it, we will check whether the process still exists.  Note that this doesn't
7180                     // completely get rid of races with LMK killing the process, but should make
7181                     // them much smaller.
7182                     if (success && verifiedAdj != cpr.proc.setAdj
7183                             && !isProcessAliveLocked(cpr.proc)) {
7184                         success = false;
7185                     }
7186                     maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name);
7187                     checkTime(startTime, "getContentProviderImpl: after updateOomAdj");
7188                     if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success);
7189                     // NOTE: there is still a race here where a signal could be
7190                     // pending on the process even though we managed to update its
7191                     // adj level.  Not sure what to do about this, but at least
7192                     // the race is now smaller.
7193                     if (!success) {
7194                         // Uh oh...  it looks like the provider's process
7195                         // has been killed on us.  We need to wait for a new
7196                         // process to be started, and make sure its death
7197                         // doesn't kill our process.
7198                         Slog.wtf(TAG, "Existing provider " + cpr.name.flattenToShortString()
7199                                 + " is crashing; detaching " + r);
7200                         boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
7201                         if (!lastRef) {
7202                             // This wasn't the last ref our process had on
7203                             // the provider...  we will be killed during cleaning up, bail.
7204                             return null;
7205                         }
7206                         // We'll just start a new process to host the content provider
7207                         providerRunning = false;
7208                         conn = null;
7209                         dyingProc = cpr.proc;
7210                     } else {
7211                         cpr.proc.verifiedAdj = cpr.proc.setAdj;
7212                     }
7213                 } finally {
7214                     Binder.restoreCallingIdentity(origId);
7215                 }
7216             }
7217 
7218             if (!providerRunning) {
7219                 try {
7220                     checkTime(startTime, "getContentProviderImpl: before resolveContentProvider");
7221                     cpi = AppGlobals.getPackageManager().
7222                         resolveContentProvider(name,
7223                             STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
7224                     checkTime(startTime, "getContentProviderImpl: after resolveContentProvider");
7225                 } catch (RemoteException ex) {
7226                 }
7227                 if (cpi == null) {
7228                     return null;
7229                 }
7230                 // If the provider is a singleton AND
7231                 // (it's a call within the same user || the provider is a
7232                 // privileged app)
7233                 // Then allow connecting to the singleton provider
7234                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
7235                         cpi.name, cpi.flags)
7236                         && isValidSingletonCall(r == null ? callingUid : r.uid,
7237                                 cpi.applicationInfo.uid);
7238                 if (singleton) {
7239                     userId = UserHandle.USER_SYSTEM;
7240                 }
7241                 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
7242                 checkTime(startTime, "getContentProviderImpl: got app info for user");
7243 
7244                 String msg;
7245                 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
7246                     throw new SecurityException("Content provider lookup " + name
7247                             + " failed: association not allowed with package " + msg);
7248                 }
7249                 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
7250                 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton))
7251                         != null) {
7252                     throw new SecurityException(msg);
7253                 }
7254                 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
7255 
7256                 if (!mProcessesReady
7257                         && !cpi.processName.equals("system")) {
7258                     // If this content provider does not run in the system
7259                     // process, and the system is not yet ready to run other
7260                     // processes, then fail fast instead of hanging.
7261                     throw new IllegalArgumentException(
7262                             "Attempt to launch content provider before system ready");
7263                 }
7264 
7265                 // If system providers are not installed yet we aggressively crash to avoid
7266                 // creating multiple instance of these providers and then bad things happen!
7267                 if (!mSystemProvidersInstalled && cpi.applicationInfo.isSystemApp()
7268                         && "system".equals(cpi.processName)) {
7269                     throw new IllegalStateException("Cannot access system provider: '"
7270                             + cpi.authority + "' before system providers are installed!");
7271                 }
7272 
7273                 // Make sure that the user who owns this provider is running.  If not,
7274                 // we don't want to allow it to run.
7275                 if (!mUserController.isUserRunning(userId, 0)) {
7276                     Slog.w(TAG, "Unable to launch app "
7277                             + cpi.applicationInfo.packageName + "/"
7278                             + cpi.applicationInfo.uid + " for provider "
7279                             + name + ": user " + userId + " is stopped");
7280                     return null;
7281                 }
7282 
7283                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
7284                 checkTime(startTime, "getContentProviderImpl: before getProviderByClass");
7285                 cpr = mProviderMap.getProviderByClass(comp, userId);
7286                 checkTime(startTime, "getContentProviderImpl: after getProviderByClass");
7287                 boolean firstClass = cpr == null;
7288                 if (firstClass) {
7289                     final long ident = Binder.clearCallingIdentity();
7290 
7291                     // If permissions need a review before any of the app components can run,
7292                     // we return no provider and launch a review activity if the calling app
7293                     // is in the foreground.
7294                     if (!requestTargetProviderPermissionsReviewIfNeededLocked(cpi, r, userId)) {
7295                         return null;
7296                     }
7297 
7298                     try {
7299                         checkTime(startTime, "getContentProviderImpl: before getApplicationInfo");
7300                         ApplicationInfo ai =
7301                             AppGlobals.getPackageManager().
7302                                 getApplicationInfo(
7303                                         cpi.applicationInfo.packageName,
7304                                         STOCK_PM_FLAGS, userId);
7305                         checkTime(startTime, "getContentProviderImpl: after getApplicationInfo");
7306                         if (ai == null) {
7307                             Slog.w(TAG, "No package info for content provider "
7308                                     + cpi.name);
7309                             return null;
7310                         }
7311                         ai = getAppInfoForUser(ai, userId);
7312                         cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
7313                     } catch (RemoteException ex) {
7314                         // pm is in same process, this will never happen.
7315                     } finally {
7316                         Binder.restoreCallingIdentity(ident);
7317                     }
7318                 } else if (dyingProc == cpr.proc && dyingProc != null) {
7319                     // The old stable connection's client should be killed during proc cleaning up,
7320                     // so do not re-use the old ContentProviderRecord, otherwise the new clients
7321                     // could get killed unexpectedly.
7322                     cpr = new ContentProviderRecord(cpr);
7323                     // This is sort of "firstClass"
7324                     firstClass = true;
7325                 }
7326 
7327                 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord");
7328 
7329                 if (r != null && cpr.canRunHere(r)) {
7330                     // If this is a multiprocess provider, then just return its
7331                     // info and allow the caller to instantiate it.  Only do
7332                     // this if the provider is the same user as the caller's
7333                     // process, or can run as root (so can be in any process).
7334                     return cpr.newHolder(null);
7335                 }
7336 
7337                 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid "
7338                             + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): "
7339                             + cpr.info.name + " callers=" + Debug.getCallers(6));
7340 
7341                 // This is single process, and our app is now connecting to it.
7342                 // See if we are already in the process of launching this
7343                 // provider.
7344                 final int N = mLaunchingProviders.size();
7345                 int i;
7346                 for (i = 0; i < N; i++) {
7347                     if (mLaunchingProviders.get(i) == cpr) {
7348                         break;
7349                     }
7350                 }
7351 
7352                 // If the provider is not already being launched, then get it
7353                 // started.
7354                 if (i >= N) {
7355                     final long origId = Binder.clearCallingIdentity();
7356 
7357                     try {
7358                         // Content provider is now in use, its package can't be stopped.
7359                         try {
7360                             checkTime(startTime, "getContentProviderImpl: before set stopped state");
7361                             AppGlobals.getPackageManager().setPackageStoppedState(
7362                                     cpr.appInfo.packageName, false, userId);
7363                             checkTime(startTime, "getContentProviderImpl: after set stopped state");
7364                         } catch (RemoteException e) {
7365                         } catch (IllegalArgumentException e) {
7366                             Slog.w(TAG, "Failed trying to unstop package "
7367                                     + cpr.appInfo.packageName + ": " + e);
7368                         }
7369 
7370                         // Use existing process if already started
7371                         checkTime(startTime, "getContentProviderImpl: looking for process record");
7372                         ProcessRecord proc = getProcessRecordLocked(
7373                                 cpi.processName, cpr.appInfo.uid, false);
7374                         if (proc != null && proc.thread != null && !proc.killed) {
7375                             if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER,
7376                                     "Installing in existing process " + proc);
7377                             if (!proc.pubProviders.containsKey(cpi.name)) {
7378                                 checkTime(startTime, "getContentProviderImpl: scheduling install");
7379                                 proc.pubProviders.put(cpi.name, cpr);
7380                                 try {
7381                                     proc.thread.scheduleInstallProvider(cpi);
7382                                 } catch (RemoteException e) {
7383                                 }
7384                             }
7385                         } else {
7386                             checkTime(startTime, "getContentProviderImpl: before start process");
7387                             proc = startProcessLocked(cpi.processName,
7388                                     cpr.appInfo, false, 0,
7389                                     new HostingRecord("content provider",
7390                                         new ComponentName(cpi.applicationInfo.packageName,
7391                                                 cpi.name)),
7392                                     ZYGOTE_POLICY_FLAG_EMPTY, false, false, false);
7393                             checkTime(startTime, "getContentProviderImpl: after start process");
7394                             if (proc == null) {
7395                                 Slog.w(TAG, "Unable to launch app "
7396                                         + cpi.applicationInfo.packageName + "/"
7397                                         + cpi.applicationInfo.uid + " for provider "
7398                                         + name + ": process is bad");
7399                                 return null;
7400                             }
7401                         }
7402                         cpr.launchingApp = proc;
7403                         mLaunchingProviders.add(cpr);
7404                     } finally {
7405                         Binder.restoreCallingIdentity(origId);
7406                     }
7407                 }
7408 
7409                 checkTime(startTime, "getContentProviderImpl: updating data structures");
7410 
7411                 // Make sure the provider is published (the same provider class
7412                 // may be published under multiple names).
7413                 if (firstClass) {
7414                     mProviderMap.putProviderByClass(comp, cpr);
7415                 }
7416 
7417                 mProviderMap.putProviderByName(name, cpr);
7418                 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag,
7419                         stable);
7420                 if (conn != null) {
7421                     conn.waiting = true;
7422                 }
7423             }
7424             checkTime(startTime, "getContentProviderImpl: done!");
7425 
7426             grantImplicitAccess(userId, null /*intent*/, callingUid,
7427                     UserHandle.getAppId(cpi.applicationInfo.uid));
7428         }
7429 
7430         // Wait for the provider to be published...
7431         final long timeout =
7432                 SystemClock.uptimeMillis() + ContentResolver.CONTENT_PROVIDER_READY_TIMEOUT_MILLIS;
7433         boolean timedOut = false;
7434         synchronized (cpr) {
7435             while (cpr.provider == null) {
7436                 if (cpr.launchingApp == null) {
7437                     Slog.w(TAG, "Unable to launch app "
7438                             + cpi.applicationInfo.packageName + "/"
7439                             + cpi.applicationInfo.uid + " for provider "
7440                             + name + ": launching app became null");
7441                     EventLogTags.writeAmProviderLostProcess(
7442                             UserHandle.getUserId(cpi.applicationInfo.uid),
7443                             cpi.applicationInfo.packageName,
7444                             cpi.applicationInfo.uid, name);
7445                     return null;
7446                 }
7447                 try {
7448                     final long wait = Math.max(0L, timeout - SystemClock.uptimeMillis());
7449                     if (DEBUG_MU) Slog.v(TAG_MU,
7450                             "Waiting to start provider " + cpr
7451                             + " launchingApp=" + cpr.launchingApp + " for " + wait + " ms");
7452                     if (conn != null) {
7453                         conn.waiting = true;
7454                     }
7455                     cpr.wait(wait);
7456                     if (cpr.provider == null) {
7457                         timedOut = true;
7458                         break;
7459                     }
7460                 } catch (InterruptedException ex) {
7461                 } finally {
7462                     if (conn != null) {
7463                         conn.waiting = false;
7464                     }
7465                 }
7466             }
7467         }
7468         if (timedOut) {
7469             // Note we do it after releasing the lock.
7470             String callerName = "unknown";
7471             if (caller != null) {
7472                 synchronized (this) {
7473                     final ProcessRecord record = mProcessList.getLRURecordForAppLocked(caller);
7474                     if (record != null) {
7475                         callerName = record.processName;
7476                     }
7477                 }
7478             }
7479 
7480             Slog.wtf(TAG, "Timeout waiting for provider "
7481                     + cpi.applicationInfo.packageName + "/"
7482                     + cpi.applicationInfo.uid + " for provider "
7483                     + name
7484                     + " providerRunning=" + providerRunning
7485                     + " caller=" + callerName + "/" + Binder.getCallingUid());
7486             return null;
7487         }
7488 
7489         return cpr.newHolder(conn);
7490     }
7491 
7492     private static final class StartActivityRunnable implements Runnable {
7493         private final Context mContext;
7494         private final Intent mIntent;
7495         private final UserHandle mUserHandle;
7496 
StartActivityRunnable(Context context, Intent intent, UserHandle userHandle)7497         StartActivityRunnable(Context context, Intent intent, UserHandle userHandle) {
7498             this.mContext = context;
7499             this.mIntent = intent;
7500             this.mUserHandle = userHandle;
7501         }
7502 
7503         @Override
run()7504         public void run() {
7505             mContext.startActivityAsUser(mIntent, mUserHandle);
7506         }
7507     }
7508 
requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, ProcessRecord r, final int userId)7509     private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi,
7510             ProcessRecord r, final int userId) {
7511         if (getPackageManagerInternalLocked().isPermissionsReviewRequired(
7512                 cpi.packageName, userId)) {
7513 
7514             final boolean callerForeground = r == null || r.setSchedGroup
7515                     != ProcessList.SCHED_GROUP_BACKGROUND;
7516 
7517             // Show a permission review UI only for starting from a foreground app
7518             if (!callerForeground) {
7519                 Slog.w(TAG, "u" + userId + " Instantiating a provider in package"
7520                         + cpi.packageName + " requires a permissions review");
7521                 return false;
7522             }
7523 
7524             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
7525             intent.addFlags(FLAG_ACTIVITY_NEW_TASK
7526                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7527             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName);
7528 
7529             if (DEBUG_PERMISSIONS_REVIEW) {
7530                 Slog.i(TAG, "u" + userId + " Launching permission review "
7531                         + "for package " + cpi.packageName);
7532             }
7533 
7534             final UserHandle userHandle = new UserHandle(userId);
7535             mHandler.post(new StartActivityRunnable(mContext, intent, userHandle));
7536 
7537             return false;
7538         }
7539 
7540         return true;
7541     }
7542 
7543     /**
7544      * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The
7545      * PackageManager could be unavailable at construction time and therefore needs to be accessed
7546      * on demand.
7547      */
7548     @VisibleForTesting
getPackageManager()7549     public IPackageManager getPackageManager() {
7550         return AppGlobals.getPackageManager();
7551     }
7552 
7553     @VisibleForTesting
getPackageManagerInternalLocked()7554     public PackageManagerInternal getPackageManagerInternalLocked() {
7555         if (mPackageManagerInt == null) {
7556             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
7557         }
7558         return mPackageManagerInt;
7559     }
7560 
getPermissionManagerInternalLocked()7561     private PermissionManagerServiceInternal getPermissionManagerInternalLocked() {
7562         if (mPermissionManagerInt == null) {
7563             mPermissionManagerInt =
7564                     LocalServices.getService(PermissionManagerServiceInternal.class);
7565         }
7566         return mPermissionManagerInt;
7567     }
7568 
7569     @Override
getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)7570     public final ContentProviderHolder getContentProvider(
7571             IApplicationThread caller, String callingPackage, String name, int userId,
7572             boolean stable) {
7573         enforceNotIsolatedCaller("getContentProvider");
7574         if (caller == null) {
7575             String msg = "null IApplicationThread when getting content provider "
7576                     + name;
7577             Slog.w(TAG, msg);
7578             throw new SecurityException(msg);
7579         }
7580         // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal
7581         // with cross-user grant.
7582         final int callingUid = Binder.getCallingUid();
7583         if (callingPackage != null && mAppOpsService.checkPackage(callingUid, callingPackage)
7584                 != AppOpsManager.MODE_ALLOWED) {
7585             throw new SecurityException("Given calling package " + callingPackage
7586                     + " does not match caller's uid " + callingUid);
7587         }
7588         return getContentProviderImpl(caller, name, null, callingUid, callingPackage,
7589                 null, stable, userId);
7590     }
7591 
getContentProviderExternal( String name, int userId, IBinder token, String tag)7592     public ContentProviderHolder getContentProviderExternal(
7593             String name, int userId, IBinder token, String tag) {
7594         enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
7595             "Do not have permission in call getContentProviderExternal()");
7596         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7597                 userId, false, ALLOW_FULL_ONLY, "getContentProvider", null);
7598         return getContentProviderExternalUnchecked(name, token, Binder.getCallingUid(),
7599                 tag != null ? tag : "*external*", userId);
7600     }
7601 
getContentProviderExternalUnchecked(String name, IBinder token, int callingUid, String callingTag, int userId)7602     private ContentProviderHolder getContentProviderExternalUnchecked(String name,
7603             IBinder token, int callingUid, String callingTag, int userId) {
7604         return getContentProviderImpl(null, name, token, callingUid, null, callingTag,
7605                 true, userId);
7606     }
7607 
7608     /**
7609      * Drop a content provider from a ProcessRecord's bookkeeping
7610      */
removeContentProvider(IBinder connection, boolean stable)7611     public void removeContentProvider(IBinder connection, boolean stable) {
7612         enforceNotIsolatedCaller("removeContentProvider");
7613         long ident = Binder.clearCallingIdentity();
7614         try {
7615             synchronized (this) {
7616                 ContentProviderConnection conn;
7617                 try {
7618                     conn = (ContentProviderConnection)connection;
7619                 } catch (ClassCastException e) {
7620                     String msg ="removeContentProvider: " + connection
7621                             + " not a ContentProviderConnection";
7622                     Slog.w(TAG, msg);
7623                     throw new IllegalArgumentException(msg);
7624                 }
7625                 if (conn == null) {
7626                     throw new NullPointerException("connection is null");
7627                 }
7628                 if (decProviderCountLocked(conn, null, null, stable)) {
7629                     updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER);
7630                 }
7631             }
7632         } finally {
7633             Binder.restoreCallingIdentity(ident);
7634         }
7635     }
7636 
7637     /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */
7638     @Deprecated
7639     @Override
removeContentProviderExternal(String name, IBinder token)7640     public void removeContentProviderExternal(String name, IBinder token) {
7641         removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId());
7642     }
7643 
7644     @Override
removeContentProviderExternalAsUser(String name, IBinder token, int userId)7645     public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) {
7646         enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
7647             "Do not have permission in call removeContentProviderExternal()");
7648         long ident = Binder.clearCallingIdentity();
7649         try {
7650             removeContentProviderExternalUnchecked(name, token, userId);
7651         } finally {
7652             Binder.restoreCallingIdentity(ident);
7653         }
7654     }
7655 
removeContentProviderExternalUnchecked(String name, IBinder token, int userId)7656     private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
7657         synchronized (this) {
7658             ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
7659             if(cpr == null) {
7660                 //remove from mProvidersByClass
7661                 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list");
7662                 return;
7663             }
7664 
7665             //update content provider record entry info
7666             ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
7667             ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
7668             if (localCpr.hasExternalProcessHandles()) {
7669                 if (localCpr.removeExternalProcessHandleLocked(token)) {
7670                     updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER);
7671                 } else {
7672                     Slog.e(TAG, "Attmpt to remove content provider " + localCpr
7673                             + " with no external reference for token: "
7674                             + token + ".");
7675                 }
7676             } else {
7677                 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
7678                         + " with no external references.");
7679             }
7680         }
7681     }
7682 
publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)7683     public final void publishContentProviders(IApplicationThread caller,
7684             List<ContentProviderHolder> providers) {
7685         if (providers == null) {
7686             return;
7687         }
7688 
7689         enforceNotIsolatedCaller("publishContentProviders");
7690         synchronized (this) {
7691             final ProcessRecord r = getRecordForAppLocked(caller);
7692             if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
7693             if (r == null) {
7694                 throw new SecurityException(
7695                         "Unable to find app for caller " + caller
7696                       + " (pid=" + Binder.getCallingPid()
7697                       + ") when publishing content providers");
7698             }
7699 
7700             final long origId = Binder.clearCallingIdentity();
7701 
7702             final int N = providers.size();
7703             for (int i = 0; i < N; i++) {
7704                 ContentProviderHolder src = providers.get(i);
7705                 if (src == null || src.info == null || src.provider == null) {
7706                     continue;
7707                 }
7708                 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
7709                 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
7710                 if (dst != null) {
7711                     ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
7712                     mProviderMap.putProviderByClass(comp, dst);
7713                     String names[] = dst.info.authority.split(";");
7714                     for (int j = 0; j < names.length; j++) {
7715                         mProviderMap.putProviderByName(names[j], dst);
7716                     }
7717 
7718                     int launchingCount = mLaunchingProviders.size();
7719                     int j;
7720                     boolean wasInLaunchingProviders = false;
7721                     for (j = 0; j < launchingCount; j++) {
7722                         if (mLaunchingProviders.get(j) == dst) {
7723                             mLaunchingProviders.remove(j);
7724                             wasInLaunchingProviders = true;
7725                             j--;
7726                             launchingCount--;
7727                         }
7728                     }
7729                     if (wasInLaunchingProviders) {
7730                         mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
7731                     }
7732                     // Make sure the package is associated with the process.
7733                     // XXX We shouldn't need to do this, since we have added the package
7734                     // when we generated the providers in generateApplicationProvidersLocked().
7735                     // But for some reason in some cases we get here with the package no longer
7736                     // added...  for now just patch it in to make things happy.
7737                     r.addPackage(dst.info.applicationInfo.packageName,
7738                             dst.info.applicationInfo.longVersionCode, mProcessStats);
7739                     synchronized (dst) {
7740                         dst.provider = src.provider;
7741                         dst.setProcess(r);
7742                         dst.notifyAll();
7743                     }
7744                     dst.mRestartCount = 0;
7745                     updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
7746                     maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
7747                             src.info.authority);
7748                 }
7749             }
7750 
7751             Binder.restoreCallingIdentity(origId);
7752         }
7753     }
7754 
refContentProvider(IBinder connection, int stable, int unstable)7755     public boolean refContentProvider(IBinder connection, int stable, int unstable) {
7756         ContentProviderConnection conn;
7757         try {
7758             conn = (ContentProviderConnection)connection;
7759         } catch (ClassCastException e) {
7760             String msg ="refContentProvider: " + connection
7761                     + " not a ContentProviderConnection";
7762             Slog.w(TAG, msg);
7763             throw new IllegalArgumentException(msg);
7764         }
7765         if (conn == null) {
7766             throw new NullPointerException("connection is null");
7767         }
7768 
7769         synchronized (this) {
7770             if (stable > 0) {
7771                 conn.numStableIncs += stable;
7772             }
7773             stable = conn.stableCount + stable;
7774             if (stable < 0) {
7775                 throw new IllegalStateException("stableCount < 0: " + stable);
7776             }
7777 
7778             if (unstable > 0) {
7779                 conn.numUnstableIncs += unstable;
7780             }
7781             unstable = conn.unstableCount + unstable;
7782             if (unstable < 0) {
7783                 throw new IllegalStateException("unstableCount < 0: " + unstable);
7784             }
7785 
7786             if ((stable+unstable) <= 0) {
7787                 throw new IllegalStateException("ref counts can't go to zero here: stable="
7788                         + stable + " unstable=" + unstable);
7789             }
7790             conn.stableCount = stable;
7791             conn.unstableCount = unstable;
7792             return !conn.dead;
7793         }
7794     }
7795 
unstableProviderDied(IBinder connection)7796     public void unstableProviderDied(IBinder connection) {
7797         ContentProviderConnection conn;
7798         try {
7799             conn = (ContentProviderConnection)connection;
7800         } catch (ClassCastException e) {
7801             String msg ="refContentProvider: " + connection
7802                     + " not a ContentProviderConnection";
7803             Slog.w(TAG, msg);
7804             throw new IllegalArgumentException(msg);
7805         }
7806         if (conn == null) {
7807             throw new NullPointerException("connection is null");
7808         }
7809 
7810         // Safely retrieve the content provider associated with the connection.
7811         IContentProvider provider;
7812         synchronized (this) {
7813             provider = conn.provider.provider;
7814         }
7815 
7816         if (provider == null) {
7817             // Um, yeah, we're way ahead of you.
7818             return;
7819         }
7820 
7821         // Make sure the caller is being honest with us.
7822         if (provider.asBinder().pingBinder()) {
7823             // Er, no, still looks good to us.
7824             synchronized (this) {
7825                 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
7826                         + " says " + conn + " died, but we don't agree");
7827                 return;
7828             }
7829         }
7830 
7831         // Well look at that!  It's dead!
7832         synchronized (this) {
7833             if (conn.provider.provider != provider) {
7834                 // But something changed...  good enough.
7835                 return;
7836             }
7837 
7838             ProcessRecord proc = conn.provider.proc;
7839             if (proc == null || proc.thread == null) {
7840                 // Seems like the process is already cleaned up.
7841                 return;
7842             }
7843 
7844             // As far as we're concerned, this is just like receiving a
7845             // death notification...  just a bit prematurely.
7846             reportUidInfoMessageLocked(TAG,
7847                     "Process " + proc.processName + " (pid " + proc.pid
7848                             + ") early provider death",
7849                     proc.info.uid);
7850             final long ident = Binder.clearCallingIdentity();
7851             try {
7852                 appDiedLocked(proc, "unstable content provider");
7853             } finally {
7854                 Binder.restoreCallingIdentity(ident);
7855             }
7856         }
7857     }
7858 
7859     @Override
appNotRespondingViaProvider(IBinder connection)7860     public void appNotRespondingViaProvider(IBinder connection) {
7861         enforceCallingPermission(REMOVE_TASKS, "appNotRespondingViaProvider()");
7862 
7863         final ContentProviderConnection conn = (ContentProviderConnection) connection;
7864         if (conn == null) {
7865             Slog.w(TAG, "ContentProviderConnection is null");
7866             return;
7867         }
7868 
7869         final ProcessRecord host = conn.provider.proc;
7870         if (host == null) {
7871             Slog.w(TAG, "Failed to find hosting ProcessRecord");
7872             return;
7873         }
7874 
7875         mAnrHelper.appNotResponding(host, "ContentProvider not responding");
7876     }
7877 
7878     @Override
appNotResponding(final String reason)7879     public void appNotResponding(final String reason) {
7880         final int callingPid = Binder.getCallingPid();
7881 
7882         synchronized (mPidsSelfLocked) {
7883             final ProcessRecord app = mPidsSelfLocked.get(callingPid);
7884             if (app == null) {
7885                 throw new SecurityException("Unknown process: " + callingPid);
7886             }
7887 
7888             mAnrHelper.appNotResponding(app, null, app.info, null, null, false,
7889                     "App requested: " + reason);
7890         }
7891     }
7892 
installSystemProviders()7893     public final void installSystemProviders() {
7894         List<ProviderInfo> providers;
7895         synchronized (this) {
7896             ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
7897             providers = generateApplicationProvidersLocked(app);
7898             if (providers != null) {
7899                 for (int i=providers.size()-1; i>=0; i--) {
7900                     ProviderInfo pi = (ProviderInfo)providers.get(i);
7901                     if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7902                         Slog.w(TAG, "Not installing system proc provider " + pi.name
7903                                 + ": not system .apk");
7904                         providers.remove(i);
7905                     }
7906                 }
7907             }
7908         }
7909         if (providers != null) {
7910             mSystemThread.installSystemProviders(providers);
7911         }
7912 
7913         synchronized (this) {
7914             mSystemProvidersInstalled = true;
7915         }
7916         mConstants.start(mContext.getContentResolver());
7917         mCoreSettingsObserver = new CoreSettingsObserver(this);
7918         mActivityTaskManager.installSystemProviders();
7919         mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
7920         SettingsToPropertiesMapper.start(mContext.getContentResolver());
7921         mOomAdjuster.initSettings();
7922 
7923         // Now that the settings provider is published we can consider sending
7924         // in a rescue party.
7925         RescueParty.onSettingsProviderPublished(mContext);
7926 
7927         //mUsageStatsService.monitorPackages();
7928     }
7929 
startPersistentApps(int matchFlags)7930     void startPersistentApps(int matchFlags) {
7931         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
7932 
7933         synchronized (this) {
7934             try {
7935                 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
7936                         .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
7937                 for (ApplicationInfo app : apps) {
7938                     if (!"android".equals(app.packageName)) {
7939                         addAppLocked(app, null, false, null /* ABI override */,
7940                                 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
7941                     }
7942                 }
7943             } catch (RemoteException ex) {
7944             }
7945         }
7946     }
7947 
7948     /**
7949      * When a user is unlocked, we need to install encryption-unaware providers
7950      * belonging to any running apps.
7951      */
installEncryptionUnawareProviders(int userId)7952     void installEncryptionUnawareProviders(int userId) {
7953         // We're only interested in providers that are encryption unaware, and
7954         // we don't care about uninstalled apps, since there's no way they're
7955         // running at this point.
7956         final int matchFlags = GET_PROVIDERS | MATCH_DIRECT_BOOT_UNAWARE;
7957 
7958         synchronized (this) {
7959             final int NP = mProcessList.mProcessNames.getMap().size();
7960             for (int ip = 0; ip < NP; ip++) {
7961                 final SparseArray<ProcessRecord> apps = mProcessList.mProcessNames.getMap().valueAt
7962                         (ip);
7963                 final int NA = apps.size();
7964                 for (int ia = 0; ia < NA; ia++) {
7965                     final ProcessRecord app = apps.valueAt(ia);
7966                     if (app.userId != userId || app.thread == null || app.unlocked) continue;
7967 
7968                     final int NG = app.pkgList.size();
7969                     for (int ig = 0; ig < NG; ig++) {
7970                         try {
7971                             final String pkgName = app.pkgList.keyAt(ig);
7972                             final PackageInfo pkgInfo = AppGlobals.getPackageManager()
7973                                     .getPackageInfo(pkgName, matchFlags, userId);
7974                             if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) {
7975                                 for (ProviderInfo pi : pkgInfo.providers) {
7976                                     // TODO: keep in sync with generateApplicationProvidersLocked
7977                                     final boolean processMatch = Objects.equals(pi.processName,
7978                                             app.processName) || pi.multiprocess;
7979                                     final boolean userMatch = isSingleton(pi.processName,
7980                                             pi.applicationInfo, pi.name, pi.flags)
7981                                                     ? (app.userId == UserHandle.USER_SYSTEM) : true;
7982                                     if (processMatch && userMatch) {
7983                                         Log.v(TAG, "Installing " + pi);
7984                                         app.thread.scheduleInstallProvider(pi);
7985                                     } else {
7986                                         Log.v(TAG, "Skipping " + pi);
7987                                     }
7988                                 }
7989                             }
7990                         } catch (RemoteException ignored) {
7991                         }
7992                     }
7993                 }
7994             }
7995         }
7996     }
7997 
7998     /**
7999      * Allows apps to retrieve the MIME type of a URI.
8000      * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
8001      * users, then it does not need permission to access the ContentProvider.
8002      * Either, it needs cross-user uri grants.
8003      *
8004      * CTS tests for this functionality can be run with "runtest cts-appsecurity".
8005      *
8006      * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
8007      *     src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
8008      *
8009      * @deprecated -- use getProviderMimeTypeAsync.
8010      */
8011     @Deprecated
getProviderMimeType(Uri uri, int userId)8012     public String getProviderMimeType(Uri uri, int userId) {
8013         enforceNotIsolatedCaller("getProviderMimeType");
8014         final String name = uri.getAuthority();
8015         int callingUid = Binder.getCallingUid();
8016         int callingPid = Binder.getCallingPid();
8017         long ident = 0;
8018         boolean clearedIdentity = false;
8019         userId = mUserController.unsafeConvertIncomingUser(userId);
8020         if (canClearIdentity(callingPid, callingUid, userId)) {
8021             clearedIdentity = true;
8022             ident = Binder.clearCallingIdentity();
8023         }
8024         ContentProviderHolder holder = null;
8025         try {
8026             holder = getContentProviderExternalUnchecked(name, null, callingUid,
8027                     "*getmimetype*", userId);
8028             if (holder != null) {
8029                 final IBinder providerConnection = holder.connection;
8030                 final ComponentName providerName = holder.info.getComponentName();
8031                 // Note: creating a new Runnable instead of using a lambda here since lambdas in
8032                 // java provide no guarantee that there will be a new instance returned every call.
8033                 // Hence, it's possible that a cached copy is returned and the ANR is executed on
8034                 // the incorrect provider.
8035                 final Runnable providerNotResponding = new Runnable() {
8036                     @Override
8037                     public void run() {
8038                         Log.w(TAG, "Provider " + providerName + " didn't return from getType().");
8039                         appNotRespondingViaProvider(providerConnection);
8040                     }
8041                 };
8042                 mHandler.postDelayed(providerNotResponding, 1000);
8043                 try {
8044                     return holder.provider.getType(uri);
8045                 } finally {
8046                     mHandler.removeCallbacks(providerNotResponding);
8047                 }
8048             }
8049         } catch (RemoteException e) {
8050             Log.w(TAG, "Content provider dead retrieving " + uri, e);
8051             return null;
8052         } catch (Exception e) {
8053             Log.w(TAG, "Exception while determining type of " + uri, e);
8054             return null;
8055         } finally {
8056             // We need to clear the identity to call removeContentProviderExternalUnchecked
8057             if (!clearedIdentity) {
8058                 ident = Binder.clearCallingIdentity();
8059             }
8060             try {
8061                 if (holder != null) {
8062                     removeContentProviderExternalUnchecked(name, null, userId);
8063                 }
8064             } finally {
8065                 Binder.restoreCallingIdentity(ident);
8066             }
8067         }
8068 
8069         return null;
8070     }
8071 
8072     /**
8073      * Allows apps to retrieve the MIME type of a URI.
8074      * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
8075      * users, then it does not need permission to access the ContentProvider.
8076      * Either way, it needs cross-user uri grants.
8077      */
8078     @Override
getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback)8079     public void getProviderMimeTypeAsync(Uri uri, int userId, RemoteCallback resultCallback) {
8080         enforceNotIsolatedCaller("getProviderMimeTypeAsync");
8081         final String name = uri.getAuthority();
8082         final int callingUid = Binder.getCallingUid();
8083         final int callingPid = Binder.getCallingPid();
8084         final int safeUserId = mUserController.unsafeConvertIncomingUser(userId);
8085         final long ident = canClearIdentity(callingPid, callingUid, userId)
8086                 ? Binder.clearCallingIdentity() : 0;
8087         try {
8088             final ContentProviderHolder holder = getContentProviderExternalUnchecked(name, null,
8089                     callingUid, "*getmimetype*", safeUserId);
8090             if (holder != null) {
8091                 holder.provider.getTypeAsync(uri, new RemoteCallback(result -> {
8092                     final long identity = Binder.clearCallingIdentity();
8093                     try {
8094                         removeContentProviderExternalUnchecked(name, null, safeUserId);
8095                     } finally {
8096                         Binder.restoreCallingIdentity(identity);
8097                     }
8098                     resultCallback.sendResult(result);
8099                 }));
8100             } else {
8101                 resultCallback.sendResult(Bundle.EMPTY);
8102             }
8103         } catch (RemoteException e) {
8104             Log.w(TAG, "Content provider dead retrieving " + uri, e);
8105             resultCallback.sendResult(Bundle.EMPTY);
8106         } finally {
8107             Binder.restoreCallingIdentity(ident);
8108         }
8109     }
8110 
checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)8111     int checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags) {
8112         if (Thread.holdsLock(mActivityTaskManager.getGlobalLock())) {
8113             Slog.wtf(TAG, new IllegalStateException("Unable to check Uri permission"
8114                     + " because caller is holding WM lock; assuming permission denied"));
8115             return PackageManager.PERMISSION_DENIED;
8116         }
8117 
8118         final String name = uri.getAuthority();
8119         final long ident = Binder.clearCallingIdentity();
8120         ContentProviderHolder holder = null;
8121         try {
8122             holder = getContentProviderExternalUnchecked(name, null, callingUid,
8123                     "*checkContentProviderUriPermission*", userId);
8124             if (holder != null) {
8125                 return holder.provider.checkUriPermission(null, null, uri, callingUid, modeFlags);
8126             }
8127         } catch (RemoteException e) {
8128             Log.w(TAG, "Content provider dead retrieving " + uri, e);
8129             return PackageManager.PERMISSION_DENIED;
8130         } catch (Exception e) {
8131             Log.w(TAG, "Exception while determining type of " + uri, e);
8132             return PackageManager.PERMISSION_DENIED;
8133         } finally {
8134             try {
8135                 if (holder != null) {
8136                     removeContentProviderExternalUnchecked(name, null, userId);
8137                 }
8138             } finally {
8139                 Binder.restoreCallingIdentity(ident);
8140             }
8141         }
8142         return PackageManager.PERMISSION_DENIED;
8143     }
8144 
canClearIdentity(int callingPid, int callingUid, int userId)8145     private boolean canClearIdentity(int callingPid, int callingUid, int userId) {
8146         if (UserHandle.getUserId(callingUid) == userId) {
8147             return true;
8148         }
8149         if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
8150                 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
8151                 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
8152                 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
8153                 return true;
8154         }
8155         return false;
8156     }
8157 
8158     // =========================================================
8159     // GLOBAL MANAGEMENT
8160     // =========================================================
8161 
uidOnBackgroundWhitelist(final int uid)8162     private boolean uidOnBackgroundWhitelist(final int uid) {
8163         final int appId = UserHandle.getAppId(uid);
8164         final int[] whitelist = mBackgroundAppIdWhitelist;
8165         final int N = whitelist.length;
8166         for (int i = 0; i < N; i++) {
8167             if (appId == whitelist[i]) {
8168                 return true;
8169             }
8170         }
8171         return false;
8172     }
8173 
8174     @Override
isBackgroundRestricted(String packageName)8175     public boolean isBackgroundRestricted(String packageName) {
8176         final int callingUid = Binder.getCallingUid();
8177         final IPackageManager pm = AppGlobals.getPackageManager();
8178         try {
8179             final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
8180                     UserHandle.getUserId(callingUid));
8181             if (packageUid != callingUid) {
8182                 throw new IllegalArgumentException("Uid " + callingUid
8183                         + " cannot query restriction state for package " + packageName);
8184             }
8185         } catch (RemoteException exc) {
8186             // Ignore.
8187         }
8188         return isBackgroundRestrictedNoCheck(callingUid, packageName);
8189     }
8190 
isBackgroundRestrictedNoCheck(final int uid, final String packageName)8191     boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) {
8192         final int mode = getAppOpsManager().checkOpNoThrow(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
8193                 uid, packageName);
8194         return mode != AppOpsManager.MODE_ALLOWED;
8195     }
8196 
8197     @Override
backgroundWhitelistUid(final int uid)8198     public void backgroundWhitelistUid(final int uid) {
8199         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
8200             throw new SecurityException("Only the OS may call backgroundWhitelistUid()");
8201         }
8202 
8203         if (DEBUG_BACKGROUND_CHECK) {
8204             Slog.i(TAG, "Adding uid " + uid + " to bg uid whitelist");
8205         }
8206         synchronized (this) {
8207             final int N = mBackgroundAppIdWhitelist.length;
8208             int[] newList = new int[N+1];
8209             System.arraycopy(mBackgroundAppIdWhitelist, 0, newList, 0, N);
8210             newList[N] = UserHandle.getAppId(uid);
8211             mBackgroundAppIdWhitelist = newList;
8212         }
8213     }
8214 
8215     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)8216     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
8217             String abiOverride, int zygotePolicyFlags) {
8218         return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */,
8219                 false /* mountExtStorageFull */, abiOverride, zygotePolicyFlags);
8220     }
8221 
8222     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride, int zygotePolicyFlags)8223     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
8224             boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride,
8225             int zygotePolicyFlags) {
8226         return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks,
8227                 false /* disableTestApiChecks */, mountExtStorageFull, abiOverride,
8228                 zygotePolicyFlags);
8229     }
8230 
8231     // TODO: Move to ProcessList?
8232     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, boolean mountExtStorageFull, String abiOverride, int zygotePolicyFlags)8233     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
8234             boolean disableHiddenApiChecks, boolean disableTestApiChecks,
8235             boolean mountExtStorageFull, String abiOverride, int zygotePolicyFlags) {
8236         ProcessRecord app;
8237         if (!isolated) {
8238             app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
8239                     info.uid, true);
8240         } else {
8241             app = null;
8242         }
8243 
8244         if (app == null) {
8245             app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0,
8246                     new HostingRecord("added application",
8247                             customProcess != null ? customProcess : info.processName));
8248             mProcessList.updateLruProcessLocked(app, false, null);
8249             updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
8250         }
8251 
8252         // This package really, really can not be stopped.
8253         try {
8254             AppGlobals.getPackageManager().setPackageStoppedState(
8255                     info.packageName, false, UserHandle.getUserId(app.uid));
8256         } catch (RemoteException e) {
8257         } catch (IllegalArgumentException e) {
8258             Slog.w(TAG, "Failed trying to unstop package "
8259                     + info.packageName + ": " + e);
8260         }
8261 
8262         if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
8263             app.setPersistent(true);
8264             app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
8265         }
8266         if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
8267             mPersistentStartingProcesses.add(app);
8268             mProcessList.startProcessLocked(app, new HostingRecord("added application",
8269                     customProcess != null ? customProcess : app.processName),
8270                     zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks,
8271                     mountExtStorageFull, abiOverride);
8272         }
8273 
8274         return app;
8275     }
8276 
unhandledBack()8277     public void unhandledBack() {
8278         mActivityTaskManager.unhandledBack();
8279     }
8280 
openContentUri(String uriString)8281     public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
8282         enforceNotIsolatedCaller("openContentUri");
8283         final int userId = UserHandle.getCallingUserId();
8284         final Uri uri = Uri.parse(uriString);
8285         String name = uri.getAuthority();
8286         ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null,
8287                 Binder.getCallingUid(), "*opencontent*", userId);
8288         ParcelFileDescriptor pfd = null;
8289         if (cph != null) {
8290             // We record the binder invoker's uid in thread-local storage before
8291             // going to the content provider to open the file.  Later, in the code
8292             // that handles all permissions checks, we look for this uid and use
8293             // that rather than the Activity Manager's own uid.  The effect is that
8294             // we do the check against the caller's permissions even though it looks
8295             // to the content provider like the Activity Manager itself is making
8296             // the request.
8297             Binder token = new Binder();
8298             sCallerIdentity.set(new Identity(
8299                     token, Binder.getCallingPid(), Binder.getCallingUid()));
8300             try {
8301                 pfd = cph.provider.openFile(null, null, uri, "r", null, token);
8302             } catch (FileNotFoundException e) {
8303                 // do nothing; pfd will be returned null
8304             } finally {
8305                 // Ensure that whatever happens, we clean up the identity state
8306                 sCallerIdentity.remove();
8307                 // Ensure we're done with the provider.
8308                 removeContentProviderExternalUnchecked(name, null, userId);
8309             }
8310         } else {
8311             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
8312         }
8313         return pfd;
8314     }
8315 
reportGlobalUsageEventLocked(int event)8316     void reportGlobalUsageEventLocked(int event) {
8317         final int currentUserId = mUserController.getCurrentUserId();
8318         mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, currentUserId, event);
8319         int[] profiles = mUserController.getCurrentProfileIds();
8320         if (profiles != null) {
8321             for (int i = profiles.length - 1; i >= 0; i--) {
8322                 if (profiles[i] == currentUserId) {
8323                     continue;
8324                 }
8325                 mUsageStatsService.reportEvent(Event.DEVICE_EVENT_PACKAGE_NAME, profiles[i], event);
8326             }
8327         }
8328     }
8329 
reportCurWakefulnessUsageEventLocked()8330     void reportCurWakefulnessUsageEventLocked() {
8331         reportGlobalUsageEventLocked(mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE
8332                 ? UsageEvents.Event.SCREEN_INTERACTIVE
8333                 : UsageEvents.Event.SCREEN_NON_INTERACTIVE);
8334     }
8335 
onWakefulnessChanged(int wakefulness)8336     void onWakefulnessChanged(int wakefulness) {
8337         synchronized(this) {
8338             boolean wasAwake = mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
8339             boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
8340             mWakefulness = wakefulness;
8341 
8342             if (wasAwake != isAwake) {
8343                 // Also update state in a special way for running foreground services UI.
8344                 mServices.updateScreenStateLocked(isAwake);
8345                 reportCurWakefulnessUsageEventLocked();
8346                 mActivityTaskManager.onScreenAwakeChanged(isAwake);
8347                 mOomAdjProfiler.onWakefulnessChanged(wakefulness);
8348             }
8349             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
8350         }
8351     }
8352 
8353     @Override
notifyCleartextNetwork(int uid, byte[] firstPacket)8354     public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
8355         mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
8356     }
8357 
8358     @Override
shutdown(int timeout)8359     public boolean shutdown(int timeout) {
8360         if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
8361                 != PackageManager.PERMISSION_GRANTED) {
8362             throw new SecurityException("Requires permission "
8363                     + android.Manifest.permission.SHUTDOWN);
8364         }
8365 
8366         final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout);
8367 
8368         mAppOpsService.shutdown();
8369         if (mUsageStatsService != null) {
8370             mUsageStatsService.prepareShutdown();
8371         }
8372         mBatteryStatsService.shutdown();
8373         synchronized (this) {
8374             mProcessStats.shutdownLocked();
8375         }
8376 
8377         return timedout;
8378     }
8379 
8380     @Override
notifyLockedProfile(@serIdInt int userId)8381     public void notifyLockedProfile(@UserIdInt int userId) {
8382         mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId());
8383     }
8384 
8385     @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)8386     public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
8387         mAtmInternal.startConfirmDeviceCredentialIntent(intent, options);
8388     }
8389 
8390     @Override
stopAppSwitches()8391     public void stopAppSwitches() {
8392         mActivityTaskManager.stopAppSwitches();
8393     }
8394 
8395     @Override
resumeAppSwitches()8396     public void resumeAppSwitches() {
8397         mActivityTaskManager.resumeAppSwitches();
8398     }
8399 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)8400     public void setDebugApp(String packageName, boolean waitForDebugger,
8401             boolean persistent) {
8402         enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
8403                 "setDebugApp()");
8404 
8405         long ident = Binder.clearCallingIdentity();
8406         try {
8407             // Note that this is not really thread safe if there are multiple
8408             // callers into it at the same time, but that's not a situation we
8409             // care about.
8410             if (persistent) {
8411                 final ContentResolver resolver = mContext.getContentResolver();
8412                 Settings.Global.putString(
8413                     resolver, Settings.Global.DEBUG_APP,
8414                     packageName);
8415                 Settings.Global.putInt(
8416                     resolver, Settings.Global.WAIT_FOR_DEBUGGER,
8417                     waitForDebugger ? 1 : 0);
8418             }
8419 
8420             synchronized (this) {
8421                 if (!persistent) {
8422                     mOrigDebugApp = mDebugApp;
8423                     mOrigWaitForDebugger = mWaitForDebugger;
8424                 }
8425                 mDebugApp = packageName;
8426                 mWaitForDebugger = waitForDebugger;
8427                 mDebugTransient = !persistent;
8428                 if (packageName != null) {
8429                     forceStopPackageLocked(packageName, -1, false, false, true, true,
8430                             false, UserHandle.USER_ALL, "set debug app");
8431                 }
8432             }
8433         } finally {
8434             Binder.restoreCallingIdentity(ident);
8435         }
8436     }
8437 
8438     /**
8439      * Set or remove an agent to be run whenever an app with the given process name starts.
8440      *
8441      * This method will not check whether the given process name matches a debuggable app. That
8442      * would require scanning all current packages, and a rescan when new packages are installed
8443      * or updated.
8444      *
8445      * Instead, do the check when an application is started and matched to a stored agent.
8446      *
8447      * @param packageName the process name of the app.
8448      * @param agent the agent string to be used, or null to remove any previously set agent.
8449      */
8450     @Override
setAgentApp(@onNull String packageName, @Nullable String agent)8451     public void setAgentApp(@NonNull String packageName, @Nullable String agent) {
8452         synchronized (this) {
8453             // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
8454             // its own permission.
8455             if (checkCallingPermission(
8456                     android.Manifest.permission.SET_ACTIVITY_WATCHER) !=
8457                         PackageManager.PERMISSION_GRANTED) {
8458                 throw new SecurityException(
8459                         "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8460             }
8461 
8462             if (agent == null) {
8463                 if (mAppAgentMap != null) {
8464                     mAppAgentMap.remove(packageName);
8465                     if (mAppAgentMap.isEmpty()) {
8466                         mAppAgentMap = null;
8467                     }
8468                 }
8469             } else {
8470                 if (mAppAgentMap == null) {
8471                     mAppAgentMap = new HashMap<>();
8472                 }
8473                 if (mAppAgentMap.size() >= 100) {
8474                     // Limit the size of the map, to avoid OOMEs.
8475                     Slog.e(TAG, "App agent map has too many entries, cannot add " + packageName
8476                             + "/" + agent);
8477                     return;
8478                 }
8479                 mAppAgentMap.put(packageName, agent);
8480             }
8481         }
8482     }
8483 
setTrackAllocationApp(ApplicationInfo app, String processName)8484     void setTrackAllocationApp(ApplicationInfo app, String processName) {
8485         synchronized (this) {
8486             boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8487             if (!isDebuggable) {
8488                 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
8489                     throw new SecurityException("Process not debuggable: " + app.packageName);
8490                 }
8491             }
8492 
8493             mTrackAllocationApp = processName;
8494         }
8495     }
8496 
setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)8497     void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) {
8498         synchronized (this) {
8499             boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8500             if (!isDebuggable) {
8501                 if (!app.isProfileableByShell()) {
8502                     throw new SecurityException("Process not debuggable, "
8503                             + "and not profileable by shell: " + app.packageName);
8504                 }
8505             }
8506             mProfileData.setProfileApp(processName);
8507 
8508             if (mProfileData.getProfilerInfo() != null) {
8509                 if (mProfileData.getProfilerInfo().profileFd != null) {
8510                     try {
8511                         mProfileData.getProfilerInfo().profileFd.close();
8512                     } catch (IOException e) {
8513                     }
8514                 }
8515             }
8516             mProfileData.setProfilerInfo(new ProfilerInfo(profilerInfo));
8517             mProfileType = 0;
8518         }
8519     }
8520 
setNativeDebuggingAppLocked(ApplicationInfo app, String processName)8521     void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
8522         boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8523         if (!isDebuggable) {
8524             if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
8525                 throw new SecurityException("Process not debuggable: " + app.packageName);
8526             }
8527         }
8528         mNativeDebuggingApp = processName;
8529     }
8530 
8531     @Override
setAlwaysFinish(boolean enabled)8532     public void setAlwaysFinish(boolean enabled) {
8533         enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
8534                 "setAlwaysFinish()");
8535 
8536         long ident = Binder.clearCallingIdentity();
8537         try {
8538             Settings.Global.putInt(
8539                     mContext.getContentResolver(),
8540                     Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
8541 
8542             synchronized (this) {
8543                 mAlwaysFinishActivities = enabled;
8544             }
8545         } finally {
8546             Binder.restoreCallingIdentity(ident);
8547         }
8548     }
8549 
8550     @Override
setActivityController(IActivityController controller, boolean imAMonkey)8551     public void setActivityController(IActivityController controller, boolean imAMonkey) {
8552         if (controller != null) {
8553             Binder.allowBlocking(controller.asBinder());
8554         }
8555         mActivityTaskManager.setActivityController(controller, imAMonkey);
8556     }
8557 
8558     @Override
setUserIsMonkey(boolean userIsMonkey)8559     public void setUserIsMonkey(boolean userIsMonkey) {
8560         synchronized (this) {
8561             synchronized (mPidsSelfLocked) {
8562                 final int callingPid = Binder.getCallingPid();
8563                 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
8564                 if (proc == null) {
8565                     throw new SecurityException("Unknown process: " + callingPid);
8566                 }
8567                 if (proc.getActiveInstrumentation() == null
8568                         || proc.getActiveInstrumentation().mUiAutomationConnection == null) {
8569                     throw new SecurityException("Only an instrumentation process "
8570                             + "with a UiAutomation can call setUserIsMonkey");
8571                 }
8572             }
8573             mUserIsMonkey = userIsMonkey;
8574         }
8575     }
8576 
8577     @Override
isUserAMonkey()8578     public boolean isUserAMonkey() {
8579         synchronized (this) {
8580             // If there is a controller also implies the user is a monkey.
8581             return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey();
8582         }
8583     }
8584 
8585     @Override
requestSystemServerHeapDump()8586     public void requestSystemServerHeapDump() {
8587         if (!Build.IS_DEBUGGABLE) {
8588             Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build");
8589             return;
8590         }
8591         if (Binder.getCallingUid() != SYSTEM_UID) {
8592             // This also intentionally excludes secondary profiles from calling this.
8593             throw new SecurityException(
8594                     "Only the system process is allowed to request a system heap dump");
8595         }
8596         ProcessRecord pr;
8597         synchronized (mPidsSelfLocked) {
8598             pr = mPidsSelfLocked.get(myPid());
8599         }
8600         if (pr == null) {
8601             Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid());
8602             return;
8603         }
8604         synchronized (this) {
8605             startHeapDumpLocked(pr, true);
8606         }
8607     }
8608 
8609     /**
8610      * Takes a bugreport using bug report API ({@code BugreportManager}) with no pre-set
8611      * title and description
8612      */
8613     @Override
requestBugReport(@ugreportParams.BugreportMode int bugreportType)8614     public void requestBugReport(@BugreportParams.BugreportMode int bugreportType) {
8615         requestBugReportWithDescription(null, null, bugreportType);
8616     }
8617 
8618     /**
8619      * Takes a bugreport using bug report API ({@code BugreportManager}) which gets
8620      * triggered by sending a broadcast to Shell.
8621      */
8622     @Override
requestBugReportWithDescription(@ullable String shareTitle, @Nullable String shareDescription, int bugreportType)8623     public void requestBugReportWithDescription(@Nullable String shareTitle,
8624             @Nullable String shareDescription, int bugreportType) {
8625         String type = null;
8626         switch (bugreportType) {
8627             case BugreportParams.BUGREPORT_MODE_FULL:
8628                 type = "bugreportfull";
8629                 break;
8630             case BugreportParams.BUGREPORT_MODE_INTERACTIVE:
8631                 type = "bugreportplus";
8632                 break;
8633             case BugreportParams.BUGREPORT_MODE_REMOTE:
8634                 type = "bugreportremote";
8635                 break;
8636             case BugreportParams.BUGREPORT_MODE_WEAR:
8637                 type = "bugreportwear";
8638                 break;
8639             case BugreportParams.BUGREPORT_MODE_TELEPHONY:
8640                 type = "bugreporttelephony";
8641                 break;
8642             case BugreportParams.BUGREPORT_MODE_WIFI:
8643                 type = "bugreportwifi";
8644                 break;
8645             default:
8646                 throw new IllegalArgumentException(
8647                     "Provided bugreport type is not correct, value: "
8648                         + bugreportType);
8649         }
8650         // Always log caller, even if it does not have permission to dump.
8651         Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid());
8652         enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
8653 
8654         if (!TextUtils.isEmpty(shareTitle)) {
8655             if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
8656                 String errorStr = "shareTitle should be less than "
8657                         + MAX_BUGREPORT_TITLE_SIZE + " characters";
8658                 throw new IllegalArgumentException(errorStr);
8659             }
8660             if (!TextUtils.isEmpty(shareDescription)) {
8661                 if (shareDescription.length() > MAX_BUGREPORT_DESCRIPTION_SIZE) {
8662                     String errorStr = "shareDescription should be less than "
8663                             + MAX_BUGREPORT_DESCRIPTION_SIZE + " characters";
8664                     throw new IllegalArgumentException(errorStr);
8665                 }
8666             }
8667             Slog.d(TAG, "Bugreport notification title " + shareTitle
8668                     + " description " + shareDescription);
8669         }
8670         // Create intent to trigger Bugreport API via Shell
8671         Intent triggerShellBugreport = new Intent();
8672         triggerShellBugreport.setAction(INTENT_BUGREPORT_REQUESTED);
8673         triggerShellBugreport.setPackage(SHELL_APP_PACKAGE);
8674         triggerShellBugreport.putExtra(EXTRA_BUGREPORT_TYPE, bugreportType);
8675         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8676         triggerShellBugreport.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
8677         if (shareTitle != null) {
8678             triggerShellBugreport.putExtra(EXTRA_TITLE, shareTitle);
8679         }
8680         if (shareDescription != null) {
8681             triggerShellBugreport.putExtra(EXTRA_DESCRIPTION, shareDescription);
8682         }
8683         final long identity = Binder.clearCallingIdentity();
8684         try {
8685             // Send broadcast to shell to trigger bugreport using Bugreport API
8686             mContext.sendBroadcast(triggerShellBugreport);
8687         } finally {
8688             Binder.restoreCallingIdentity(identity);
8689         }
8690     }
8691 
8692     /**
8693      * Takes a telephony bugreport with title and description
8694      */
8695     @Override
requestTelephonyBugReport(String shareTitle, String shareDescription)8696     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
8697         requestBugReportWithDescription(shareTitle, shareDescription,
8698                 BugreportParams.BUGREPORT_MODE_TELEPHONY);
8699     }
8700 
8701     /**
8702      * Takes a minimal bugreport of Wifi-related state with pre-set title and description
8703      */
8704     @Override
requestWifiBugReport(String shareTitle, String shareDescription)8705     public void requestWifiBugReport(String shareTitle, String shareDescription) {
8706         requestBugReportWithDescription(shareTitle, shareDescription,
8707                 BugreportParams.BUGREPORT_MODE_WIFI);
8708     }
8709 
8710     /**
8711      * Takes an interactive bugreport with a progress notification
8712      */
8713     @Override
requestInteractiveBugReport()8714     public void requestInteractiveBugReport() {
8715         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_INTERACTIVE);
8716     }
8717 
8718     /**
8719      * Takes an interactive bugreport with a progress notification. Also, shows the given title and
8720      * description on the final share notification
8721      */
8722     @Override
requestInteractiveBugReportWithDescription(String shareTitle, String shareDescription)8723     public void requestInteractiveBugReportWithDescription(String shareTitle,
8724             String shareDescription) {
8725         requestBugReportWithDescription(shareTitle, shareDescription,
8726                 BugreportParams.BUGREPORT_MODE_INTERACTIVE);
8727     }
8728 
8729     /**
8730      * Takes a bugreport with minimal user interference
8731      */
8732     @Override
requestFullBugReport()8733     public void requestFullBugReport() {
8734         requestBugReportWithDescription(null, null,  BugreportParams.BUGREPORT_MODE_FULL);
8735     }
8736 
8737     /**
8738      * Takes a bugreport remotely
8739      */
8740     @Override
requestRemoteBugReport()8741     public void requestRemoteBugReport() {
8742         requestBugReportWithDescription(null, null, BugreportParams.BUGREPORT_MODE_REMOTE);
8743     }
8744 
8745     /**
8746      * Launches a bugreport-whitelisted app to handle a bugreport.
8747      *
8748      * <p>Allows a bug report handler app to take bugreports on the user's behalf. The handler can
8749      * be predefined in the config, meant to be launched with the primary user. The user can
8750      * override this with a different (or same) handler app on possibly a different user. This is
8751      * useful for capturing bug reports from work profile, for instance.
8752      *
8753      * @return true if there is a bugreport-whitelisted app to handle a bugreport, or false
8754      * otherwise.
8755      */
8756     @Override
launchBugReportHandlerApp()8757     public boolean launchBugReportHandlerApp() {
8758         if (!BugReportHandlerUtil.isBugReportHandlerEnabled(mContext)) {
8759             return false;
8760         }
8761 
8762         // Always log caller, even if it does not have permission to dump.
8763         Slog.i(TAG, "launchBugReportHandlerApp requested by UID " + Binder.getCallingUid());
8764         enforceCallingPermission(android.Manifest.permission.DUMP,
8765                 "launchBugReportHandlerApp");
8766 
8767         return BugReportHandlerUtil.launchBugReportHandlerApp(mContext);
8768     }
8769 
8770     /**
8771      * Get packages of bugreport-whitelisted apps to handle a bug report.
8772      *
8773      * @return packages of bugreport-whitelisted apps to handle a bug report.
8774      */
8775     @Override
getBugreportWhitelistedPackages()8776     public List<String> getBugreportWhitelistedPackages() {
8777         enforceCallingPermission(android.Manifest.permission.MANAGE_DEBUGGING,
8778                 "getBugreportWhitelistedPackages");
8779         return new ArrayList<>(SystemConfig.getInstance().getBugreportWhitelistedPackages());
8780     }
8781 
registerProcessObserver(IProcessObserver observer)8782     public void registerProcessObserver(IProcessObserver observer) {
8783         enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
8784                 "registerProcessObserver()");
8785         synchronized (this) {
8786             mProcessObservers.register(observer);
8787         }
8788     }
8789 
8790     @Override
unregisterProcessObserver(IProcessObserver observer)8791     public void unregisterProcessObserver(IProcessObserver observer) {
8792         synchronized (this) {
8793             mProcessObservers.unregister(observer);
8794         }
8795     }
8796 
8797     @Override
getUidProcessState(int uid, String callingPackage)8798     public int getUidProcessState(int uid, String callingPackage) {
8799         if (!hasUsageStatsPermission(callingPackage)) {
8800             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8801                     "getUidProcessState");
8802         }
8803 
8804         synchronized (this) {
8805             return mProcessList.getUidProcStateLocked(uid);
8806         }
8807     }
8808 
8809     @Override
registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)8810     public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
8811             String callingPackage) {
8812         if (!hasUsageStatsPermission(callingPackage)) {
8813             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8814                     "registerUidObserver");
8815         }
8816         synchronized (this) {
8817             mUidObservers.register(observer, new UidObserverRegistration(Binder.getCallingUid(),
8818                     callingPackage, which, cutpoint));
8819         }
8820     }
8821 
8822     @Override
unregisterUidObserver(IUidObserver observer)8823     public void unregisterUidObserver(IUidObserver observer) {
8824         synchronized (this) {
8825             mUidObservers.unregister(observer);
8826         }
8827     }
8828 
8829     @Override
isUidActive(int uid, String callingPackage)8830     public boolean isUidActive(int uid, String callingPackage) {
8831         if (!hasUsageStatsPermission(callingPackage)) {
8832             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8833                     "isUidActive");
8834         }
8835         synchronized (this) {
8836             if (isUidActiveLocked(uid)) {
8837                 return true;
8838             }
8839         }
8840         return mInternal.isPendingTopUid(uid);
8841     }
8842 
isUidActiveLocked(int uid)8843     boolean isUidActiveLocked(int uid) {
8844         final UidRecord uidRecord = mProcessList.getUidRecordLocked(uid);
8845         return uidRecord != null && !uidRecord.setIdle;
8846     }
8847 
8848     @Override
setPersistentVrThread(int tid)8849     public void setPersistentVrThread(int tid) {
8850         mActivityTaskManager.setPersistentVrThread(tid);
8851     }
8852 
8853     /**
8854      * Schedule the given thread a normal scheduling priority.
8855      *
8856      * @param tid the tid of the thread to adjust the scheduling of.
8857      * @param suppressLogs {@code true} if any error logging should be disabled.
8858      *
8859      * @return {@code true} if this succeeded.
8860      */
scheduleAsRegularPriority(int tid, boolean suppressLogs)8861     public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
8862         try {
8863             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
8864             return true;
8865         } catch (IllegalArgumentException e) {
8866             if (!suppressLogs) {
8867                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
8868             }
8869         } catch (SecurityException e) {
8870             if (!suppressLogs) {
8871                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
8872             }
8873         }
8874         return false;
8875     }
8876 
8877     /**
8878      * Schedule the given thread an FIFO scheduling priority.
8879      *
8880      * @param tid the tid of the thread to adjust the scheduling of.
8881      * @param suppressLogs {@code true} if any error logging should be disabled.
8882      *
8883      * @return {@code true} if this succeeded.
8884      */
scheduleAsFifoPriority(int tid, boolean suppressLogs)8885     public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
8886         try {
8887             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
8888             return true;
8889         } catch (IllegalArgumentException e) {
8890             if (!suppressLogs) {
8891                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
8892             }
8893         } catch (SecurityException e) {
8894             if (!suppressLogs) {
8895                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
8896             }
8897         }
8898         return false;
8899     }
8900 
8901     @Override
setRenderThread(int tid)8902     public void setRenderThread(int tid) {
8903         synchronized (this) {
8904             ProcessRecord proc;
8905             int pid = Binder.getCallingPid();
8906             if (pid == Process.myPid()) {
8907                 demoteSystemServerRenderThread(tid);
8908                 return;
8909             }
8910             synchronized (mPidsSelfLocked) {
8911                 proc = mPidsSelfLocked.get(pid);
8912                 if (proc != null && proc.renderThreadTid == 0 && tid > 0) {
8913                     // ensure the tid belongs to the process
8914                     if (!isThreadInProcess(pid, tid)) {
8915                         throw new IllegalArgumentException(
8916                             "Render thread does not belong to process");
8917                     }
8918                     proc.renderThreadTid = tid;
8919                     if (DEBUG_OOM_ADJ) {
8920                         Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
8921                     }
8922                     // promote to FIFO now
8923                     if (proc.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) {
8924                         if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
8925                         if (mUseFifoUiScheduling) {
8926                             setThreadScheduler(proc.renderThreadTid,
8927                                 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
8928                         } else {
8929                             setThreadPriority(proc.renderThreadTid, TOP_APP_PRIORITY_BOOST);
8930                         }
8931                     }
8932                 } else {
8933                     if (DEBUG_OOM_ADJ) {
8934                         Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " +
8935                                "PID: " + pid + ", TID: " + tid + " FIFO: " +
8936                                mUseFifoUiScheduling);
8937                     }
8938                 }
8939             }
8940         }
8941     }
8942 
8943     /**
8944      * We only use RenderThread in system_server to store task snapshots to the disk, which should
8945      * happen in the background. Thus, demote render thread from system_server to a lower priority.
8946      *
8947      * @param tid the tid of the RenderThread
8948      */
demoteSystemServerRenderThread(int tid)8949     private void demoteSystemServerRenderThread(int tid) {
8950         setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
8951     }
8952 
8953     @Override
isVrModePackageEnabled(ComponentName packageName)8954     public boolean isVrModePackageEnabled(ComponentName packageName) {
8955         mActivityTaskManager.enforceSystemHasVrFeature();
8956 
8957         final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
8958 
8959         return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
8960                 VrManagerInternal.NO_ERROR;
8961     }
8962 
isTopActivityImmersive()8963     public boolean isTopActivityImmersive() {
8964         return mActivityTaskManager.isTopActivityImmersive();
8965     }
8966 
8967     @Override
isTopOfTask(IBinder token)8968     public boolean isTopOfTask(IBinder token) {
8969         return mActivityTaskManager.isTopOfTask(token);
8970     }
8971 
8972     @Override
setHasTopUi(boolean hasTopUi)8973     public void setHasTopUi(boolean hasTopUi) throws RemoteException {
8974         if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
8975             String msg = "Permission Denial: setHasTopUi() from pid="
8976                     + Binder.getCallingPid()
8977                     + ", uid=" + Binder.getCallingUid()
8978                     + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
8979             Slog.w(TAG, msg);
8980             throw new SecurityException(msg);
8981         }
8982         final int pid = Binder.getCallingPid();
8983         final long origId = Binder.clearCallingIdentity();
8984         try {
8985             synchronized (this) {
8986                 boolean changed = false;
8987                 ProcessRecord pr;
8988                 synchronized (mPidsSelfLocked) {
8989                     pr = mPidsSelfLocked.get(pid);
8990                     if (pr == null) {
8991                         Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
8992                         return;
8993                     }
8994                     if (pr.hasTopUi() != hasTopUi) {
8995                         if (DEBUG_OOM_ADJ) {
8996                             Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
8997                         }
8998                         pr.setHasTopUi(hasTopUi);
8999                         changed = true;
9000                     }
9001                 }
9002                 if (changed) {
9003                     updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
9004                 }
9005             }
9006         } finally {
9007             Binder.restoreCallingIdentity(origId);
9008         }
9009     }
9010 
enterSafeMode()9011     public final void enterSafeMode() {
9012         synchronized(this) {
9013             // It only makes sense to do this before the system is ready
9014             // and started launching other packages.
9015             if (!mSystemReady) {
9016                 try {
9017                     AppGlobals.getPackageManager().enterSafeMode();
9018                 } catch (RemoteException e) {
9019                 }
9020             }
9021 
9022             mSafeMode = true;
9023         }
9024     }
9025 
showSafeModeOverlay()9026     public final void showSafeModeOverlay() {
9027         View v = LayoutInflater.from(mContext).inflate(
9028                 com.android.internal.R.layout.safe_mode, null);
9029         WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
9030         lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
9031         lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
9032         lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
9033         lp.gravity = Gravity.BOTTOM | Gravity.START;
9034         lp.format = v.getBackground().getOpacity();
9035         lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
9036                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
9037         lp.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
9038         ((WindowManager)mContext.getSystemService(
9039                 Context.WINDOW_SERVICE)).addView(v, lp);
9040     }
9041 
9042     @Override
noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)9043     public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid,
9044             String sourcePkg, String tag) {
9045         if (workSource != null && workSource.isEmpty()) {
9046             workSource = null;
9047         }
9048 
9049         if (sourceUid <= 0 && workSource == null) {
9050             // Try and derive a UID to attribute things to based on the caller.
9051             if (sender != null) {
9052                 if (!(sender instanceof PendingIntentRecord)) {
9053                     return;
9054                 }
9055 
9056                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
9057                 final int callerUid = Binder.getCallingUid();
9058                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
9059             } else {
9060                 // TODO(narayan): Should we throw an exception in this case ? It means that we
9061                 // haven't been able to derive a UID to attribute things to.
9062                 return;
9063             }
9064         }
9065 
9066         int standbyBucket = 0;
9067 
9068         mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag);
9069         if (workSource != null) {
9070             String workSourcePackage = workSource.getPackageName(0);
9071             int workSourceUid = workSource.getAttributionUid();
9072             if (workSourcePackage == null) {
9073                 workSourcePackage = sourcePkg;
9074                 workSourceUid = sourceUid;
9075             }
9076 
9077             if (mUsageStatsService != null) {
9078                 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage,
9079                         UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime());
9080             }
9081 
9082             FrameworkStatsLog.write(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag,
9083                     sourcePkg, standbyBucket);
9084             if (DEBUG_POWER) {
9085                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
9086                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
9087                         + standbyBucket + " wsName=" + workSourcePackage + ")]");
9088             }
9089         } else {
9090             if (mUsageStatsService != null) {
9091                 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg,
9092                         UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime());
9093             }
9094             FrameworkStatsLog.write_non_chained(FrameworkStatsLog.WAKEUP_ALARM_OCCURRED, sourceUid,
9095                     null, tag, sourcePkg, standbyBucket);
9096             if (DEBUG_POWER) {
9097                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
9098                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
9099                         + standbyBucket + "]");
9100             }
9101         }
9102 
9103     }
9104 
9105     @Override
noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)9106     public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid,
9107             String tag) {
9108         if (workSource != null && workSource.isEmpty()) {
9109             workSource = null;
9110         }
9111 
9112         if (sourceUid <= 0 && workSource == null) {
9113             // Try and derive a UID to attribute things to based on the caller.
9114             if (sender != null) {
9115                 if (!(sender instanceof PendingIntentRecord)) {
9116                     return;
9117                 }
9118 
9119                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
9120                 final int callerUid = Binder.getCallingUid();
9121                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
9122             } else {
9123                 // TODO(narayan): Should we throw an exception in this case ? It means that we
9124                 // haven't been able to derive a UID to attribute things to.
9125                 return;
9126             }
9127         }
9128 
9129         if (DEBUG_POWER) {
9130             Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource +
9131                     ", tag=" + tag + "]");
9132         }
9133 
9134         mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid);
9135     }
9136 
9137     @Override
noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)9138     public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid,
9139             String tag) {
9140         if (workSource != null && workSource.isEmpty()) {
9141             workSource = null;
9142         }
9143 
9144         if (sourceUid <= 0 && workSource == null) {
9145             // Try and derive a UID to attribute things to based on the caller.
9146             if (sender != null) {
9147                 if (!(sender instanceof PendingIntentRecord)) {
9148                     return;
9149                 }
9150 
9151                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
9152                 final int callerUid = Binder.getCallingUid();
9153                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
9154             } else {
9155                 // TODO(narayan): Should we throw an exception in this case ? It means that we
9156                 // haven't been able to derive a UID to attribute things to.
9157                 return;
9158             }
9159         }
9160 
9161         if (DEBUG_POWER) {
9162             Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource +
9163                     ", tag=" + tag + "]");
9164         }
9165 
9166         mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid);
9167     }
9168 
killPids(int[] pids, String pReason, boolean secure)9169     public boolean killPids(int[] pids, String pReason, boolean secure) {
9170         if (Binder.getCallingUid() != SYSTEM_UID) {
9171             throw new SecurityException("killPids only available to the system");
9172         }
9173         String reason = (pReason == null) ? "Unknown" : pReason;
9174         // XXX Note: don't acquire main activity lock here, because the window
9175         // manager calls in with its locks held.
9176 
9177         boolean killed = false;
9178         synchronized (mPidsSelfLocked) {
9179             int worstType = 0;
9180             for (int i=0; i<pids.length; i++) {
9181                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
9182                 if (proc != null) {
9183                     int type = proc.setAdj;
9184                     if (type > worstType) {
9185                         worstType = type;
9186                     }
9187                 }
9188             }
9189 
9190             // If the worst oom_adj is somewhere in the cached proc LRU range,
9191             // then constrain it so we will kill all cached procs.
9192             if (worstType < ProcessList.CACHED_APP_MAX_ADJ
9193                     && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
9194                 worstType = ProcessList.CACHED_APP_MIN_ADJ;
9195             }
9196 
9197             // If this is not a secure call, don't let it kill processes that
9198             // are important.
9199             if (!secure && worstType < ProcessList.SERVICE_ADJ) {
9200                 worstType = ProcessList.SERVICE_ADJ;
9201             }
9202 
9203             Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
9204             for (int i=0; i<pids.length; i++) {
9205                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
9206                 if (proc == null) {
9207                     continue;
9208                 }
9209                 int adj = proc.setAdj;
9210                 if (adj >= worstType && !proc.killedByAm) {
9211                     proc.kill(reason, ApplicationExitInfo.REASON_OTHER,
9212                             ApplicationExitInfo.SUBREASON_KILL_PID, true);
9213                     killed = true;
9214                 }
9215             }
9216         }
9217         return killed;
9218     }
9219 
9220     @Override
killUid(int appId, int userId, String reason)9221     public void killUid(int appId, int userId, String reason) {
9222         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
9223         synchronized (this) {
9224             final long identity = Binder.clearCallingIdentity();
9225             try {
9226                 mProcessList.killPackageProcessesLocked(null /* packageName */, appId, userId,
9227                         ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
9228                         true /* callerWillRestart */, true /* doit */, true /* evenPersistent */,
9229                         false /* setRemoved */,
9230                         ApplicationExitInfo.REASON_OTHER,
9231                         ApplicationExitInfo.SUBREASON_KILL_UID,
9232                         reason != null ? reason : "kill uid");
9233             } finally {
9234                 Binder.restoreCallingIdentity(identity);
9235             }
9236         }
9237     }
9238 
9239     @Override
killUidForPermissionChange(int appId, int userId, String reason)9240     public void killUidForPermissionChange(int appId, int userId, String reason) {
9241         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
9242         synchronized (this) {
9243             final long identity = Binder.clearCallingIdentity();
9244             try {
9245                 mProcessList.killPackageProcessesLocked(null /* packageName */, appId, userId,
9246                         ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
9247                         true /* callerWillRestart */, true /* doit */, true /* evenPersistent */,
9248                         false /* setRemoved */,
9249                         ApplicationExitInfo.REASON_PERMISSION_CHANGE,
9250                         ApplicationExitInfo.SUBREASON_UNKNOWN,
9251                         reason != null ? reason : "kill uid");
9252             } finally {
9253                 Binder.restoreCallingIdentity(identity);
9254             }
9255         }
9256     }
9257 
9258     @Override
killProcessesBelowForeground(String reason)9259     public boolean killProcessesBelowForeground(String reason) {
9260         if (Binder.getCallingUid() != SYSTEM_UID) {
9261             throw new SecurityException("killProcessesBelowForeground() only available to system");
9262         }
9263 
9264         return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
9265     }
9266 
killProcessesBelowAdj(int belowAdj, String reason)9267     private boolean killProcessesBelowAdj(int belowAdj, String reason) {
9268         if (Binder.getCallingUid() != SYSTEM_UID) {
9269             throw new SecurityException("killProcessesBelowAdj() only available to system");
9270         }
9271 
9272         boolean killed = false;
9273         synchronized (mPidsSelfLocked) {
9274             final int size = mPidsSelfLocked.size();
9275             for (int i = 0; i < size; i++) {
9276                 final int pid = mPidsSelfLocked.keyAt(i);
9277                 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
9278                 if (proc == null) continue;
9279 
9280                 final int adj = proc.setAdj;
9281                 if (adj > belowAdj && !proc.killedByAm) {
9282                     proc.kill(reason, ApplicationExitInfo.REASON_PERMISSION_CHANGE, true);
9283                     killed = true;
9284                 }
9285             }
9286         }
9287         return killed;
9288     }
9289 
9290     /**
9291      * Similar to {@link #killPids} but killing will be delayed until the device is idle
9292      * and the given process is imperceptible.
9293      */
9294     @Override
killProcessesWhenImperceptible(int[] pids, String reason)9295     public void killProcessesWhenImperceptible(int[] pids, String reason) {
9296         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
9297                 != PackageManager.PERMISSION_GRANTED) {
9298             throw new SecurityException("Requires permission "
9299                     + android.Manifest.permission.FORCE_STOP_PACKAGES);
9300         }
9301         int callerUid = Binder.getCallingUid();
9302         long iden = Binder.clearCallingIdentity();
9303         try {
9304             mProcessList.killProcessesWhenImperceptible(pids, reason, callerUid);
9305         } finally {
9306             Binder.restoreCallingIdentity(iden);
9307         }
9308     }
9309 
9310     @Override
hang(final IBinder who, boolean allowRestart)9311     public void hang(final IBinder who, boolean allowRestart) {
9312         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9313                 != PackageManager.PERMISSION_GRANTED) {
9314             throw new SecurityException("Requires permission "
9315                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9316         }
9317 
9318         final IBinder.DeathRecipient death = new DeathRecipient() {
9319             @Override
9320             public void binderDied() {
9321                 synchronized (this) {
9322                     notifyAll();
9323                 }
9324             }
9325         };
9326 
9327         try {
9328             who.linkToDeath(death, 0);
9329         } catch (RemoteException e) {
9330             Slog.w(TAG, "hang: given caller IBinder is already dead.");
9331             return;
9332         }
9333 
9334         synchronized (this) {
9335             Watchdog.getInstance().setAllowRestart(allowRestart);
9336             Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
9337             synchronized (death) {
9338                 while (who.isBinderAlive()) {
9339                     try {
9340                         death.wait();
9341                     } catch (InterruptedException e) {
9342                     }
9343                 }
9344             }
9345             Watchdog.getInstance().setAllowRestart(true);
9346         }
9347     }
9348 
9349     @Override
restart()9350     public void restart() {
9351         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9352                 != PackageManager.PERMISSION_GRANTED) {
9353             throw new SecurityException("Requires permission "
9354                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9355         }
9356 
9357         Log.i(TAG, "Sending shutdown broadcast...");
9358 
9359         BroadcastReceiver br = new BroadcastReceiver() {
9360             @Override public void onReceive(Context context, Intent intent) {
9361                 // Now the broadcast is done, finish up the low-level shutdown.
9362                 Log.i(TAG, "Shutting down activity manager...");
9363                 shutdown(10000);
9364                 Log.i(TAG, "Shutdown complete, restarting!");
9365                 killProcess(myPid());
9366                 System.exit(10);
9367             }
9368         };
9369 
9370         // First send the high-level shut down broadcast.
9371         Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
9372         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9373         intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
9374         /* For now we are not doing a clean shutdown, because things seem to get unhappy.
9375         mContext.sendOrderedBroadcastAsUser(intent,
9376                 UserHandle.ALL, null, br, mHandler, 0, null, null);
9377         */
9378         br.onReceive(mContext, intent);
9379     }
9380 
getLowRamTimeSinceIdle(long now)9381     private long getLowRamTimeSinceIdle(long now) {
9382         return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0);
9383     }
9384 
9385     @Override
performIdleMaintenance()9386     public void performIdleMaintenance() {
9387         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9388                 != PackageManager.PERMISSION_GRANTED) {
9389             throw new SecurityException("Requires permission "
9390                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9391         }
9392 
9393         synchronized (this) {
9394             final long now = SystemClock.uptimeMillis();
9395             final long timeSinceLastIdle = now - mLastIdleTime;
9396 
9397             // Compact all non-zygote processes to freshen up the page cache.
9398             mOomAdjuster.mCachedAppOptimizer.compactAllSystem();
9399 
9400             final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
9401             mLastIdleTime = now;
9402             mLowRamTimeSinceLastIdle = 0;
9403             if (mLowRamStartTime != 0) {
9404                 mLowRamStartTime = now;
9405             }
9406 
9407             StringBuilder sb = new StringBuilder(128);
9408             sb.append("Idle maintenance over ");
9409             TimeUtils.formatDuration(timeSinceLastIdle, sb);
9410             sb.append(" low RAM for ");
9411             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
9412             Slog.i(TAG, sb.toString());
9413 
9414             // If at least 1/3 of our time since the last idle period has been spent
9415             // with RAM low, then we want to kill processes.
9416             boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
9417             // If the processes' memory has increased by more than 1% of the total memory,
9418             // or 10 MB, whichever is greater, then the processes' are eligible to be killed.
9419             final long totalMemoryInKb = getTotalMemory() / 1000;
9420             final long memoryGrowthThreshold =
9421                     Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
9422 
9423             for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) {
9424                 ProcessRecord proc = mProcessList.mLruProcesses.get(i);
9425                 if (proc.notCachedSinceIdle) {
9426                     if (proc.setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
9427                             && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
9428                         if (doKilling && proc.initialIdlePss != 0
9429                                 && proc.lastPss > ((proc.initialIdlePss * 3) / 2)
9430                                 && proc.lastPss > (proc.initialIdlePss + memoryGrowthThreshold)) {
9431                             sb = new StringBuilder(128);
9432                             sb.append("Kill");
9433                             sb.append(proc.processName);
9434                             sb.append(" in idle maint: pss=");
9435                             sb.append(proc.lastPss);
9436                             sb.append(", swapPss=");
9437                             sb.append(proc.lastSwapPss);
9438                             sb.append(", initialPss=");
9439                             sb.append(proc.initialIdlePss);
9440                             sb.append(", period=");
9441                             TimeUtils.formatDuration(timeSinceLastIdle, sb);
9442                             sb.append(", lowRamPeriod=");
9443                             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
9444                             Slog.wtfQuiet(TAG, sb.toString());
9445                             proc.kill("idle maint (pss " + proc.lastPss
9446                                     + " from " + proc.initialIdlePss + ")",
9447                                     ApplicationExitInfo.REASON_OTHER,
9448                                     ApplicationExitInfo.SUBREASON_MEMORY_PRESSURE,
9449                                     true);
9450                         }
9451                     }
9452                 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME
9453                         && proc.setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
9454                     proc.notCachedSinceIdle = true;
9455                     proc.initialIdlePss = 0;
9456                     proc.nextPssTime = ProcessList.computeNextPssTime(proc.setProcState, null,
9457                             mTestPssMode, mAtmInternal.isSleeping(), now);
9458                 }
9459             }
9460         }
9461     }
9462 
9463     @Override
sendIdleJobTrigger()9464     public void sendIdleJobTrigger() {
9465         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9466                 != PackageManager.PERMISSION_GRANTED) {
9467             throw new SecurityException("Requires permission "
9468                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9469         }
9470 
9471         final long ident = Binder.clearCallingIdentity();
9472         try {
9473             Intent intent = new Intent(ACTION_TRIGGER_IDLE)
9474                     .setPackage("android")
9475                     .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
9476             broadcastIntent(null, intent, null, null, 0, null, null, null,
9477                     OP_NONE, null, false, false, UserHandle.USER_ALL);
9478         } finally {
9479             Binder.restoreCallingIdentity(ident);
9480         }
9481     }
9482 
retrieveSettings()9483     private void retrieveSettings() {
9484         final ContentResolver resolver = mContext.getContentResolver();
9485         mActivityTaskManager.retrieveSettings(resolver);
9486 
9487         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
9488         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
9489         final boolean alwaysFinishActivities =
9490                 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
9491         final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver,
9492                 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS);
9493         mHiddenApiBlacklist.registerObserver();
9494 
9495         final long pssDeferralMs = DeviceConfig.getLong(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
9496                 ACTIVITY_START_PSS_DEFER_CONFIG, 0L);
9497         DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
9498                 ActivityThread.currentApplication().getMainExecutor(),
9499                 mPssDelayConfigListener);
9500 
9501         synchronized (this) {
9502             mDebugApp = mOrigDebugApp = debugApp;
9503             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
9504             mAlwaysFinishActivities = alwaysFinishActivities;
9505             // Load resources only after the current configuration has been set.
9506             final Resources res = mContext.getResources();
9507             mAppErrors.loadAppsNotReportingCrashesFromConfigLocked(res.getString(
9508                     com.android.internal.R.string.config_appsNotReportingCrashes));
9509             final boolean userSwitchUiEnabled = !res.getBoolean(
9510                     com.android.internal.R.bool.config_customUserSwitchUi);
9511             final int maxRunningUsers = res.getInteger(
9512                     com.android.internal.R.integer.config_multiuserMaxRunningUsers);
9513             final boolean delayUserDataLocking = res.getBoolean(
9514                     com.android.internal.R.bool.config_multiuserDelayUserDataLocking);
9515             mUserController.setInitialConfig(userSwitchUiEnabled, maxRunningUsers,
9516                     delayUserDataLocking);
9517             mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs;
9518             mPssDeferralTime = pssDeferralMs;
9519         }
9520     }
9521 
9522     /**
9523      * Ready. Set. Go!
9524      */
systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t)9525     public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
9526         t.traceBegin("PhaseActivityManagerReady");
9527         mSystemServiceManager.preSystemReady();
9528         synchronized(this) {
9529             if (mSystemReady) {
9530                 // If we're done calling all the receivers, run the next "boot phase" passed in
9531                 // by the SystemServer
9532                 if (goingCallback != null) {
9533                     goingCallback.run();
9534                 }
9535                 t.traceEnd(); // PhaseActivityManagerReady
9536                 return;
9537             }
9538 
9539             t.traceBegin("controllersReady");
9540             mLocalDeviceIdleController =
9541                     LocalServices.getService(DeviceIdleInternal.class);
9542             mActivityTaskManager.onSystemReady();
9543             // Make sure we have the current profile info, since it is needed for security checks.
9544             mUserController.onSystemReady();
9545             mAppOpsService.systemReady();
9546             mProcessList.onSystemReady();
9547             mSystemReady = true;
9548             t.traceEnd();
9549         }
9550 
9551         try {
9552             sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
9553                     ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
9554                     .getSerial();
9555         } catch (RemoteException e) {}
9556 
9557         t.traceBegin("killProcesses");
9558         ArrayList<ProcessRecord> procsToKill = null;
9559         synchronized(mPidsSelfLocked) {
9560             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
9561                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
9562                 if (!isAllowedWhileBooting(proc.info)){
9563                     if (procsToKill == null) {
9564                         procsToKill = new ArrayList<ProcessRecord>();
9565                     }
9566                     procsToKill.add(proc);
9567                 }
9568             }
9569         }
9570 
9571         synchronized(this) {
9572             if (procsToKill != null) {
9573                 for (int i=procsToKill.size()-1; i>=0; i--) {
9574                     ProcessRecord proc = procsToKill.get(i);
9575                     Slog.i(TAG, "Removing system update proc: " + proc);
9576                     mProcessList.removeProcessLocked(proc, true, false,
9577                             ApplicationExitInfo.REASON_OTHER,
9578                             ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
9579                             "system update done");
9580                 }
9581             }
9582 
9583             // Now that we have cleaned up any update processes, we
9584             // are ready to start launching real processes and know that
9585             // we won't trample on them any more.
9586             mProcessesReady = true;
9587         }
9588         t.traceEnd(); // KillProcesses
9589 
9590         Slog.i(TAG, "System now ready");
9591 
9592         EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
9593 
9594         t.traceBegin("updateTopComponentForFactoryTest");
9595         mAtmInternal.updateTopComponentForFactoryTest();
9596         t.traceEnd();
9597 
9598         t.traceBegin("registerActivityLaunchObserver");
9599         mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
9600         t.traceEnd();
9601 
9602         t.traceBegin("watchDeviceProvisioning");
9603         watchDeviceProvisioning(mContext);
9604         t.traceEnd();
9605 
9606         t.traceBegin("retrieveSettings");
9607         retrieveSettings();
9608         t.traceEnd();
9609 
9610         t.traceBegin("Ugm.onSystemReady");
9611         mUgmInternal.onSystemReady();
9612         t.traceEnd();
9613 
9614         t.traceBegin("updateForceBackgroundCheck");
9615         final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
9616         if (pmi != null) {
9617             pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
9618                     state -> updateForceBackgroundCheck(state.batterySaverEnabled));
9619             updateForceBackgroundCheck(
9620                     pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
9621         } else {
9622             Slog.wtf(TAG, "PowerManagerInternal not found.");
9623         }
9624         t.traceEnd();
9625 
9626         if (goingCallback != null) goingCallback.run();
9627 
9628         t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
9629         // Check the current user here as a user can be started inside goingCallback.run() from
9630         // other system services.
9631         final int currentUserId = mUserController.getCurrentUserId();
9632         Slog.i(TAG, "Current user:" + currentUserId);
9633         if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
9634             // User other than system user has started. Make sure that system user is already
9635             // started before switching user.
9636             throw new RuntimeException("System user not started while current user is:"
9637                     + currentUserId);
9638         }
9639         t.traceEnd();
9640 
9641         t.traceBegin("ActivityManagerStartApps");
9642         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
9643                 Integer.toString(currentUserId), currentUserId);
9644         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
9645                 Integer.toString(currentUserId), currentUserId);
9646 
9647         // On Automotive, at this point the system user has already been started and unlocked,
9648         // and some of the tasks we do here have already been done. So skip those in that case.
9649         // TODO(b/132262830): this workdound shouldn't be necessary once we move the
9650         // headless-user start logic to UserManager-land
9651         final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
9652 
9653         if (bootingSystemUser) {
9654             mSystemServiceManager.startUser(t, currentUserId);
9655         }
9656 
9657         synchronized (this) {
9658             // Only start up encryption-aware persistent apps; once user is
9659             // unlocked we'll come back around and start unaware apps
9660             t.traceBegin("startPersistentApps");
9661             startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
9662             t.traceEnd();
9663 
9664             // Start up initial activity.
9665             mBooting = true;
9666             // Enable home activity for system user, so that the system can always boot. We don't
9667             // do this when the system user is not setup since the setup wizard should be the one
9668             // to handle home activity in this case.
9669             if (UserManager.isSplitSystemUser() &&
9670                     Settings.Secure.getInt(mContext.getContentResolver(),
9671                          Settings.Secure.USER_SETUP_COMPLETE, 0) != 0
9672                     || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
9673                 t.traceBegin("enableHomeActivity");
9674                 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
9675                 try {
9676                     AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
9677                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
9678                             UserHandle.USER_SYSTEM);
9679                 } catch (RemoteException e) {
9680                     throw e.rethrowAsRuntimeException();
9681                 }
9682                 t.traceEnd();
9683             }
9684 
9685             if (bootingSystemUser) {
9686                 t.traceBegin("startHomeOnAllDisplays");
9687                 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
9688                 t.traceEnd();
9689             }
9690 
9691             t.traceBegin("showSystemReadyErrorDialogs");
9692             mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
9693             t.traceEnd();
9694 
9695 
9696             if (bootingSystemUser) {
9697                 t.traceBegin("sendUserStartBroadcast");
9698                 final int callingUid = Binder.getCallingUid();
9699                 final int callingPid = Binder.getCallingPid();
9700                 long ident = Binder.clearCallingIdentity();
9701                 try {
9702                     Intent intent = new Intent(Intent.ACTION_USER_STARTED);
9703                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
9704                             | Intent.FLAG_RECEIVER_FOREGROUND);
9705                     intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9706                     broadcastIntentLocked(null, null, null, intent,
9707                             null, null, 0, null, null, null, OP_NONE,
9708                             null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9709                             currentUserId);
9710                     intent = new Intent(Intent.ACTION_USER_STARTING);
9711                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
9712                     intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9713                     broadcastIntentLocked(null, null, null, intent, null,
9714                             new IIntentReceiver.Stub() {
9715                                 @Override
9716                                 public void performReceive(Intent intent, int resultCode,
9717                                         String data, Bundle extras, boolean ordered, boolean sticky,
9718                                         int sendingUser) {}
9719                             }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, OP_NONE, null,
9720                             true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9721                             UserHandle.USER_ALL);
9722                 } catch (Throwable e) {
9723                     Slog.wtf(TAG, "Failed sending first user broadcasts", e);
9724                 } finally {
9725                     Binder.restoreCallingIdentity(ident);
9726                 }
9727                 t.traceEnd();
9728             } else {
9729                 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
9730                         + currentUserId);
9731             }
9732 
9733             t.traceBegin("resumeTopActivities");
9734             mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
9735             t.traceEnd();
9736 
9737             if (bootingSystemUser) {
9738                 t.traceBegin("sendUserSwitchBroadcasts");
9739                 mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
9740                 t.traceEnd();
9741             }
9742 
9743             t.traceBegin("setBinderProxies");
9744             BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
9745                     BINDER_PROXY_LOW_WATERMARK);
9746             BinderInternal.nSetBinderProxyCountEnabled(true);
9747             BinderInternal.setBinderProxyCountCallback(
9748                     (uid) -> {
9749                         Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
9750                                 + Process.myUid());
9751                         BinderProxy.dumpProxyDebugInfo();
9752                         if (uid == Process.SYSTEM_UID) {
9753                             Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
9754                         } else {
9755                             killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
9756                                     "Too many Binders sent to SYSTEM");
9757                         }
9758                     }, mHandler);
9759             t.traceEnd(); // setBinderProxies
9760 
9761             t.traceEnd(); // ActivityManagerStartApps
9762             t.traceEnd(); // PhaseActivityManagerReady
9763         }
9764     }
9765 
watchDeviceProvisioning(Context context)9766     private void watchDeviceProvisioning(Context context) {
9767         // setting system property based on whether device is provisioned
9768 
9769         if (isDeviceProvisioned(context)) {
9770             SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
9771         } else {
9772             // watch for device provisioning change
9773             context.getContentResolver().registerContentObserver(
9774                     Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false,
9775                     new ContentObserver(new Handler(Looper.getMainLooper())) {
9776                         @Override
9777                         public void onChange(boolean selfChange) {
9778                             if (isDeviceProvisioned(context)) {
9779                                 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
9780                                 context.getContentResolver().unregisterContentObserver(this);
9781                             }
9782                         }
9783                     });
9784         }
9785     }
9786 
isDeviceProvisioned(Context context)9787     private boolean isDeviceProvisioned(Context context) {
9788         return Settings.Global.getInt(context.getContentResolver(),
9789                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
9790     }
9791 
startBroadcastObservers()9792     private void startBroadcastObservers() {
9793         for (BroadcastQueue queue : mBroadcastQueues) {
9794             queue.start(mContext.getContentResolver());
9795         }
9796     }
9797 
updateForceBackgroundCheck(boolean enabled)9798     private void updateForceBackgroundCheck(boolean enabled) {
9799         synchronized (this) {
9800             if (mForceBackgroundCheck != enabled) {
9801                 mForceBackgroundCheck = enabled;
9802 
9803                 if (DEBUG_BACKGROUND_CHECK) {
9804                     Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled"));
9805                 }
9806 
9807                 if (mForceBackgroundCheck) {
9808                     // Stop background services for idle UIDs.
9809                     mProcessList.doStopUidForIdleUidsLocked();
9810                 }
9811             }
9812         }
9813     }
9814 
killAppAtUsersRequest(ProcessRecord app)9815     void killAppAtUsersRequest(ProcessRecord app) {
9816         synchronized (this) {
9817             mAppErrors.killAppAtUserRequestLocked(app);
9818         }
9819     }
9820 
skipCurrentReceiverLocked(ProcessRecord app)9821     void skipCurrentReceiverLocked(ProcessRecord app) {
9822         for (BroadcastQueue queue : mBroadcastQueues) {
9823             queue.skipCurrentReceiverLocked(app);
9824         }
9825     }
9826 
9827     /**
9828      * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
9829      * The application process will exit immediately after this call returns.
9830      * @param app object of the crashing app, null for the system server
9831      * @param crashInfo describing the exception
9832      */
handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)9833     public void handleApplicationCrash(IBinder app,
9834             ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
9835         ProcessRecord r = findAppProcess(app, "Crash");
9836         final String processName = app == null ? "system_server"
9837                 : (r == null ? "unknown" : r.processName);
9838 
9839         handleApplicationCrashInner("crash", r, processName, crashInfo);
9840     }
9841 
9842     /* Native crash reporting uses this inner version because it needs to be somewhat
9843      * decoupled from the AM-managed cleanup lifecycle
9844      */
handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)9845     void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
9846             ApplicationErrorReport.CrashInfo crashInfo) {
9847 
9848         EventLogTags.writeAmCrash(Binder.getCallingPid(),
9849                 UserHandle.getUserId(Binder.getCallingUid()), processName,
9850                 r == null ? -1 : r.info.flags,
9851                 crashInfo.exceptionClassName,
9852                 crashInfo.exceptionMessage,
9853                 crashInfo.throwFileName,
9854                 crashInfo.throwLineNumber);
9855 
9856         FrameworkStatsLog.write(FrameworkStatsLog.APP_CRASH_OCCURRED,
9857                 Binder.getCallingUid(),
9858                 eventType,
9859                 processName,
9860                 Binder.getCallingPid(),
9861                 (r != null && r.info != null) ? r.info.packageName : "",
9862                 (r != null && r.info != null) ? (r.info.isInstantApp()
9863                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE
9864                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE)
9865                         : FrameworkStatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE,
9866                 r != null ? (r.isInterestingToUserLocked()
9867                         ? FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND
9868                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND)
9869                         : FrameworkStatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN,
9870                 processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER
9871                         : (r != null) ? r.getProcessClassEnum()
9872                                       : ServerProtoEnums.ERROR_SOURCE_UNKNOWN
9873         );
9874 
9875         final int relaunchReason = r == null ? RELAUNCH_REASON_NONE
9876                         : r.getWindowProcessController().computeRelaunchReason();
9877         final String relaunchReasonString = relaunchReasonToString(relaunchReason);
9878         if (crashInfo.crashTag == null) {
9879             crashInfo.crashTag = relaunchReasonString;
9880         } else {
9881             crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString;
9882         }
9883 
9884         addErrorToDropBox(
9885                 eventType, r, processName, null, null, null, null, null, null, crashInfo);
9886 
9887         mAppErrors.crashApplication(r, crashInfo);
9888     }
9889 
handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9890     public void handleApplicationStrictModeViolation(
9891             IBinder app,
9892             int penaltyMask,
9893             StrictMode.ViolationInfo info) {
9894         // We're okay if the ProcessRecord is missing; it probably means that
9895         // we're reporting a violation from the system process itself.
9896         final ProcessRecord r = findAppProcess(app, "StrictMode");
9897 
9898         if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) {
9899             Integer stackFingerprint = info.hashCode();
9900             boolean logIt = true;
9901             synchronized (mAlreadyLoggedViolatedStacks) {
9902                 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
9903                     logIt = false;
9904                     // TODO: sub-sample into EventLog for these, with
9905                     // the info.durationMillis?  Then we'd get
9906                     // the relative pain numbers, without logging all
9907                     // the stack traces repeatedly.  We'd want to do
9908                     // likewise in the client code, which also does
9909                     // dup suppression, before the Binder call.
9910                 } else {
9911                     if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
9912                         mAlreadyLoggedViolatedStacks.clear();
9913                     }
9914                     mAlreadyLoggedViolatedStacks.add(stackFingerprint);
9915                 }
9916             }
9917             if (logIt) {
9918                 logStrictModeViolationToDropBox(r, info);
9919             }
9920         }
9921 
9922         if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) {
9923             AppErrorResult result = new AppErrorResult();
9924             synchronized (this) {
9925                 final long origId = Binder.clearCallingIdentity();
9926 
9927                 Message msg = Message.obtain();
9928                 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG;
9929                 HashMap<String, Object> data = new HashMap<String, Object>();
9930                 data.put("result", result);
9931                 data.put("app", r);
9932                 data.put("info", info);
9933                 msg.obj = data;
9934                 mUiHandler.sendMessage(msg);
9935 
9936                 Binder.restoreCallingIdentity(origId);
9937             }
9938             int res = result.get();
9939             Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
9940         }
9941     }
9942 
9943     // Depending on the policy in effect, there could be a bunch of
9944     // these in quick succession so we try to batch these together to
9945     // minimize disk writes, number of dropbox entries, and maximize
9946     // compression, by having more fewer, larger records.
logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9947     private void logStrictModeViolationToDropBox(
9948             ProcessRecord process,
9949             StrictMode.ViolationInfo info) {
9950         if (info == null) {
9951             return;
9952         }
9953         final boolean isSystemApp = process == null ||
9954                 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
9955                                        ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
9956         final String processName = process == null ? "unknown" : process.processName;
9957         final DropBoxManager dbox = (DropBoxManager)
9958                 mContext.getSystemService(Context.DROPBOX_SERVICE);
9959 
9960         // Exit early if the dropbox isn't configured to accept this report type.
9961         final String dropboxTag = processClass(process) + "_strictmode";
9962         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9963 
9964         final StringBuilder sb = new StringBuilder(1024);
9965         synchronized (sb) {
9966             appendDropBoxProcessHeaders(process, processName, sb);
9967             sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9968             sb.append("System-App: ").append(isSystemApp).append("\n");
9969             sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
9970             if (info.violationNumThisLoop != 0) {
9971                 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
9972             }
9973             if (info.numAnimationsRunning != 0) {
9974                 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
9975             }
9976             if (info.broadcastIntentAction != null) {
9977                 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
9978             }
9979             if (info.durationMillis != -1) {
9980                 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
9981             }
9982             if (info.numInstances != -1) {
9983                 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
9984             }
9985             if (info.tags != null) {
9986                 for (String tag : info.tags) {
9987                     sb.append("Span-Tag: ").append(tag).append("\n");
9988                 }
9989             }
9990             sb.append("\n");
9991             sb.append(info.getStackTrace());
9992             sb.append("\n");
9993             if (info.getViolationDetails() != null) {
9994                 sb.append(info.getViolationDetails());
9995                 sb.append("\n");
9996             }
9997         }
9998 
9999         final String res = sb.toString();
10000         IoThread.getHandler().post(() -> {
10001             dbox.addText(dropboxTag, res);
10002         });
10003     }
10004 
10005     /**
10006      * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
10007      * @param app object of the crashing app, null for the system server
10008      * @param tag reported by the caller
10009      * @param system whether this wtf is coming from the system
10010      * @param crashInfo describing the context of the error
10011      * @return true if the process should exit immediately (WTF is fatal)
10012      */
10013     @Override
handleApplicationWtf(final IBinder app, final String tag, boolean system, final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid)10014     public boolean handleApplicationWtf(final IBinder app, final String tag, boolean system,
10015             final ApplicationErrorReport.ParcelableCrashInfo crashInfo, int immediateCallerPid) {
10016         final int callingUid = Binder.getCallingUid();
10017         final int callingPid = Binder.getCallingPid();
10018 
10019         // If this is coming from the system, we could very well have low-level
10020         // system locks held, so we want to do this all asynchronously.  And we
10021         // never want this to become fatal, so there is that too.
10022         //
10023         // Note: "callingPid == Process.myPid())" wouldn't be reliable because even if the caller
10024         // is within the system server, if it calls Log.wtf() without clearning the calling
10025         // identity, callingPid would still be of a remote caller. So we explicltly pass the
10026         // process PID from the caller.
10027         if (system || (immediateCallerPid == Process.myPid())) {
10028             mHandler.post(new Runnable() {
10029                 @Override public void run() {
10030                     handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo);
10031                 }
10032             });
10033             return false;
10034         }
10035 
10036         final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag,
10037                 crashInfo);
10038 
10039         final boolean isFatal = Build.IS_ENG || Settings.Global
10040                 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0;
10041         final boolean isSystem = (r == null) || r.isPersistent();
10042 
10043         if (isFatal && !isSystem) {
10044             mAppErrors.crashApplication(r, crashInfo);
10045             return true;
10046         } else {
10047             return false;
10048         }
10049     }
10050 
handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, final ApplicationErrorReport.CrashInfo crashInfo)10051     ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag,
10052             final ApplicationErrorReport.CrashInfo crashInfo) {
10053         final ProcessRecord r = findAppProcess(app, "WTF");
10054         final String processName = app == null ? "system_server"
10055                 : (r == null ? "unknown" : r.processName);
10056 
10057         EventLogTags.writeAmWtf(UserHandle.getUserId(callingUid), callingPid,
10058                 processName, r == null ? -1 : r.info.flags, tag, crashInfo.exceptionMessage);
10059 
10060         FrameworkStatsLog.write(FrameworkStatsLog.WTF_OCCURRED, callingUid, tag, processName,
10061                 callingPid, (r != null) ? r.getProcessClassEnum() : 0);
10062 
10063         addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo);
10064 
10065         return r;
10066     }
10067 
10068     /**
10069      * Schedule to handle any pending system_server WTFs.
10070      */
schedulePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)10071     public void schedulePendingSystemServerWtfs(
10072             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
10073         mHandler.post(() -> handlePendingSystemServerWtfs(list));
10074     }
10075 
10076     /**
10077      * Handle any pending system_server WTFs, add into the dropbox
10078      */
handlePendingSystemServerWtfs( final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list)10079     private void handlePendingSystemServerWtfs(
10080             final LinkedList<Pair<String, ApplicationErrorReport.CrashInfo>> list) {
10081         ProcessRecord proc;
10082         synchronized (mPidsSelfLocked) {
10083             proc = mPidsSelfLocked.get(MY_PID);
10084         }
10085         for (Pair<String, ApplicationErrorReport.CrashInfo> p = list.poll();
10086                 p != null; p = list.poll()) {
10087             addErrorToDropBox("wtf", proc, "system_server", null, null, null, p.first, null, null,
10088                     p.second);
10089         }
10090     }
10091 
10092     /**
10093      * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
10094      * @return the corresponding {@link ProcessRecord} object, or null if none could be found
10095      */
findAppProcess(IBinder app, String reason)10096     private ProcessRecord findAppProcess(IBinder app, String reason) {
10097         if (app == null) {
10098             return null;
10099         }
10100 
10101         synchronized (this) {
10102             return mProcessList.findAppProcessLocked(app, reason);
10103         }
10104     }
10105 
10106     /**
10107      * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
10108      * to append various headers to the dropbox log text.
10109      */
appendDropBoxProcessHeaders(ProcessRecord process, String processName, StringBuilder sb)10110     void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
10111             StringBuilder sb) {
10112         // Watchdog thread ends up invoking this function (with
10113         // a null ProcessRecord) to add the stack file to dropbox.
10114         // Do not acquire a lock on this (am) in such cases, as it
10115         // could cause a potential deadlock, if and when watchdog
10116         // is invoked due to unavailability of lock on am and it
10117         // would prevent watchdog from killing system_server.
10118         if (process == null) {
10119             sb.append("Process: ").append(processName).append("\n");
10120             return;
10121         }
10122         // Note: ProcessRecord 'process' is guarded by the service
10123         // instance.  (notably process.pkgList, which could otherwise change
10124         // concurrently during execution of this method)
10125         synchronized (this) {
10126             sb.append("Process: ").append(processName).append("\n");
10127             sb.append("PID: ").append(process.pid).append("\n");
10128             sb.append("UID: ").append(process.uid).append("\n");
10129             int flags = process.info.flags;
10130             IPackageManager pm = AppGlobals.getPackageManager();
10131             sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n");
10132             for (int ip=0; ip<process.pkgList.size(); ip++) {
10133                 String pkg = process.pkgList.keyAt(ip);
10134                 sb.append("Package: ").append(pkg);
10135                 try {
10136                     PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
10137                     if (pi != null) {
10138                         sb.append(" v").append(pi.getLongVersionCode());
10139                         if (pi.versionName != null) {
10140                             sb.append(" (").append(pi.versionName).append(")");
10141                         }
10142                     }
10143                 } catch (RemoteException e) {
10144                     Slog.e(TAG, "Error getting package info: " + pkg, e);
10145                 }
10146                 sb.append("\n");
10147             }
10148             if (process.info.isInstantApp()) {
10149                 sb.append("Instant-App: true\n");
10150             }
10151         }
10152     }
10153 
processClass(ProcessRecord process)10154     private static String processClass(ProcessRecord process) {
10155         if (process == null || process.pid == MY_PID) {
10156             return "system_server";
10157         } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10158             return "system_app";
10159         } else {
10160             return "data_app";
10161         }
10162     }
10163 
10164     private final ArrayMap<String, long[]> mErrorClusterRecords = new ArrayMap<>();
10165 
10166     /**
10167      * Write a description of an error (crash, WTF, ANR) to the drop box.
10168      * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
10169      * @param process which caused the error, null means the system server
10170      * @param activityShortComponentName which triggered the error, null if unknown
10171      * @param parentShortComponentName activity related to the error, null if unknown
10172      * @param parentProcess parent process
10173      * @param subject line related to the error, null if absent
10174      * @param report in long form describing the error, null if absent
10175      * @param dataFile text file to include in the report, null if none
10176      * @param crashInfo giving an application stack trace, null if absent
10177      */
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)10178     public void addErrorToDropBox(String eventType,
10179             ProcessRecord process, String processName, String activityShortComponentName,
10180             String parentShortComponentName, ProcessRecord parentProcess,
10181             String subject, final String report, final File dataFile,
10182             final ApplicationErrorReport.CrashInfo crashInfo) {
10183         // NOTE -- this must never acquire the ActivityManagerService lock,
10184         // otherwise the watchdog may be prevented from resetting the system.
10185 
10186         // Bail early if not published yet
10187         if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return;
10188         final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class);
10189 
10190         // Exit early if the dropbox isn't configured to accept this report type.
10191         final String dropboxTag = processClass(process) + "_" + eventType;
10192         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
10193 
10194         // Rate-limit how often we're willing to do the heavy lifting below to
10195         // collect and record logs; currently 5 logs per 10 second period per eventType.
10196         final long now = SystemClock.elapsedRealtime();
10197         synchronized (mErrorClusterRecords) {
10198             long[] errRecord = mErrorClusterRecords.get(eventType);
10199             if (errRecord == null) {
10200                 errRecord = new long[2]; // [0]: startTime, [1]: count
10201                 mErrorClusterRecords.put(eventType, errRecord);
10202             }
10203             if (now - errRecord[0] > 10 * DateUtils.SECOND_IN_MILLIS) {
10204                 errRecord[0] = now;
10205                 errRecord[1] = 1L;
10206             } else {
10207                 if (errRecord[1]++ >= 5) return;
10208             }
10209         }
10210 
10211         final StringBuilder sb = new StringBuilder(1024);
10212         appendDropBoxProcessHeaders(process, processName, sb);
10213         if (process != null) {
10214             sb.append("Foreground: ")
10215                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
10216                     .append("\n");
10217             if (process.startTime > 0) {
10218                 long runtimeMillis = SystemClock.elapsedRealtime() - process.startTime;
10219                 sb.append("Process-Runtime: ").append(runtimeMillis).append("\n");
10220             }
10221         }
10222         if (activityShortComponentName != null) {
10223             sb.append("Activity: ").append(activityShortComponentName).append("\n");
10224         }
10225         if (parentShortComponentName != null) {
10226             if (parentProcess != null && parentProcess.pid != process.pid) {
10227                 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n");
10228             }
10229             if (!parentShortComponentName.equals(activityShortComponentName)) {
10230                 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n");
10231             }
10232         }
10233         if (subject != null) {
10234             sb.append("Subject: ").append(subject).append("\n");
10235         }
10236         sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
10237         if (Debug.isDebuggerConnected()) {
10238             sb.append("Debugger: Connected\n");
10239         }
10240         if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) {
10241             sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n");
10242         }
10243         sb.append("\n");
10244 
10245         // Do the rest in a worker thread to avoid blocking the caller on I/O
10246         // (After this point, we shouldn't access AMS internal data structures.)
10247         Thread worker = new Thread("Error dump: " + dropboxTag) {
10248             @Override
10249             public void run() {
10250                 if (report != null) {
10251                     sb.append(report);
10252                 }
10253 
10254                 String logcatSetting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
10255                 String maxBytesSetting = Settings.Global.MAX_ERROR_BYTES_PREFIX + dropboxTag;
10256                 int lines = Settings.Global.getInt(mContext.getContentResolver(), logcatSetting, 0);
10257                 int dropboxMaxSize = Settings.Global.getInt(
10258                         mContext.getContentResolver(), maxBytesSetting, DROPBOX_DEFAULT_MAX_SIZE);
10259                 int maxDataFileSize = dropboxMaxSize - sb.length()
10260                         - lines * RESERVED_BYTES_PER_LOGCAT_LINE;
10261 
10262                 if (dataFile != null && maxDataFileSize > 0) {
10263                     try {
10264                         sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize,
10265                                     "\n\n[[TRUNCATED]]"));
10266                     } catch (IOException e) {
10267                         Slog.e(TAG, "Error reading " + dataFile, e);
10268                     }
10269                 }
10270                 if (crashInfo != null && crashInfo.stackTrace != null) {
10271                     sb.append(crashInfo.stackTrace);
10272                 }
10273 
10274                 if (lines > 0) {
10275                     sb.append("\n");
10276 
10277                     // Merge several logcat streams, and take the last N lines
10278                     InputStreamReader input = null;
10279                     try {
10280                         java.lang.Process logcat = new ProcessBuilder(
10281                                 "/system/bin/timeout", "-k", "15s", "10s",
10282                                 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system",
10283                                 "-b", "main", "-b", "crash", "-t", String.valueOf(lines))
10284                                         .redirectErrorStream(true).start();
10285 
10286                         try { logcat.getOutputStream().close(); } catch (IOException e) {}
10287                         try { logcat.getErrorStream().close(); } catch (IOException e) {}
10288                         input = new InputStreamReader(logcat.getInputStream());
10289 
10290                         int num;
10291                         char[] buf = new char[8192];
10292                         while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
10293                     } catch (IOException e) {
10294                         Slog.e(TAG, "Error running logcat", e);
10295                     } finally {
10296                         if (input != null) try { input.close(); } catch (IOException e) {}
10297                     }
10298                 }
10299 
10300                 dbox.addText(dropboxTag, sb.toString());
10301             }
10302         };
10303 
10304         if (process == null) {
10305             // If process is null, we are being called from some internal code
10306             // and may be about to die -- run this synchronously.
10307             final int oldMask = StrictMode.allowThreadDiskWritesMask();
10308             try {
10309                 worker.run();
10310             } finally {
10311                 StrictMode.setThreadPolicyMask(oldMask);
10312             }
10313         } else {
10314             worker.start();
10315         }
10316     }
10317 
10318     @Override
getProcessesInErrorState()10319     public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
10320         enforceNotIsolatedCaller("getProcessesInErrorState");
10321         // assume our apps are happy - lazy create the list
10322         List<ActivityManager.ProcessErrorStateInfo> errList = null;
10323 
10324         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
10325                 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
10326         int userId = UserHandle.getUserId(Binder.getCallingUid());
10327 
10328         synchronized (this) {
10329 
10330             // iterate across all processes
10331             for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) {
10332                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
10333                 if (!allUsers && app.userId != userId) {
10334                     continue;
10335                 }
10336                 final boolean crashing = app.isCrashing();
10337                 final boolean notResponding = app.isNotResponding();
10338                 if ((app.thread != null) && (crashing || notResponding)) {
10339                     // This one's in trouble, so we'll generate a report for it
10340                     // crashes are higher priority (in case there's a crash *and* an anr)
10341                     ActivityManager.ProcessErrorStateInfo report = null;
10342                     if (crashing) {
10343                         report = app.crashingReport;
10344                     } else if (notResponding) {
10345                         report = app.notRespondingReport;
10346                     }
10347 
10348                     if (report != null) {
10349                         if (errList == null) {
10350                             errList = new ArrayList<>(1);
10351                         }
10352                         errList.add(report);
10353                     } else {
10354                         Slog.w(TAG, "Missing app error report, app = " + app.processName +
10355                                 " crashing = " + crashing +
10356                                 " notResponding = " + notResponding);
10357                     }
10358                 }
10359             }
10360         }
10361 
10362         return errList;
10363     }
10364 
10365     @Override
getRunningAppProcesses()10366     public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
10367         enforceNotIsolatedCaller("getRunningAppProcesses");
10368 
10369         final int callingUid = Binder.getCallingUid();
10370         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
10371 
10372         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
10373                 callingUid) == PackageManager.PERMISSION_GRANTED;
10374         final int userId = UserHandle.getUserId(callingUid);
10375         final boolean allUids = mAtmInternal.isGetTasksAllowed(
10376                 "getRunningAppProcesses", Binder.getCallingPid(), callingUid);
10377 
10378         synchronized (this) {
10379             // Iterate across all processes
10380             return mProcessList.getRunningAppProcessesLocked(allUsers, userId, allUids,
10381                     callingUid, clientTargetSdk);
10382         }
10383     }
10384 
10385     @Override
getRunningExternalApplications()10386     public List<ApplicationInfo> getRunningExternalApplications() {
10387         enforceNotIsolatedCaller("getRunningExternalApplications");
10388         List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
10389         List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
10390         if (runningApps != null && runningApps.size() > 0) {
10391             Set<String> extList = new HashSet<String>();
10392             for (ActivityManager.RunningAppProcessInfo app : runningApps) {
10393                 if (app.pkgList != null) {
10394                     for (String pkg : app.pkgList) {
10395                         extList.add(pkg);
10396                     }
10397                 }
10398             }
10399             IPackageManager pm = AppGlobals.getPackageManager();
10400             for (String pkg : extList) {
10401                 try {
10402                     ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
10403                     if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
10404                         retList.add(info);
10405                     }
10406                 } catch (RemoteException e) {
10407                 }
10408             }
10409         }
10410         return retList;
10411     }
10412 
10413     @Override
getHistoricalProcessExitReasons( String packageName, int pid, int maxNum, int userId)10414     public ParceledListSlice<ApplicationExitInfo> getHistoricalProcessExitReasons(
10415             String packageName, int pid, int maxNum, int userId) {
10416         enforceNotIsolatedCaller("getHistoricalProcessExitReasons");
10417 
10418         // For the simplification, we don't support USER_ALL nor USER_CURRENT here.
10419         if (userId == UserHandle.USER_ALL || userId == UserHandle.USER_CURRENT) {
10420             throw new IllegalArgumentException("Unsupported userId");
10421         }
10422 
10423         final int callingPid = Binder.getCallingPid();
10424         final int callingUid = Binder.getCallingUid();
10425         final int callingUserId = UserHandle.getCallingUserId();
10426         mUserController.handleIncomingUser(callingPid, callingUid, userId, true, ALLOW_NON_FULL,
10427                 "getHistoricalProcessExitReasons", null);
10428 
10429         final ArrayList<ApplicationExitInfo> results = new ArrayList<ApplicationExitInfo>();
10430         if (!TextUtils.isEmpty(packageName)) {
10431             final int uid = enforceDumpPermissionForPackage(packageName, userId, callingUid,
10432                       "getHistoricalProcessExitReasons");
10433             if (uid != Process.INVALID_UID) {
10434                 mProcessList.mAppExitInfoTracker.getExitInfo(
10435                         packageName, uid, pid, maxNum, results);
10436             }
10437         } else {
10438             // If no package name is given, use the caller's uid as the filter uid.
10439             mProcessList.mAppExitInfoTracker.getExitInfo(
10440                     packageName, callingUid, pid, maxNum, results);
10441         }
10442 
10443         return new ParceledListSlice<ApplicationExitInfo>(results);
10444     }
10445 
10446     @Override
setProcessStateSummary(@ullable byte[] state)10447     public void setProcessStateSummary(@Nullable byte[] state) {
10448         if (state != null && state.length > MAX_STATE_DATA_SIZE) {
10449             throw new IllegalArgumentException("Data size is too large");
10450         }
10451         mProcessList.mAppExitInfoTracker.setProcessStateSummary(Binder.getCallingUid(),
10452                 Binder.getCallingPid(), state);
10453     }
10454 
10455     /**
10456      * Check if the calling process has the permission to dump given package,
10457      * throw SecurityException if it doesn't have the permission.
10458      *
10459      * @return The UID of the given package, or {@link android.os.Process#INVALID_UID}
10460      *         if the package is not found.
10461      */
enforceDumpPermissionForPackage(String packageName, int userId, int callingUid, String function)10462     int enforceDumpPermissionForPackage(String packageName, int userId, int callingUid,
10463             String function) {
10464         long identity = Binder.clearCallingIdentity();
10465         int uid = Process.INVALID_UID;
10466         try {
10467             uid = mPackageManagerInt.getPackageUid(packageName,
10468                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, userId);
10469         } finally {
10470             Binder.restoreCallingIdentity(identity);
10471         }
10472         // If the uid is Process.INVALID_UID, the below 'if' check will be always true
10473         if (UserHandle.getAppId(uid) != UserHandle.getAppId(callingUid)) {
10474             // Requires the DUMP permission if the target package doesn't belong
10475             // to the caller or it doesn't exist.
10476             enforceCallingPermission(android.Manifest.permission.DUMP, function);
10477         }
10478         return uid;
10479     }
10480 
10481     @Override
getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)10482     public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) {
10483         if (outState == null) {
10484             throw new IllegalArgumentException("outState is null");
10485         }
10486         enforceNotIsolatedCaller("getMyMemoryState");
10487 
10488         final int callingUid = Binder.getCallingUid();
10489         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
10490 
10491         synchronized (this) {
10492             ProcessRecord proc;
10493             synchronized (mPidsSelfLocked) {
10494                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
10495             }
10496             if (proc != null) {
10497                 mProcessList.fillInProcMemInfoLocked(proc, outState, clientTargetSdk);
10498             }
10499         }
10500     }
10501 
10502     @Override
getMemoryTrimLevel()10503     public int getMemoryTrimLevel() {
10504         enforceNotIsolatedCaller("getMyMemoryState");
10505         synchronized (this) {
10506             return mLastMemoryLevel;
10507         }
10508     }
10509 
10510     @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)10511     public void onShellCommand(FileDescriptor in, FileDescriptor out,
10512             FileDescriptor err, String[] args, ShellCallback callback,
10513             ResultReceiver resultReceiver) {
10514         (new ActivityManagerShellCommand(this, false)).exec(
10515                 this, in, out, err, args, callback, resultReceiver);
10516     }
10517 
10518     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)10519     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
10520         PriorityDump.dump(mPriorityDumper, fd, pw, args);
10521     }
10522 
dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId, boolean dumpProxies)10523     private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti,
10524             boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority,
10525             int dumpAppId, boolean dumpProxies) {
10526 
10527         ActiveServices.ServiceDumper sdumper;
10528 
10529         synchronized(this) {
10530             mConstants.dump(pw);
10531             mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
10532             pw.println();
10533             if (dumpAll) {
10534                 pw.println("-------------------------------------------------------------------------------");
10535 
10536             }
10537             dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
10538             pw.println();
10539             if (dumpAll) {
10540                 pw.println("-------------------------------------------------------------------------------");
10541 
10542             }
10543             mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage);
10544             pw.println();
10545             if (dumpAll) {
10546                 pw.println("-------------------------------------------------------------------------------");
10547             }
10548             dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
10549             pw.println();
10550             if (dumpAll) {
10551                 pw.println("-------------------------------------------------------------------------------");
10552             }
10553             if (dumpAll || dumpPackage != null) {
10554                 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
10555                 pw.println();
10556                 if (dumpAll) {
10557                     pw.println("-------------------------------------------------------------------------------");
10558                 }
10559             }
10560             dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
10561             pw.println();
10562             if (dumpAll) {
10563                 pw.println("-------------------------------------------------------------------------------");
10564             }
10565             dumpPermissionsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
10566             pw.println();
10567             sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage);
10568             if (!dumpClient) {
10569                 if (dumpAll) {
10570                     pw.println("-------------------------------------------------------------------------------");
10571                 }
10572                 sdumper.dumpLocked();
10573             }
10574         }
10575         // We drop the lock here because we can't call dumpWithClient() with the lock held;
10576         // if the caller wants a consistent state for the !dumpClient case, it can call this
10577         // method with the lock held.
10578         if (dumpClient) {
10579             if (dumpAll) {
10580                 pw.println("-------------------------------------------------------------------------------");
10581             }
10582             sdumper.dumpWithClient();
10583         }
10584         if (dumpPackage == null && dumpProxies) {
10585             // Intentionally dropping the lock for this, because dumpBinderProxies() will make many
10586             // outgoing binder calls to retrieve interface descriptors; while that is system code,
10587             // there is nothing preventing an app from overriding this implementation by talking to
10588             // the binder driver directly, and hang up system_server in the process. So, dump
10589             // without locks held, and even then only when there is an unreasonably large number of
10590             // proxies in the first place.
10591             pw.println();
10592             if (dumpAll) {
10593                 pw.println("-------------------------------------------------------------------------------");
10594             }
10595             dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */);
10596         }
10597         synchronized(this) {
10598             pw.println();
10599             if (dumpAll) {
10600                 pw.println("-------------------------------------------------------------------------------");
10601             }
10602             mAtmInternal.dump(
10603                     DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
10604             pw.println();
10605             if (dumpAll) {
10606                 pw.println("-------------------------------------------------------------------------------");
10607             }
10608             mAtmInternal.dump(
10609                     DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
10610             pw.println();
10611             if (dumpAll) {
10612                 pw.println("-------------------------------------------------------------------------------");
10613             }
10614             mAtmInternal.dump(
10615                     DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
10616             if (dumpPackage == null) {
10617                 pw.println();
10618                 if (dumpAll) {
10619                     pw.println("-------------------------------------------------------------------------------");
10620                 }
10621                 mAtmInternal.dump(
10622                         DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
10623             }
10624             // Activities section is dumped as part of the Critical priority dump. Exclude the
10625             // section if priority is Normal.
10626             if (!dumpNormalPriority) {
10627                 pw.println();
10628                 if (dumpAll) {
10629                     pw.println("-------------------------------------------------------------------------------");
10630                 }
10631                 mAtmInternal.dump(
10632                         DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
10633             }
10634             if (mAssociations.size() > 0) {
10635                 pw.println();
10636                 if (dumpAll) {
10637                     pw.println("-------------------------------------------------------------------------------");
10638                 }
10639                 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
10640             }
10641             pw.println();
10642             if (dumpAll) {
10643                 pw.println("-------------------------------------------------------------------------------");
10644             }
10645             mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
10646             if (dumpPackage == null) {
10647                 pw.println();
10648                 if (dumpAll) {
10649                     pw.println("-------------------------------------------------------------------------------");
10650                 }
10651                 mOomAdjProfiler.dump(pw);
10652                 pw.println();
10653                 if (dumpAll) {
10654                     pw.println("-------------------------------------------------------------------------------");
10655                 }
10656                 dumpLmkLocked(pw);
10657             }
10658             pw.println();
10659             if (dumpAll) {
10660                 pw.println("-------------------------------------------------------------------------------");
10661             }
10662             dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId);
10663             pw.println();
10664             if (dumpAll) {
10665                 pw.println("-------------------------------------------------------------------------------");
10666             }
10667             dumpUsersLocked(pw);
10668         }
10669     }
10670 
10671     /**
10672      * Wrapper function to print out debug data filtered by specified arguments.
10673     */
doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)10674     private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
10675         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
10676 
10677         boolean dumpAll = false;
10678         boolean dumpClient = false;
10679         boolean dumpCheckin = false;
10680         boolean dumpCheckinFormat = false;
10681         boolean dumpNormalPriority = false;
10682         boolean dumpVisibleStacksOnly = false;
10683         boolean dumpFocusedStackOnly = false;
10684         String dumpPackage = null;
10685 
10686         int opti = 0;
10687         while (opti < args.length) {
10688             String opt = args[opti];
10689             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10690                 break;
10691             }
10692             opti++;
10693             if ("-a".equals(opt)) {
10694                 dumpAll = true;
10695             } else if ("-c".equals(opt)) {
10696                 dumpClient = true;
10697             } else if ("-v".equals(opt)) {
10698                 dumpVisibleStacksOnly = true;
10699             } else if ("-f".equals(opt)) {
10700                 dumpFocusedStackOnly = true;
10701             } else if ("-p".equals(opt)) {
10702                 if (opti < args.length) {
10703                     dumpPackage = args[opti];
10704                     opti++;
10705                 } else {
10706                     pw.println("Error: -p option requires package argument");
10707                     return;
10708                 }
10709                 dumpClient = true;
10710             } else if ("--checkin".equals(opt)) {
10711                 dumpCheckin = dumpCheckinFormat = true;
10712             } else if ("-C".equals(opt)) {
10713                 dumpCheckinFormat = true;
10714             } else if ("--normal-priority".equals(opt)) {
10715                 dumpNormalPriority = true;
10716             } else if ("-h".equals(opt)) {
10717                 ActivityManagerShellCommand.dumpHelp(pw, true);
10718                 return;
10719             } else {
10720                 pw.println("Unknown argument: " + opt + "; use -h for help");
10721             }
10722         }
10723 
10724         long origId = Binder.clearCallingIdentity();
10725 
10726         if (useProto) {
10727             final ProtoOutputStream proto = new ProtoOutputStream(fd);
10728             String cmd = opti < args.length ? args[opti] : "";
10729             opti++;
10730 
10731             if ("activities".equals(cmd) || "a".equals(cmd)) {
10732                 // output proto is ActivityManagerServiceDumpActivitiesProto
10733                 mAtmInternal.writeActivitiesToProto(proto);
10734             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10735                 // output proto is ActivityManagerServiceDumpBroadcastsProto
10736                 synchronized (this) {
10737                     writeBroadcastsToProtoLocked(proto);
10738                 }
10739             } else if ("provider".equals(cmd)) {
10740                 String[] newArgs;
10741                 String name;
10742                 if (opti >= args.length) {
10743                     name = null;
10744                     newArgs = EMPTY_STRING_ARRAY;
10745                 } else {
10746                     name = args[opti];
10747                     opti++;
10748                     newArgs = new String[args.length - opti];
10749                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10750                             args.length - opti);
10751                 }
10752                 if (!dumpProviderProto(fd, pw, name, newArgs)) {
10753                     pw.println("No providers match: " + name);
10754                     pw.println("Use -h for help.");
10755                 }
10756             } else if ("service".equals(cmd)) {
10757                 // output proto is ActivityManagerServiceDumpServicesProto
10758                 mServices.dumpDebug(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10759             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10760                 if (opti < args.length) {
10761                     dumpPackage = args[opti];
10762                     opti++;
10763                 }
10764                 // output proto is ProcessProto
10765                 synchronized (this) {
10766                     writeProcessesToProtoLocked(proto, dumpPackage);
10767                 }
10768             } else {
10769                 // default option, dump everything, output is ActivityManagerServiceProto
10770                 synchronized (this) {
10771                     long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES);
10772                     mAtmInternal.writeActivitiesToProto(proto);
10773                     proto.end(activityToken);
10774 
10775                     long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS);
10776                     writeBroadcastsToProtoLocked(proto);
10777                     proto.end(broadcastToken);
10778 
10779                     long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES);
10780                     mServices.dumpDebug(proto,
10781                             ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10782                     proto.end(serviceToken);
10783 
10784                     long processToken = proto.start(ActivityManagerServiceProto.PROCESSES);
10785                     writeProcessesToProtoLocked(proto, dumpPackage);
10786                     proto.end(processToken);
10787                 }
10788             }
10789             proto.flush();
10790             Binder.restoreCallingIdentity(origId);
10791             return;
10792         }
10793 
10794         int dumpAppId = getAppId(dumpPackage);
10795         boolean more = false;
10796         // Is the caller requesting to dump a particular piece of data?
10797         if (opti < args.length) {
10798             String cmd = args[opti];
10799             opti++;
10800             if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
10801                     || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
10802                     || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
10803                     || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
10804                 mAtmInternal.dump(
10805                         cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage);
10806             } else if ("binder-proxies".equals(cmd)) {
10807                 if (opti >= args.length) {
10808                     dumpBinderProxies(pw, 0 /* minToDump */);
10809                 } else {
10810                     String uid = args[opti];
10811                     opti++;
10812                     // Ensure Binder Proxy Count is as up to date as possible
10813                     System.gc();
10814                     System.runFinalization();
10815                     System.gc();
10816                     pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid)));
10817                 }
10818             } else if ("allowed-associations".equals(cmd)) {
10819                 if (opti < args.length) {
10820                     dumpPackage = args[opti];
10821                     opti++;
10822                 }
10823                 synchronized (this) {
10824                     dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage);
10825                 }
10826             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10827                 if (opti < args.length) {
10828                     dumpPackage = args[opti];
10829                     opti++;
10830                 }
10831                 synchronized (this) {
10832                     dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage);
10833                 }
10834             } else if ("broadcast-stats".equals(cmd)) {
10835                 if (opti < args.length) {
10836                     dumpPackage = args[opti];
10837                     opti++;
10838                 }
10839                 synchronized (this) {
10840                     if (dumpCheckinFormat) {
10841                         dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
10842                                 dumpPackage);
10843                     } else {
10844                         dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
10845                     }
10846                 }
10847             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
10848                 if (opti < args.length) {
10849                     dumpPackage = args[opti];
10850                     opti++;
10851                 }
10852                 synchronized (this) {
10853                     mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage);
10854                 }
10855             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10856                 if (opti < args.length) {
10857                     dumpPackage = args[opti];
10858                     opti++;
10859                 }
10860                 synchronized (this) {
10861                     dumpProcessesLocked(fd, pw, args, opti, true, dumpPackage, dumpAppId);
10862                 }
10863             } else if ("oom".equals(cmd) || "o".equals(cmd)) {
10864                 synchronized (this) {
10865                     dumpOomLocked(fd, pw, false, args, opti, true, dumpPackage, true);
10866                 }
10867             } else if ("lmk".equals(cmd)) {
10868                 synchronized (this) {
10869                     dumpLmkLocked(pw);
10870                 }
10871             } else if ("lru".equals(cmd)) {
10872                 synchronized (this) {
10873                     dumpLruLocked(pw, dumpPackage, null);
10874                 }
10875             } else if ("permissions".equals(cmd) || "perm".equals(cmd)) {
10876                 synchronized (this) {
10877                     dumpPermissionsLocked(fd, pw, args, opti, true, dumpPackage);
10878                 }
10879             } else if ("provider".equals(cmd)) {
10880                 String[] newArgs;
10881                 String name;
10882                 if (opti >= args.length) {
10883                     name = null;
10884                     newArgs = EMPTY_STRING_ARRAY;
10885                 } else {
10886                     name = args[opti];
10887                     opti++;
10888                     newArgs = new String[args.length - opti];
10889                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
10890                 }
10891                 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
10892                     pw.println("No providers match: " + name);
10893                     pw.println("Use -h for help.");
10894                 }
10895             } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
10896                 synchronized (this) {
10897                     dumpProvidersLocked(fd, pw, args, opti, true, dumpPackage);
10898                 }
10899             } else if ("service".equals(cmd)) {
10900                 String[] newArgs;
10901                 String name;
10902                 if (opti >= args.length) {
10903                     name = null;
10904                     newArgs = EMPTY_STRING_ARRAY;
10905                 } else {
10906                     name = args[opti];
10907                     opti++;
10908                     newArgs = new String[args.length - opti];
10909                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10910                             args.length - opti);
10911                 }
10912                 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
10913                     pw.println("No services match: " + name);
10914                     pw.println("Use -h for help.");
10915                 }
10916             } else if ("package".equals(cmd)) {
10917                 String[] newArgs;
10918                 if (opti >= args.length) {
10919                     pw.println("package: no package name specified");
10920                     pw.println("Use -h for help.");
10921                 } else {
10922                     dumpPackage = args[opti];
10923                     opti++;
10924                     newArgs = new String[args.length - opti];
10925                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10926                             args.length - opti);
10927                     args = newArgs;
10928                     opti = 0;
10929                     more = true;
10930                 }
10931             } else if ("associations".equals(cmd) || "as".equals(cmd)) {
10932                 synchronized (this) {
10933                     dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage);
10934                 }
10935             } else if ("settings".equals(cmd)) {
10936                 synchronized (this) {
10937                     mConstants.dump(pw);
10938                     mOomAdjuster.dumpCachedAppOptimizerSettings(pw);
10939                 }
10940             } else if ("services".equals(cmd) || "s".equals(cmd)) {
10941                 if (dumpClient) {
10942                     ActiveServices.ServiceDumper dumper;
10943                     synchronized (this) {
10944                         dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10945                                 dumpPackage);
10946                     }
10947                     dumper.dumpWithClient();
10948                 } else {
10949                     synchronized (this) {
10950                         mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10951                                 dumpPackage).dumpLocked();
10952                     }
10953                 }
10954             } else if ("locks".equals(cmd)) {
10955                 LockGuard.dump(fd, pw, args);
10956             } else if ("users".equals(cmd)) {
10957                 synchronized (this) {
10958                     dumpUsersLocked(pw);
10959                 }
10960             } else if ("exit-info".equals(cmd)) {
10961                 if (opti < args.length) {
10962                     dumpPackage = args[opti];
10963                     opti++;
10964                 }
10965                 mProcessList.mAppExitInfoTracker.dumpHistoryProcessExitInfo(pw, dumpPackage);
10966             } else {
10967                 // Dumping a single activity?
10968                 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll,
10969                         dumpVisibleStacksOnly, dumpFocusedStackOnly)) {
10970                     ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true);
10971                     int res = shell.exec(this, null, fd, null, args, null,
10972                             new ResultReceiver(null));
10973                     if (res < 0) {
10974                         pw.println("Bad activity command, or no activities match: " + cmd);
10975                         pw.println("Use -h for help.");
10976                     }
10977                 }
10978             }
10979             if (!more) {
10980                 Binder.restoreCallingIdentity(origId);
10981                 return;
10982             }
10983         }
10984 
10985         // No piece of data specified, dump everything.
10986         if (dumpCheckinFormat) {
10987             dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage);
10988         } else {
10989             if (dumpClient) {
10990                 // dumpEverything() will take the lock when needed, and momentarily drop
10991                 // it for dumping client state.
10992                 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
10993                         dumpNormalPriority, dumpAppId, true /* dumpProxies */);
10994             } else {
10995                 // Take the lock here, so we get a consistent state for the entire dump;
10996                 // dumpEverything() will take the lock as well, which is fine for everything
10997                 // except dumping proxies, which can take a long time; exclude them.
10998                 synchronized(this) {
10999                     dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
11000                             dumpNormalPriority, dumpAppId, false /* dumpProxies */);
11001                 }
11002             }
11003         }
11004         Binder.restoreCallingIdentity(origId);
11005     }
11006 
dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)11007     void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11008             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
11009         pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)");
11010 
11011         int dumpUid = 0;
11012         if (dumpPackage != null) {
11013             IPackageManager pm = AppGlobals.getPackageManager();
11014             try {
11015                 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0);
11016             } catch (RemoteException e) {
11017             }
11018         }
11019 
11020         boolean printedAnything = false;
11021 
11022         final long now = SystemClock.uptimeMillis();
11023 
11024         for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
11025             ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
11026                     = mAssociations.valueAt(i1);
11027             for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
11028                 SparseArray<ArrayMap<String, Association>> sourceUids
11029                         = targetComponents.valueAt(i2);
11030                 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) {
11031                     ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3);
11032                     for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
11033                         Association ass = sourceProcesses.valueAt(i4);
11034                         if (dumpPackage != null) {
11035                             if (!ass.mTargetComponent.getPackageName().equals(dumpPackage)
11036                                     && UserHandle.getAppId(ass.mSourceUid) != dumpUid) {
11037                                 continue;
11038                             }
11039                         }
11040                         printedAnything = true;
11041                         pw.print("  ");
11042                         pw.print(ass.mTargetProcess);
11043                         pw.print("/");
11044                         UserHandle.formatUid(pw, ass.mTargetUid);
11045                         pw.print(" <- ");
11046                         pw.print(ass.mSourceProcess);
11047                         pw.print("/");
11048                         UserHandle.formatUid(pw, ass.mSourceUid);
11049                         pw.println();
11050                         pw.print("    via ");
11051                         pw.print(ass.mTargetComponent.flattenToShortString());
11052                         pw.println();
11053                         pw.print("    ");
11054                         long dur = ass.mTime;
11055                         if (ass.mNesting > 0) {
11056                             dur += now - ass.mStartTime;
11057                         }
11058                         TimeUtils.formatDuration(dur, pw);
11059                         pw.print(" (");
11060                         pw.print(ass.mCount);
11061                         pw.print(" times)");
11062                         pw.print("  ");
11063                         for (int i=0; i<ass.mStateTimes.length; i++) {
11064                             long amt = ass.mStateTimes[i];
11065                             if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
11066                                 amt += now - ass.mLastStateUptime;
11067                             }
11068                             if (amt != 0) {
11069                                 pw.print(" ");
11070                                 pw.print(ProcessList.makeProcStateString(
11071                                             i + ActivityManager.MIN_PROCESS_STATE));
11072                                 pw.print("=");
11073                                 TimeUtils.formatDuration(amt, pw);
11074                                 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
11075                                     pw.print("*");
11076                                 }
11077                             }
11078                         }
11079                         pw.println();
11080                         if (ass.mNesting > 0) {
11081                             pw.print("    Currently active: ");
11082                             TimeUtils.formatDuration(now - ass.mStartTime, pw);
11083                             pw.println();
11084                         }
11085                     }
11086                 }
11087             }
11088 
11089         }
11090 
11091         if (!printedAnything) {
11092             pw.println("  (nothing)");
11093         }
11094     }
11095 
getAppId(String dumpPackage)11096     private int getAppId(String dumpPackage) {
11097         if (dumpPackage != null) {
11098             try {
11099                 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
11100                         dumpPackage, 0);
11101                 return UserHandle.getAppId(info.uid);
11102             } catch (NameNotFoundException e) {
11103                 e.printStackTrace();
11104             }
11105         }
11106         return -1;
11107     }
11108 
dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids, String header, boolean needSep)11109     boolean dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids,
11110                 String header, boolean needSep) {
11111         boolean printed = false;
11112         for (int i=0; i<uids.size(); i++) {
11113             UidRecord uidRec = uids.valueAt(i);
11114             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != dumpAppId) {
11115                 continue;
11116             }
11117             if (!printed) {
11118                 printed = true;
11119                 if (needSep) {
11120                     pw.println();
11121                 }
11122                 pw.print("  ");
11123                 pw.println(header);
11124                 needSep = true;
11125             }
11126             pw.print("    UID "); UserHandle.formatUid(pw, uidRec.uid);
11127             pw.print(": "); pw.println(uidRec);
11128             pw.print("      curProcState="); pw.print(uidRec.mCurProcState);
11129             pw.print(" curCapability=");
11130             ActivityManager.printCapabilitiesFull(pw, uidRec.curCapability);
11131             pw.println();
11132             for (int j = uidRec.procRecords.size() - 1; j >= 0; j--) {
11133                 pw.print("      proc=");
11134                 pw.println(uidRec.procRecords.valueAt(j));
11135             }
11136         }
11137         return printed;
11138     }
11139 
dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)11140     void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) {
11141         final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50);
11142 
11143         pw.println(header);
11144         for (int i = 0; i < proxyCounts.length; i++) {
11145             pw.println("    #" + (i + 1) + ": " + proxyCounts[i]);
11146         }
11147     }
11148 
dumpBinderProxiesCounts(PrintWriter pw, String header)11149     boolean dumpBinderProxiesCounts(PrintWriter pw, String header) {
11150         SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
11151         if(counts != null) {
11152             pw.println(header);
11153             for (int i = 0; i < counts.size(); i++) {
11154                 final int uid = counts.keyAt(i);
11155                 final int binderCount = counts.valueAt(i);
11156                 pw.print("    UID ");
11157                 pw.print(uid);
11158                 pw.print(", binder count = ");
11159                 pw.print(binderCount);
11160                 pw.print(", package(s)= ");
11161                 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid);
11162                 if (pkgNames != null) {
11163                     for (int j = 0; j < pkgNames.length; j++) {
11164                         pw.print(pkgNames[j]);
11165                         pw.print("; ");
11166                     }
11167                 } else {
11168                     pw.print("NO PACKAGE NAME FOUND");
11169                 }
11170                 pw.println();
11171             }
11172             return true;
11173         }
11174         return false;
11175     }
11176 
dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)11177     void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) {
11178         pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)");
11179         final int proxyCount = BinderProxy.getProxyCount();
11180         if (proxyCount >= minCountToDumpInterfaces) {
11181             dumpBinderProxyInterfaceCounts(pw,
11182                     "Top proxy interface names held by SYSTEM");
11183         } else {
11184             pw.print("Not dumping proxy interface counts because size ("
11185                     + Integer.toString(proxyCount) + ") looks reasonable");
11186             pw.println();
11187         }
11188         dumpBinderProxiesCounts(pw,
11189                 "  Counts of Binder Proxies held by SYSTEM");
11190     }
11191 
dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc, String prefix)11192     void dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc, String prefix) {
11193         pw.print(prefix);
11194         pw.print('#');
11195         if (index < 10) {
11196             pw.print(' ');
11197         }
11198         pw.print(index);
11199         pw.print(": ");
11200         pw.print(ProcessList.makeOomAdjString(proc.setAdj, false));
11201         pw.print(' ');
11202         pw.print(ProcessList.makeProcStateString(proc.getCurProcState()));
11203         pw.print(' ');
11204         ActivityManager.printCapabilitiesSummary(pw, proc.curCapability);
11205         pw.print(' ');
11206         pw.print(proc.toShortString());
11207         if (proc.hasActivitiesOrRecentTasks() || proc.hasClientActivities()
11208                 || proc.treatLikeActivity) {
11209             pw.print(" act:");
11210             boolean printed = false;
11211             if (proc.hasActivities()) {
11212                 pw.print("activities");
11213                 printed = true;
11214             }
11215             if (proc.hasRecentTasks()) {
11216                 if (printed) {
11217                     pw.print("|");
11218                 }
11219                 pw.print("recents");
11220                 printed = true;
11221             }
11222             if (proc.hasClientActivities()) {
11223                 if (printed) {
11224                     pw.print("|");
11225                 }
11226                 pw.print("client");
11227                 printed = true;
11228             }
11229             if (proc.treatLikeActivity) {
11230                 if (printed) {
11231                     pw.print("|");
11232                 }
11233                 pw.print("treated");
11234             }
11235         }
11236         pw.println();
11237     }
11238 
11239     // TODO: Move to ProcessList?
dumpLruLocked(PrintWriter pw, String dumpPackage, String prefix)11240     boolean dumpLruLocked(PrintWriter pw, String dumpPackage, String prefix) {
11241         final int N = mProcessList.mLruProcesses.size();
11242         final String innerPrefix;
11243         if (prefix == null) {
11244             pw.println("ACTIVITY MANAGER LRU PROCESSES (dumpsys activity lru)");
11245             innerPrefix = "  ";
11246         } else {
11247             boolean haveAny = false;
11248             for (int i = N - 1; i >= 0; i--) {
11249                 final ProcessRecord r = mProcessList.mLruProcesses.get(i);
11250                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11251                     continue;
11252                 }
11253                 haveAny = true;
11254                 break;
11255             }
11256             if (!haveAny) {
11257                 return false;
11258             }
11259             pw.print(prefix);
11260             pw.println("Raw LRU list (dumpsys activity lru):");
11261             innerPrefix = prefix + "  ";
11262         }
11263         int i;
11264         boolean first = true;
11265         for (i = N - 1; i >= mProcessList.mLruProcessActivityStart; i--) {
11266             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
11267             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11268                 continue;
11269             }
11270             if (first) {
11271                 pw.print(innerPrefix);
11272                 pw.println("Activities:");
11273                 first = false;
11274             }
11275             dumpLruEntryLocked(pw, i, r, innerPrefix);
11276         }
11277         first = true;
11278         for (; i >= mProcessList.mLruProcessServiceStart; i--) {
11279             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
11280             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11281                 continue;
11282             }
11283             if (first) {
11284                 pw.print(innerPrefix);
11285                 pw.println("Services:");
11286                 first = false;
11287             }
11288             dumpLruEntryLocked(pw, i, r, innerPrefix);
11289         }
11290         first = true;
11291         for (; i >= 0; i--) {
11292             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
11293             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11294                 continue;
11295             }
11296             if (first) {
11297                 pw.print(innerPrefix);
11298                 pw.println("Other:");
11299                 first = false;
11300             }
11301             dumpLruEntryLocked(pw, i, r, innerPrefix);
11302         }
11303         return true;
11304     }
11305 
11306     // TODO: Move to ProcessList?
11307     @GuardedBy("this")
dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int dumpAppId)11308     void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11309             int opti, boolean dumpAll, String dumpPackage, int dumpAppId) {
11310         boolean needSep = false;
11311         int numPers = 0;
11312 
11313         pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
11314 
11315         if (dumpAll || dumpPackage != null) {
11316             final int NP = mProcessList.mProcessNames.getMap().size();
11317             for (int ip=0; ip<NP; ip++) {
11318                 SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip);
11319                 final int NA = procs.size();
11320                 for (int ia=0; ia<NA; ia++) {
11321                     ProcessRecord r = procs.valueAt(ia);
11322                     if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11323                         continue;
11324                     }
11325                     if (!needSep) {
11326                         pw.println("  All known processes:");
11327                         needSep = true;
11328                     }
11329                     pw.print(r.isPersistent() ? "  *PERS*" : "  *APP*");
11330                         pw.print(" UID "); pw.print(procs.keyAt(ia));
11331                         pw.print(" "); pw.println(r);
11332                     r.dump(pw, "    ");
11333                     if (r.isPersistent()) {
11334                         numPers++;
11335                     }
11336                 }
11337             }
11338         }
11339 
11340         if (mProcessList.mIsolatedProcesses.size() > 0) {
11341             boolean printed = false;
11342             for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) {
11343                 ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i);
11344                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11345                     continue;
11346                 }
11347                 if (!printed) {
11348                     if (needSep) {
11349                         pw.println();
11350                     }
11351                     pw.println("  Isolated process list (sorted by uid):");
11352                     printed = true;
11353                     needSep = true;
11354                 }
11355                 pw.print("    Isolated #"); pw.print(i); pw.print(": ");
11356                 pw.println(r);
11357             }
11358         }
11359 
11360         if (mActiveInstrumentation.size() > 0) {
11361             boolean printed = false;
11362             for (int i=0; i<mActiveInstrumentation.size(); i++) {
11363                 ActiveInstrumentation ai = mActiveInstrumentation.get(i);
11364                 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
11365                         && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
11366                     continue;
11367                 }
11368                 if (!printed) {
11369                     if (needSep) {
11370                         pw.println();
11371                     }
11372                     pw.println("  Active instrumentation:");
11373                     printed = true;
11374                     needSep = true;
11375                 }
11376                 pw.print("    Instrumentation #"); pw.print(i); pw.print(": ");
11377                 pw.println(ai);
11378                 ai.dump(pw, "      ");
11379             }
11380         }
11381 
11382         if (dumpOomLocked(fd, pw, needSep, args, opti, dumpAll, dumpPackage, false)) {
11383             needSep = true;
11384         }
11385 
11386         needSep = dumpProcessesToGc(pw, needSep, dumpPackage);
11387 
11388         if (mProcessList.mActiveUids.size() > 0) {
11389             if (dumpUids(pw, dumpPackage, dumpAppId, mProcessList.mActiveUids,
11390                     "UID states:", needSep)) {
11391                 needSep = true;
11392             }
11393         }
11394 
11395         if (dumpAll) {
11396             if (mValidateUids.size() > 0) {
11397                 if (dumpUids(pw, dumpPackage, dumpAppId, mValidateUids, "UID validation:",
11398                         needSep)) {
11399                     needSep = true;
11400                 }
11401             }
11402         }
11403 
11404         if (needSep) {
11405             pw.println();
11406         }
11407         if (dumpLruLocked(pw, dumpPackage, "  ")) {
11408             needSep = true;
11409         }
11410 
11411         if (mProcessList.getLruSizeLocked() > 0) {
11412             if (needSep) {
11413                 pw.println();
11414             }
11415             mProcessList.dumpLruListHeaderLocked(pw);
11416             dumpProcessOomList(pw, this, mProcessList.mLruProcesses, "    ", "Proc", "PERS", false,
11417                     dumpPackage);
11418             needSep = true;
11419         }
11420 
11421         if (dumpAll || dumpPackage != null) {
11422             final SparseArray<ProcessRecord> pidToProcess = new SparseArray<>();
11423             synchronized (mPidsSelfLocked) {
11424                 boolean printed = false;
11425                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
11426                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
11427                     pidToProcess.put(r.pid, r);
11428                     if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11429                         continue;
11430                     }
11431                     if (!printed) {
11432                         if (needSep) pw.println();
11433                         needSep = true;
11434                         pw.println("  PID mappings:");
11435                         printed = true;
11436                     }
11437                     pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
11438                         pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
11439                 }
11440             }
11441 
11442             synchronized (sActiveProcessInfoSelfLocked) {
11443                 boolean printed = false;
11444                 for (int i = 0; i < sActiveProcessInfoSelfLocked.size(); i++) {
11445                     ProcessInfo info = sActiveProcessInfoSelfLocked.valueAt(i);
11446                     ProcessRecord r = pidToProcess.get(sActiveProcessInfoSelfLocked.keyAt(i));
11447                     if (r != null && dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11448                         continue;
11449                     }
11450                     if (!printed) {
11451                         if (needSep) pw.println();
11452                         needSep = true;
11453                         pw.println("  Active process infos:");
11454                         printed = true;
11455                     }
11456                     pw.print("    Pinfo PID #"); pw.print(sActiveProcessInfoSelfLocked.keyAt(i));
11457                     pw.println(":");
11458                     pw.print("      name="); pw.println(info.name);
11459                     if (info.deniedPermissions != null) {
11460                         for (int j = 0; j < info.deniedPermissions.size(); j++) {
11461                             pw.print("      deny: ");
11462                             pw.println(info.deniedPermissions.valueAt(i));
11463                         }
11464                     }
11465                 }
11466             }
11467         }
11468 
11469         if (mImportantProcesses.size() > 0) {
11470             synchronized (mPidsSelfLocked) {
11471                 boolean printed = false;
11472                 for (int i = 0; i< mImportantProcesses.size(); i++) {
11473                     ProcessRecord r = mPidsSelfLocked.get(
11474                             mImportantProcesses.valueAt(i).pid);
11475                     if (dumpPackage != null && (r == null
11476                             || !r.pkgList.containsKey(dumpPackage))) {
11477                         continue;
11478                     }
11479                     if (!printed) {
11480                         if (needSep) pw.println();
11481                         needSep = true;
11482                         pw.println("  Foreground Processes:");
11483                         printed = true;
11484                     }
11485                     pw.print("    PID #"); pw.print(mImportantProcesses.keyAt(i));
11486                             pw.print(": "); pw.println(mImportantProcesses.valueAt(i));
11487                 }
11488             }
11489         }
11490 
11491         if (mPersistentStartingProcesses.size() > 0) {
11492             if (needSep) pw.println();
11493             needSep = true;
11494             pw.println("  Persisent processes that are starting:");
11495             dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
11496                     "Starting Norm", "Restarting PERS", dumpPackage);
11497         }
11498 
11499         if (mProcessList.mRemovedProcesses.size() > 0) {
11500             if (needSep) pw.println();
11501             needSep = true;
11502             pw.println("  Processes that are being removed:");
11503             dumpProcessList(pw, this, mProcessList.mRemovedProcesses, "    ",
11504                     "Removed Norm", "Removed PERS", dumpPackage);
11505         }
11506 
11507         if (mProcessesOnHold.size() > 0) {
11508             if (needSep) pw.println();
11509             needSep = true;
11510             pw.println("  Processes that are on old until the system is ready:");
11511             dumpProcessList(pw, this, mProcessesOnHold, "    ",
11512                     "OnHold Norm", "OnHold PERS", dumpPackage);
11513         }
11514 
11515         needSep = mAppErrors.dumpLocked(fd, pw, needSep, dumpPackage);
11516 
11517         needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep,
11518                 mTestPssMode, mWakefulness);
11519 
11520         if (dumpAll && mProcessList.mPendingStarts.size() > 0) {
11521             if (needSep) pw.println();
11522             needSep = true;
11523             pw.println("  mPendingStarts: ");
11524             for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) {
11525                 pw.println("    " + mProcessList.mPendingStarts.keyAt(i) + ": "
11526                         + mProcessList.mPendingStarts.valueAt(i));
11527             }
11528         }
11529         if (dumpAll) {
11530             final int NI = mUidObservers.getRegisteredCallbackCount();
11531             boolean printed = false;
11532             for (int i=0; i<NI; i++) {
11533                 final UidObserverRegistration reg = (UidObserverRegistration)
11534                         mUidObservers.getRegisteredCallbackCookie(i);
11535                 if (dumpPackage == null || dumpPackage.equals(reg.pkg)) {
11536                     if (!printed) {
11537                         pw.println("  mUidObservers:");
11538                         printed = true;
11539                     }
11540                     pw.print("    "); UserHandle.formatUid(pw, reg.uid);
11541                     pw.print(" "); pw.print(reg.pkg);
11542                     final IUidObserver observer = mUidObservers.getRegisteredCallbackItem(i);
11543                     pw.print(" "); pw.print(observer.getClass().getTypeName()); pw.print(":");
11544                     if ((reg.which&ActivityManager.UID_OBSERVER_IDLE) != 0) {
11545                         pw.print(" IDLE");
11546                     }
11547                     if ((reg.which&ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
11548                         pw.print(" ACT" );
11549                     }
11550                     if ((reg.which&ActivityManager.UID_OBSERVER_GONE) != 0) {
11551                         pw.print(" GONE");
11552                     }
11553                     if ((reg.which&ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
11554                         pw.print(" STATE");
11555                         pw.print(" (cut="); pw.print(reg.cutpoint);
11556                         pw.print(")");
11557                     }
11558                     pw.println();
11559                     if (reg.lastProcStates != null) {
11560                         final int NJ = reg.lastProcStates.size();
11561                         for (int j=0; j<NJ; j++) {
11562                             pw.print("      Last ");
11563                             UserHandle.formatUid(pw, reg.lastProcStates.keyAt(j));
11564                             pw.print(": "); pw.println(reg.lastProcStates.valueAt(j));
11565                         }
11566                     }
11567                 }
11568             }
11569             pw.println("  mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
11570             pw.println("  mDeviceIdleExceptIdleWhitelist="
11571                     + Arrays.toString(mDeviceIdleExceptIdleWhitelist));
11572             pw.println("  mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
11573             if (mPendingTempWhitelist.size() > 0) {
11574                 pw.println("  mPendingTempWhitelist:");
11575                 for (int i = 0; i < mPendingTempWhitelist.size(); i++) {
11576                     PendingTempWhitelist ptw = mPendingTempWhitelist.valueAt(i);
11577                     pw.print("    ");
11578                     UserHandle.formatUid(pw, ptw.targetUid);
11579                     pw.print(": ");
11580                     TimeUtils.formatDuration(ptw.duration, pw);
11581                     pw.print(" ");
11582                     pw.println(ptw.tag);
11583                 }
11584             }
11585         }
11586         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
11587                 || mOrigWaitForDebugger) {
11588             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
11589                     || dumpPackage.equals(mOrigDebugApp)) {
11590                 if (needSep) {
11591                     pw.println();
11592                     needSep = false;
11593                 }
11594                 pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
11595                         + " mDebugTransient=" + mDebugTransient
11596                         + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
11597             }
11598         }
11599         if (mMemWatchProcesses.getMap().size() > 0) {
11600             pw.println("  Mem watch processes:");
11601             final ArrayMap<String, SparseArray<Pair<Long, String>>> procs
11602                     = mMemWatchProcesses.getMap();
11603             for (int i=0; i<procs.size(); i++) {
11604                 final String proc = procs.keyAt(i);
11605                 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i);
11606                 for (int j=0; j<uids.size(); j++) {
11607                     if (needSep) {
11608                         pw.println();
11609                         needSep = false;
11610                     }
11611                     StringBuilder sb = new StringBuilder();
11612                     sb.append("    ").append(proc).append('/');
11613                     UserHandle.formatUid(sb, uids.keyAt(j));
11614                     Pair<Long, String> val = uids.valueAt(j);
11615                     sb.append(": "); DebugUtils.sizeValueToString(val.first, sb);
11616                     if (val.second != null) {
11617                         sb.append(", report to ").append(val.second);
11618                     }
11619                     pw.println(sb.toString());
11620                 }
11621             }
11622             pw.print("  mMemWatchDumpProcName="); pw.println(mMemWatchDumpProcName);
11623             pw.print("  mMemWatchDumpUri="); pw.println(mMemWatchDumpUri);
11624             pw.print("  mMemWatchDumpPid="); pw.println(mMemWatchDumpPid);
11625             pw.print("  mMemWatchDumpUid="); pw.println(mMemWatchDumpUid);
11626             pw.print("  mMemWatchIsUserInitiated="); pw.println(mMemWatchIsUserInitiated);
11627         }
11628         if (mTrackAllocationApp != null) {
11629             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
11630                 if (needSep) {
11631                     pw.println();
11632                     needSep = false;
11633                 }
11634                 pw.println("  mTrackAllocationApp=" + mTrackAllocationApp);
11635             }
11636         }
11637         if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null
11638                 || (mProfileData.getProfilerInfo() != null &&
11639                 (mProfileData.getProfilerInfo().profileFile != null
11640                         || mProfileData.getProfilerInfo().profileFd != null))) {
11641             if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) {
11642                 if (needSep) {
11643                     pw.println();
11644                     needSep = false;
11645                 }
11646                 pw.println("  mProfileApp=" + mProfileData.getProfileApp()
11647                         + " mProfileProc=" + mProfileData.getProfileProc());
11648                 if (mProfileData.getProfilerInfo() != null) {
11649                     pw.println("  mProfileFile=" + mProfileData.getProfilerInfo().profileFile
11650                             + " mProfileFd=" + mProfileData.getProfilerInfo().profileFd);
11651                     pw.println("  mSamplingInterval="
11652                             + mProfileData.getProfilerInfo().samplingInterval +
11653                             " mAutoStopProfiler="
11654                             + mProfileData.getProfilerInfo().autoStopProfiler +
11655                             " mStreamingOutput=" + mProfileData.getProfilerInfo().streamingOutput);
11656                     pw.println("  mProfileType=" + mProfileType);
11657                 }
11658             }
11659         }
11660         if (mNativeDebuggingApp != null) {
11661             if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
11662                 if (needSep) {
11663                     pw.println();
11664                     needSep = false;
11665                 }
11666                 pw.println("  mNativeDebuggingApp=" + mNativeDebuggingApp);
11667             }
11668         }
11669         if (dumpPackage == null) {
11670             if (mAlwaysFinishActivities) {
11671                 pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities);
11672             }
11673             if (dumpAll) {
11674                 pw.println("  Total persistent processes: " + numPers);
11675                 pw.println("  mProcessesReady=" + mProcessesReady
11676                         + " mSystemReady=" + mSystemReady
11677                         + " mBooted=" + mBooted
11678                         + " mFactoryTest=" + mFactoryTest);
11679                 pw.println("  mBooting=" + mBooting
11680                         + " mCallFinishBooting=" + mCallFinishBooting
11681                         + " mBootAnimationComplete=" + mBootAnimationComplete);
11682                 pw.print("  mLastPowerCheckUptime=");
11683                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
11684                         pw.println("");
11685                 mOomAdjuster.dumpSequenceNumbersLocked(pw);
11686                 mOomAdjuster.dumpProcCountsLocked(pw);
11687                 pw.println("  mAllowLowerMemLevel=" + mAllowLowerMemLevel
11688                         + " mLastMemoryLevel=" + mLastMemoryLevel
11689                         + " mLastNumProcesses=" + mLastNumProcesses);
11690                 long now = SystemClock.uptimeMillis();
11691                 pw.print("  mLastIdleTime=");
11692                         TimeUtils.formatDuration(now, mLastIdleTime, pw);
11693                         pw.print(" mLowRamSinceLastIdle=");
11694                         TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw);
11695                         pw.println();
11696                 pw.println();
11697                 pw.print("  mUidChangeDispatchCount=");
11698                 pw.print(mUidChangeDispatchCount);
11699                 pw.println();
11700 
11701                 pw.println("  Slow UID dispatches:");
11702                 final int N = mUidObservers.beginBroadcast();
11703                 for (int i = 0; i < N; i++) {
11704                     UidObserverRegistration r =
11705                             (UidObserverRegistration) mUidObservers.getBroadcastCookie(i);
11706                     pw.print("    ");
11707                     pw.print(mUidObservers.getBroadcastItem(i).getClass().getTypeName());
11708                     pw.print(": ");
11709                     pw.print(r.mSlowDispatchCount);
11710                     pw.print(" / Max ");
11711                     pw.print(r.mMaxDispatchTime);
11712                     pw.println("ms");
11713                 }
11714                 mUidObservers.finishBroadcast();
11715 
11716                 pw.println();
11717                 pw.println("  ServiceManager statistics:");
11718                 ServiceManager.sStatLogger.dump(pw, "    ");
11719                 pw.println();
11720             }
11721         }
11722         pw.println("  mForceBackgroundCheck=" + mForceBackgroundCheck);
11723     }
11724 
11725     @GuardedBy("this")
dumpUsersLocked(PrintWriter pw)11726     private void dumpUsersLocked(PrintWriter pw) {
11727         pw.println("ACTIVITY MANAGER USERS (dumpsys activity users)");
11728         mUserController.dump(pw);
11729     }
11730 
11731     @GuardedBy("this")
writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage)11732     void writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage) {
11733         int numPers = 0;
11734 
11735         final int NP = mProcessList.mProcessNames.getMap().size();
11736         for (int ip=0; ip<NP; ip++) {
11737             SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip);
11738             final int NA = procs.size();
11739             for (int ia = 0; ia<NA; ia++) {
11740                 ProcessRecord r = procs.valueAt(ia);
11741                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11742                     continue;
11743                 }
11744                 r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.PROCS,
11745                         mProcessList.mLruProcesses.indexOf(r)
11746                 );
11747                 if (r.isPersistent()) {
11748                     numPers++;
11749                 }
11750             }
11751         }
11752 
11753         for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) {
11754             ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i);
11755             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11756                 continue;
11757             }
11758             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ISOLATED_PROCS,
11759                     mProcessList.mLruProcesses.indexOf(r)
11760             );
11761         }
11762 
11763         for (int i=0; i<mActiveInstrumentation.size(); i++) {
11764             ActiveInstrumentation ai = mActiveInstrumentation.get(i);
11765             if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
11766                     && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
11767                 continue;
11768             }
11769             ai.dumpDebug(proto,
11770                     ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS);
11771         }
11772 
11773         int whichAppId = getAppId(dumpPackage);
11774         for (int i = 0; i < mProcessList.mActiveUids.size(); i++) {
11775             UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
11776             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) {
11777                 continue;
11778             }
11779             uidRec.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ACTIVE_UIDS);
11780         }
11781 
11782         for (int i = 0; i < mValidateUids.size(); i++) {
11783             UidRecord uidRec = mValidateUids.valueAt(i);
11784             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) {
11785                 continue;
11786             }
11787             uidRec.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS);
11788         }
11789 
11790         if (mProcessList.getLruSizeLocked() > 0) {
11791             long lruToken = proto.start(ActivityManagerServiceDumpProcessesProto.LRU_PROCS);
11792             int total = mProcessList.getLruSizeLocked();
11793             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.SIZE, total);
11794             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_ACT_AT,
11795                     total - mProcessList.mLruProcessActivityStart);
11796             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_SVC_AT,
11797                     total - mProcessList.mLruProcessServiceStart);
11798             writeProcessOomListToProto(proto,
11799                     ActivityManagerServiceDumpProcessesProto.LruProcesses.LIST, this,
11800                     mProcessList.mLruProcesses,false, dumpPackage);
11801             proto.end(lruToken);
11802         }
11803 
11804         if (dumpPackage != null) {
11805             synchronized (mPidsSelfLocked) {
11806                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
11807                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
11808                     if (!r.pkgList.containsKey(dumpPackage)) {
11809                         continue;
11810                     }
11811                     r.dumpDebug(proto,
11812                             ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED);
11813                 }
11814             }
11815         }
11816 
11817         if (mImportantProcesses.size() > 0) {
11818             synchronized (mPidsSelfLocked) {
11819                 for (int i=0; i<mImportantProcesses.size(); i++) {
11820                     ImportanceToken it = mImportantProcesses.valueAt(i);
11821                     ProcessRecord r = mPidsSelfLocked.get(it.pid);
11822                     if (dumpPackage != null && (r == null
11823                             || !r.pkgList.containsKey(dumpPackage))) {
11824                         continue;
11825                     }
11826                     it.dumpDebug(proto,
11827                             ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS);
11828                 }
11829             }
11830         }
11831 
11832         for (int i=0; i<mPersistentStartingProcesses.size(); i++) {
11833             ProcessRecord r = mPersistentStartingProcesses.get(i);
11834             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11835                 continue;
11836             }
11837             r.dumpDebug(proto,
11838                     ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS);
11839         }
11840 
11841         for (int i = 0; i < mProcessList.mRemovedProcesses.size(); i++) {
11842             ProcessRecord r = mProcessList.mRemovedProcesses.get(i);
11843             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11844                 continue;
11845             }
11846             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS);
11847         }
11848 
11849         for (int i=0; i<mProcessesOnHold.size(); i++) {
11850             ProcessRecord r = mProcessesOnHold.get(i);
11851             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11852                 continue;
11853             }
11854             r.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS);
11855         }
11856 
11857         writeProcessesToGcToProto(proto, ActivityManagerServiceDumpProcessesProto.GC_PROCS,
11858                 dumpPackage);
11859         mAppErrors.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS,
11860                 dumpPackage);
11861         mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness, mTestPssMode);
11862 
11863         if (dumpPackage == null) {
11864             mUserController.dumpDebug(proto,
11865             ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER);
11866         }
11867 
11868         final int NI = mUidObservers.getRegisteredCallbackCount();
11869         for (int i=0; i<NI; i++) {
11870             final UidObserverRegistration reg = (UidObserverRegistration)
11871                     mUidObservers.getRegisteredCallbackCookie(i);
11872             if (dumpPackage == null || dumpPackage.equals(reg.pkg)) {
11873                 reg.dumpDebug(proto, ActivityManagerServiceDumpProcessesProto.UID_OBSERVERS);
11874             }
11875         }
11876 
11877         for (int v : mDeviceIdleWhitelist) {
11878             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v);
11879         }
11880 
11881         for (int v : mDeviceIdleTempWhitelist) {
11882             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v);
11883         }
11884 
11885         if (mPendingTempWhitelist.size() > 0) {
11886             for (int i=0; i < mPendingTempWhitelist.size(); i++) {
11887                 mPendingTempWhitelist.valueAt(i).dumpDebug(proto,
11888                         ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST);
11889             }
11890         }
11891 
11892         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
11893                 || mOrigWaitForDebugger) {
11894             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
11895                     || dumpPackage.equals(mOrigDebugApp)) {
11896                 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG);
11897                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp);
11898                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp);
11899                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient);
11900                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger);
11901                 proto.end(debugAppToken);
11902             }
11903         }
11904 
11905         if (mMemWatchProcesses.getMap().size() > 0) {
11906             final long token = proto.start(ActivityManagerServiceDumpProcessesProto.MEM_WATCH_PROCESSES);
11907             ArrayMap<String, SparseArray<Pair<Long, String>>> procs = mMemWatchProcesses.getMap();
11908             for (int i=0; i<procs.size(); i++) {
11909                 final String proc = procs.keyAt(i);
11910                 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i);
11911                 final long ptoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.PROCS);
11912                 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.NAME, proc);
11913                 for (int j=0; j<uids.size(); j++) {
11914                     final long utoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MEM_STATS);
11915                     Pair<Long, String> val = uids.valueAt(j);
11916                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.UID, uids.keyAt(j));
11917                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.SIZE,
11918                             DebugUtils.sizeValueToString(val.first, new StringBuilder()));
11919                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.REPORT_TO, val.second);
11920                     proto.end(utoken);
11921                 }
11922                 proto.end(ptoken);
11923             }
11924 
11925             final long dtoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.DUMP);
11926             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PROC_NAME,
11927                     mMemWatchDumpProcName);
11928             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.URI,
11929                     mMemWatchDumpUri.toString());
11930             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PID,
11931                     mMemWatchDumpPid);
11932             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.UID,
11933                     mMemWatchDumpUid);
11934             proto.write(
11935                     ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.IS_USER_INITIATED,
11936                     mMemWatchIsUserInitiated);
11937             proto.end(dtoken);
11938 
11939             proto.end(token);
11940         }
11941 
11942         if (mTrackAllocationApp != null) {
11943             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
11944                 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP,
11945                         mTrackAllocationApp);
11946             }
11947         }
11948 
11949         if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null
11950                 || (mProfileData.getProfilerInfo() != null &&
11951                 (mProfileData.getProfilerInfo().profileFile != null
11952                         || mProfileData.getProfilerInfo().profileFd != null))) {
11953             if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) {
11954                 final long token = proto.start(ActivityManagerServiceDumpProcessesProto.PROFILE);
11955                 proto.write(ActivityManagerServiceDumpProcessesProto.Profile.APP_NAME,
11956                         mProfileData.getProfileApp());
11957                 mProfileData.getProfileProc().dumpDebug(proto,
11958                         ActivityManagerServiceDumpProcessesProto.Profile.PROC);
11959                 if (mProfileData.getProfilerInfo() != null) {
11960                     mProfileData.getProfilerInfo().dumpDebug(proto,
11961                             ActivityManagerServiceDumpProcessesProto.Profile.INFO);
11962                     proto.write(ActivityManagerServiceDumpProcessesProto.Profile.TYPE,
11963                             mProfileType);
11964                 }
11965                 proto.end(token);
11966             }
11967         }
11968 
11969         if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
11970             proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp);
11971         }
11972 
11973         if (dumpPackage == null) {
11974             proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities);
11975             proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers);
11976             proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady);
11977             proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady);
11978             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted);
11979             proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest);
11980             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting);
11981             proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting);
11982             proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete);
11983             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime);
11984             mOomAdjuster.dumpProcessListVariablesLocked(proto);
11985             proto.write(ActivityManagerServiceDumpProcessesProto.ALLOW_LOWER_MEM_LEVEL, mAllowLowerMemLevel);
11986             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_MEMORY_LEVEL, mLastMemoryLevel);
11987             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_NUM_PROCESSES, mLastNumProcesses);
11988             long now = SystemClock.uptimeMillis();
11989             ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now);
11990             proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, getLowRamTimeSinceIdle(now));
11991         }
11992     }
11993 
writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage)11994     void writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage) {
11995         if (mProcessesToGc.size() > 0) {
11996             long now = SystemClock.uptimeMillis();
11997             for (int i=0; i<mProcessesToGc.size(); i++) {
11998                 ProcessRecord r = mProcessesToGc.get(i);
11999                 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
12000                     continue;
12001                 }
12002                 final long token = proto.start(fieldId);
12003                 r.dumpDebug(proto, ProcessToGcProto.PROC);
12004                 proto.write(ProcessToGcProto.REPORT_LOW_MEMORY, r.reportLowMemory);
12005                 proto.write(ProcessToGcProto.NOW_UPTIME_MS, now);
12006                 proto.write(ProcessToGcProto.LAST_GCED_MS, r.lastRequestedGc);
12007                 proto.write(ProcessToGcProto.LAST_LOW_MEMORY_MS, r.lastLowMemory);
12008                 proto.end(token);
12009             }
12010         }
12011     }
12012 
dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage)12013     boolean dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage) {
12014         if (mProcessesToGc.size() > 0) {
12015             boolean printed = false;
12016             long now = SystemClock.uptimeMillis();
12017             for (int i=0; i<mProcessesToGc.size(); i++) {
12018                 ProcessRecord proc = mProcessesToGc.get(i);
12019                 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
12020                     continue;
12021                 }
12022                 if (!printed) {
12023                     if (needSep) pw.println();
12024                     needSep = true;
12025                     pw.println("  Processes that are waiting to GC:");
12026                     printed = true;
12027                 }
12028                 pw.print("    Process "); pw.println(proc);
12029                 pw.print("      lowMem="); pw.print(proc.reportLowMemory);
12030                         pw.print(", last gced=");
12031                         pw.print(now-proc.lastRequestedGc);
12032                         pw.print(" ms ago, last lowMem=");
12033                         pw.print(now-proc.lastLowMemory);
12034                         pw.println(" ms ago");
12035 
12036             }
12037         }
12038         return needSep;
12039     }
12040 
printOomLevel(PrintWriter pw, String name, int adj)12041     void printOomLevel(PrintWriter pw, String name, int adj) {
12042         pw.print("    ");
12043         if (adj >= 0) {
12044             pw.print(' ');
12045             if (adj < 10) pw.print(' ');
12046         } else {
12047             if (adj > -10) pw.print(' ');
12048         }
12049         pw.print(adj);
12050         pw.print(": ");
12051         pw.print(name);
12052         pw.print(" (");
12053         pw.print(stringifySize(mProcessList.getMemLevel(adj), 1024));
12054         pw.println(")");
12055     }
12056 
dumpOomLocked(FileDescriptor fd, PrintWriter pw, boolean needSep, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean inclGc)12057     boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, boolean needSep, String[] args,
12058             int opti, boolean dumpAll, String dumpPackage, boolean inclGc) {
12059         if (mProcessList.getLruSizeLocked() > 0) {
12060             if (needSep) pw.println();
12061             needSep = true;
12062             pw.println("  OOM levels:");
12063             printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ);
12064             printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ);
12065             printOomLevel(pw, "PERSISTENT_SERVICE_ADJ", ProcessList.PERSISTENT_SERVICE_ADJ);
12066             printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ);
12067             printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ);
12068             printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ);
12069             printOomLevel(pw, "PERCEPTIBLE_LOW_APP_ADJ", ProcessList.PERCEPTIBLE_LOW_APP_ADJ);
12070             printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ);
12071             printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ);
12072             printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ);
12073             printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ);
12074             printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ);
12075             printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ);
12076             printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ);
12077             printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ);
12078 
12079             if (needSep) pw.println();
12080             pw.print("  Process OOM control ("); pw.print(mProcessList.getLruSizeLocked());
12081                     pw.print(" total, non-act at ");
12082                     pw.print(mProcessList.getLruSizeLocked()
12083                             - mProcessList.mLruProcessActivityStart);
12084                     pw.print(", non-svc at ");
12085                     pw.print(mProcessList.getLruSizeLocked()
12086                             - mProcessList.mLruProcessServiceStart);
12087                     pw.println("):");
12088             dumpProcessOomList(pw, this, mProcessList.mLruProcesses, "    ", "Proc", "PERS", true,
12089                     dumpPackage);
12090             needSep = true;
12091         }
12092 
12093         dumpProcessesToGc(pw, needSep, dumpPackage);
12094 
12095         pw.println();
12096         mAtmInternal.dumpForOom(pw);
12097 
12098         return true;
12099     }
12100 
reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)12101     private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) {
12102         Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj);
12103         if (cnt != null) {
12104             pw.println("    kills at or below oom_adj " + oom_adj + ": " + cnt);
12105             return true;
12106         }
12107         return false;
12108     }
12109 
dumpLmkLocked(PrintWriter pw)12110     boolean dumpLmkLocked(PrintWriter pw) {
12111         pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)");
12112         Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ,
12113                 ProcessList.UNKNOWN_ADJ);
12114         if (cnt == null) {
12115             return false;
12116         }
12117         pw.println("  Total number of kills: " + cnt);
12118 
12119         return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) &&
12120                 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) &&
12121                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) &&
12122                 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) &&
12123                 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) &&
12124                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) &&
12125                 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) &&
12126                 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) &&
12127                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) &&
12128                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) &&
12129                 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) &&
12130                 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ);
12131     }
12132 
12133     /**
12134      * There are three ways to call this:
12135      *  - no provider specified: dump all the providers
12136      *  - a flattened component name that matched an existing provider was specified as the
12137      *    first arg: dump that one provider
12138      *  - the first arg isn't the flattened component name of an existing provider:
12139      *    dump all providers whose component contains the first arg as a substring
12140      */
dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)12141     protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
12142             int opti, boolean dumpAll) {
12143         return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
12144     }
12145 
12146     /**
12147      * Similar to the dumpProvider, but only dumps the first matching provider.
12148      * The provider is responsible for dumping as proto.
12149      */
dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, String[] args)12150     protected boolean dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name,
12151             String[] args) {
12152         return mProviderMap.dumpProviderProto(fd, pw, name, args);
12153     }
12154 
12155     public static class ItemMatcher {
12156         ArrayList<ComponentName> components;
12157         ArrayList<String> strings;
12158         ArrayList<Integer> objects;
12159         boolean all;
12160 
ItemMatcher()12161         public ItemMatcher() {
12162             all = true;
12163         }
12164 
build(String name)12165         public void build(String name) {
12166             ComponentName componentName = ComponentName.unflattenFromString(name);
12167             if (componentName != null) {
12168                 if (components == null) {
12169                     components = new ArrayList<ComponentName>();
12170                 }
12171                 components.add(componentName);
12172                 all = false;
12173             } else {
12174                 int objectId = 0;
12175                 // Not a '/' separated full component name; maybe an object ID?
12176                 try {
12177                     objectId = Integer.parseInt(name, 16);
12178                     if (objects == null) {
12179                         objects = new ArrayList<Integer>();
12180                     }
12181                     objects.add(objectId);
12182                     all = false;
12183                 } catch (RuntimeException e) {
12184                     // Not an integer; just do string match.
12185                     if (strings == null) {
12186                         strings = new ArrayList<String>();
12187                     }
12188                     strings.add(name);
12189                     all = false;
12190                 }
12191             }
12192         }
12193 
build(String[] args, int opti)12194         public int build(String[] args, int opti) {
12195             for (; opti<args.length; opti++) {
12196                 String name = args[opti];
12197                 if ("--".equals(name)) {
12198                     return opti+1;
12199                 }
12200                 build(name);
12201             }
12202             return opti;
12203         }
12204 
match(Object object, ComponentName comp)12205         public boolean match(Object object, ComponentName comp) {
12206             if (all) {
12207                 return true;
12208             }
12209             if (components != null) {
12210                 for (int i=0; i<components.size(); i++) {
12211                     if (components.get(i).equals(comp)) {
12212                         return true;
12213                     }
12214                 }
12215             }
12216             if (objects != null) {
12217                 for (int i=0; i<objects.size(); i++) {
12218                     if (System.identityHashCode(object) == objects.get(i)) {
12219                         return true;
12220                     }
12221                 }
12222             }
12223             if (strings != null) {
12224                 String flat = comp.flattenToString();
12225                 for (int i=0; i<strings.size(); i++) {
12226                     if (flat.contains(strings.get(i))) {
12227                         return true;
12228                     }
12229                 }
12230             }
12231             return false;
12232         }
12233     }
12234 
writeBroadcastsToProtoLocked(ProtoOutputStream proto)12235     void writeBroadcastsToProtoLocked(ProtoOutputStream proto) {
12236         if (mRegisteredReceivers.size() > 0) {
12237             Iterator it = mRegisteredReceivers.values().iterator();
12238             while (it.hasNext()) {
12239                 ReceiverList r = (ReceiverList)it.next();
12240                 r.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST);
12241             }
12242         }
12243         mReceiverResolver.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER);
12244         for (BroadcastQueue q : mBroadcastQueues) {
12245             q.dumpDebug(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE);
12246         }
12247         for (int user=0; user<mStickyBroadcasts.size(); user++) {
12248             long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS);
12249             proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user));
12250             for (Map.Entry<String, ArrayList<Intent>> ent
12251                     : mStickyBroadcasts.valueAt(user).entrySet()) {
12252                 long actionToken = proto.start(StickyBroadcastProto.ACTIONS);
12253                 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey());
12254                 for (Intent intent : ent.getValue()) {
12255                     intent.dumpDebug(proto, StickyBroadcastProto.StickyAction.INTENTS,
12256                             false, true, true, false);
12257                 }
12258                 proto.end(actionToken);
12259             }
12260             proto.end(token);
12261         }
12262 
12263         long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER);
12264         proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString());
12265         mHandler.getLooper().dumpDebug(proto,
12266             ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER);
12267         proto.end(handlerToken);
12268     }
12269 
dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12270     void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12271             int opti, boolean dumpAll, String dumpPackage) {
12272         pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)");
12273         boolean printed = false;
12274         if (mAllowedAssociations != null) {
12275             for (int i = 0; i < mAllowedAssociations.size(); i++) {
12276                 final String pkg = mAllowedAssociations.keyAt(i);
12277                 final ArraySet<String> asc =
12278                         mAllowedAssociations.valueAt(i).getAllowedPackageAssociations();
12279                 if (!printed) {
12280                     pw.println("  Allowed associations (by restricted package):");
12281                     printed = true;
12282                 }
12283                 pw.print("  * ");
12284                 pw.print(pkg);
12285                 pw.println(":");
12286                 for (int j = 0; j < asc.size(); j++) {
12287                     if (dumpPackage == null || pkg.equals(dumpPackage)
12288                             || asc.valueAt(j).equals(dumpPackage)) {
12289                         pw.print("      Allow: ");
12290                         pw.println(asc.valueAt(j));
12291                     }
12292                 }
12293                 if (mAllowedAssociations.valueAt(i).isDebuggable()) {
12294                     pw.println("      (debuggable)");
12295                 }
12296             }
12297         }
12298         if (!printed) {
12299             pw.println("  (No association restrictions)");
12300         }
12301     }
12302 
dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12303     void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12304             int opti, boolean dumpAll, String dumpPackage) {
12305         boolean needSep = false;
12306         boolean onlyHistory = false;
12307         boolean printedAnything = false;
12308 
12309         if ("history".equals(dumpPackage)) {
12310             if (opti < args.length && "-s".equals(args[opti])) {
12311                 dumpAll = false;
12312             }
12313             onlyHistory = true;
12314             dumpPackage = null;
12315         }
12316 
12317         pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
12318         if (!onlyHistory && dumpAll) {
12319             if (mRegisteredReceivers.size() > 0) {
12320                 boolean printed = false;
12321                 Iterator it = mRegisteredReceivers.values().iterator();
12322                 while (it.hasNext()) {
12323                     ReceiverList r = (ReceiverList)it.next();
12324                     if (dumpPackage != null && (r.app == null ||
12325                             !dumpPackage.equals(r.app.info.packageName))) {
12326                         continue;
12327                     }
12328                     if (!printed) {
12329                         pw.println("  Registered Receivers:");
12330                         needSep = true;
12331                         printed = true;
12332                         printedAnything = true;
12333                     }
12334                     pw.print("  * "); pw.println(r);
12335                     r.dump(pw, "    ");
12336                 }
12337             }
12338 
12339             if (mReceiverResolver.dump(pw, needSep ?
12340                     "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
12341                     "    ", dumpPackage, false, false)) {
12342                 needSep = true;
12343                 printedAnything = true;
12344             }
12345         }
12346 
12347         for (BroadcastQueue q : mBroadcastQueues) {
12348             needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
12349             printedAnything |= needSep;
12350         }
12351 
12352         needSep = true;
12353 
12354         if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
12355             for (int user=0; user<mStickyBroadcasts.size(); user++) {
12356                 if (needSep) {
12357                     pw.println();
12358                 }
12359                 needSep = true;
12360                 printedAnything = true;
12361                 pw.print("  Sticky broadcasts for user ");
12362                         pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
12363                 StringBuilder sb = new StringBuilder(128);
12364                 for (Map.Entry<String, ArrayList<Intent>> ent
12365                         : mStickyBroadcasts.valueAt(user).entrySet()) {
12366                     pw.print("  * Sticky action "); pw.print(ent.getKey());
12367                     if (dumpAll) {
12368                         pw.println(":");
12369                         ArrayList<Intent> intents = ent.getValue();
12370                         final int N = intents.size();
12371                         for (int i=0; i<N; i++) {
12372                             sb.setLength(0);
12373                             sb.append("    Intent: ");
12374                             intents.get(i).toShortString(sb, false, true, false, false);
12375                             pw.println(sb.toString());
12376                             Bundle bundle = intents.get(i).getExtras();
12377                             if (bundle != null) {
12378                                 pw.print("      ");
12379                                 pw.println(bundle.toString());
12380                             }
12381                         }
12382                     } else {
12383                         pw.println("");
12384                     }
12385                 }
12386             }
12387         }
12388 
12389         if (!onlyHistory && dumpAll) {
12390             pw.println();
12391             for (BroadcastQueue queue : mBroadcastQueues) {
12392                 pw.println("  mBroadcastsScheduled [" + queue.mQueueName + "]="
12393                         + queue.mBroadcastsScheduled);
12394             }
12395             pw.println("  mHandler:");
12396             mHandler.dump(new PrintWriterPrinter(pw), "    ");
12397             needSep = true;
12398             printedAnything = true;
12399         }
12400 
12401         if (!printedAnything) {
12402             pw.println("  (nothing)");
12403         }
12404     }
12405 
dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12406     void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12407             int opti, boolean dumpAll, String dumpPackage) {
12408         if (mCurBroadcastStats == null) {
12409             return;
12410         }
12411 
12412         pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)");
12413         final long now = SystemClock.elapsedRealtime();
12414         if (mLastBroadcastStats != null) {
12415             pw.print("  Last stats (from ");
12416             TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw);
12417             pw.print(" to ");
12418             TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw);
12419             pw.print(", ");
12420             TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime
12421                     - mLastBroadcastStats.mStartUptime, pw);
12422             pw.println(" uptime):");
12423             if (!mLastBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
12424                 pw.println("    (nothing)");
12425             }
12426             pw.println();
12427         }
12428         pw.print("  Current stats (from ");
12429         TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw);
12430         pw.print(" to now, ");
12431         TimeUtils.formatDuration(SystemClock.uptimeMillis()
12432                 - mCurBroadcastStats.mStartUptime, pw);
12433         pw.println(" uptime):");
12434         if (!mCurBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
12435             pw.println("    (nothing)");
12436         }
12437     }
12438 
dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)12439     void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12440             int opti, boolean fullCheckin, String dumpPackage) {
12441         if (mCurBroadcastStats == null) {
12442             return;
12443         }
12444 
12445         if (mLastBroadcastStats != null) {
12446             mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage);
12447             if (fullCheckin) {
12448                 mLastBroadcastStats = null;
12449                 return;
12450             }
12451         }
12452         mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage);
12453         if (fullCheckin) {
12454             mCurBroadcastStats = null;
12455         }
12456     }
12457 
dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12458     void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12459             int opti, boolean dumpAll, String dumpPackage) {
12460         boolean needSep;
12461         boolean printedAnything = false;
12462 
12463         ItemMatcher matcher = new ItemMatcher();
12464         matcher.build(args, opti);
12465 
12466         pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
12467 
12468         needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage);
12469         printedAnything |= needSep;
12470 
12471         if (mLaunchingProviders.size() > 0) {
12472             boolean printed = false;
12473             for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
12474                 ContentProviderRecord r = mLaunchingProviders.get(i);
12475                 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
12476                     continue;
12477                 }
12478                 if (!printed) {
12479                     if (needSep) pw.println();
12480                     needSep = true;
12481                     pw.println("  Launching content providers:");
12482                     printed = true;
12483                     printedAnything = true;
12484                 }
12485                 pw.print("  Launching #"); pw.print(i); pw.print(": ");
12486                         pw.println(r);
12487             }
12488         }
12489 
12490         if (!printedAnything) {
12491             pw.println("  (nothing)");
12492         }
12493     }
12494 
12495     @GuardedBy("this")
dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)12496     void dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12497             int opti, boolean dumpAll, String dumpPackage) {
12498 
12499         pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)");
12500 
12501         mUgmInternal.dump(pw, dumpAll, dumpPackage);
12502     }
12503 
dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)12504     private static final int dumpProcessList(PrintWriter pw,
12505             ActivityManagerService service, List list,
12506             String prefix, String normalLabel, String persistentLabel,
12507             String dumpPackage) {
12508         int numPers = 0;
12509         final int N = list.size()-1;
12510         for (int i=N; i>=0; i--) {
12511             ProcessRecord r = (ProcessRecord)list.get(i);
12512             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
12513                 continue;
12514             }
12515             pw.println(String.format("%s%s #%2d: %s",
12516                     prefix, (r.isPersistent() ? persistentLabel : normalLabel),
12517                     i, r.toString()));
12518             if (r.isPersistent()) {
12519                 numPers++;
12520             }
12521         }
12522         return numPers;
12523     }
12524 
12525     private static final ArrayList<Pair<ProcessRecord, Integer>>
sortProcessOomList(List<ProcessRecord> origList, String dumpPackage)12526         sortProcessOomList(List<ProcessRecord> origList, String dumpPackage) {
12527         ArrayList<Pair<ProcessRecord, Integer>> list
12528                 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
12529         for (int i=0; i<origList.size(); i++) {
12530             ProcessRecord r = origList.get(i);
12531             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
12532                 continue;
12533             }
12534             list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
12535         }
12536 
12537         Comparator<Pair<ProcessRecord, Integer>> comparator
12538                 = new Comparator<Pair<ProcessRecord, Integer>>() {
12539             @Override
12540             public int compare(Pair<ProcessRecord, Integer> object1,
12541                     Pair<ProcessRecord, Integer> object2) {
12542                 if (object1.first.setAdj != object2.first.setAdj) {
12543                     return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
12544                 }
12545                 if (object1.first.setProcState != object2.first.setProcState) {
12546                     return object1.first.setProcState > object2.first.setProcState ? -1 : 1;
12547                 }
12548                 if (object1.second.intValue() != object2.second.intValue()) {
12549                     return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
12550                 }
12551                 return 0;
12552             }
12553         };
12554 
12555         Collections.sort(list, comparator);
12556         return list;
12557     }
12558 
writeProcessOomListToProto(ProtoOutputStream proto, long fieldId, ActivityManagerService service, List<ProcessRecord> origList, boolean inclDetails, String dumpPackage)12559     private static final boolean writeProcessOomListToProto(ProtoOutputStream proto, long fieldId,
12560             ActivityManagerService service, List<ProcessRecord> origList,
12561             boolean inclDetails, String dumpPackage) {
12562         ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage);
12563         if (list.isEmpty()) return false;
12564 
12565         final long curUptime = SystemClock.uptimeMillis();
12566 
12567         for (int i = list.size() - 1; i >= 0; i--) {
12568             ProcessRecord r = list.get(i).first;
12569             long token = proto.start(fieldId);
12570             String oomAdj = ProcessList.makeOomAdjString(r.setAdj, true);
12571             proto.write(ProcessOomProto.PERSISTENT, r.isPersistent());
12572             proto.write(ProcessOomProto.NUM, (origList.size()-1)-list.get(i).second);
12573             proto.write(ProcessOomProto.OOM_ADJ, oomAdj);
12574             int schedGroup = ProcessOomProto.SCHED_GROUP_UNKNOWN;
12575             switch (r.setSchedGroup) {
12576                 case ProcessList.SCHED_GROUP_BACKGROUND:
12577                     schedGroup = ProcessOomProto.SCHED_GROUP_BACKGROUND;
12578                     break;
12579                 case ProcessList.SCHED_GROUP_DEFAULT:
12580                     schedGroup = ProcessOomProto.SCHED_GROUP_DEFAULT;
12581                     break;
12582                 case ProcessList.SCHED_GROUP_TOP_APP:
12583                     schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP;
12584                     break;
12585                 case ProcessList.SCHED_GROUP_TOP_APP_BOUND:
12586                     schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP_BOUND;
12587                     break;
12588             }
12589             if (schedGroup != ProcessOomProto.SCHED_GROUP_UNKNOWN) {
12590                 proto.write(ProcessOomProto.SCHED_GROUP, schedGroup);
12591             }
12592             if (r.hasForegroundActivities()) {
12593                 proto.write(ProcessOomProto.ACTIVITIES, true);
12594             } else if (r.hasForegroundServices()) {
12595                 proto.write(ProcessOomProto.SERVICES, true);
12596             }
12597             proto.write(ProcessOomProto.STATE,
12598                     ProcessList.makeProcStateProtoEnum(r.getCurProcState()));
12599             proto.write(ProcessOomProto.TRIM_MEMORY_LEVEL, r.trimMemoryLevel);
12600             r.dumpDebug(proto, ProcessOomProto.PROC);
12601             proto.write(ProcessOomProto.ADJ_TYPE, r.adjType);
12602             if (r.adjSource != null || r.adjTarget != null) {
12603                 if (r.adjTarget instanceof  ComponentName) {
12604                     ComponentName cn = (ComponentName) r.adjTarget;
12605                     cn.dumpDebug(proto, ProcessOomProto.ADJ_TARGET_COMPONENT_NAME);
12606                 } else if (r.adjTarget != null) {
12607                     proto.write(ProcessOomProto.ADJ_TARGET_OBJECT, r.adjTarget.toString());
12608                 }
12609                 if (r.adjSource instanceof ProcessRecord) {
12610                     ProcessRecord p = (ProcessRecord) r.adjSource;
12611                     p.dumpDebug(proto, ProcessOomProto.ADJ_SOURCE_PROC);
12612                 } else if (r.adjSource != null) {
12613                     proto.write(ProcessOomProto.ADJ_SOURCE_OBJECT, r.adjSource.toString());
12614                 }
12615             }
12616             if (inclDetails) {
12617                 long detailToken = proto.start(ProcessOomProto.DETAIL);
12618                 proto.write(ProcessOomProto.Detail.MAX_ADJ, r.maxAdj);
12619                 proto.write(ProcessOomProto.Detail.CUR_RAW_ADJ, r.getCurRawAdj());
12620                 proto.write(ProcessOomProto.Detail.SET_RAW_ADJ, r.setRawAdj);
12621                 proto.write(ProcessOomProto.Detail.CUR_ADJ, r.curAdj);
12622                 proto.write(ProcessOomProto.Detail.SET_ADJ, r.setAdj);
12623                 proto.write(ProcessOomProto.Detail.CURRENT_STATE,
12624                         ProcessList.makeProcStateProtoEnum(r.getCurProcState()));
12625                 proto.write(ProcessOomProto.Detail.SET_STATE,
12626                         ProcessList.makeProcStateProtoEnum(r.setProcState));
12627                 proto.write(ProcessOomProto.Detail.LAST_PSS, DebugUtils.sizeValueToString(
12628                         r.lastPss*1024, new StringBuilder()));
12629                 proto.write(ProcessOomProto.Detail.LAST_SWAP_PSS, DebugUtils.sizeValueToString(
12630                         r.lastSwapPss*1024, new StringBuilder()));
12631                 proto.write(ProcessOomProto.Detail.LAST_CACHED_PSS, DebugUtils.sizeValueToString(
12632                         r.lastCachedPss*1024, new StringBuilder()));
12633                 proto.write(ProcessOomProto.Detail.CACHED, r.isCached());
12634                 proto.write(ProcessOomProto.Detail.EMPTY, r.empty);
12635                 proto.write(ProcessOomProto.Detail.HAS_ABOVE_CLIENT, r.hasAboveClient);
12636 
12637                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
12638                     if (r.lastCpuTime != 0) {
12639                         long uptimeSince = curUptime - service.mLastPowerCheckUptime;
12640                         long timeUsed = r.curCpuTime - r.lastCpuTime;
12641                         long cpuTimeToken = proto.start(ProcessOomProto.Detail.SERVICE_RUN_TIME);
12642                         proto.write(ProcessOomProto.Detail.CpuRunTime.OVER_MS, uptimeSince);
12643                         proto.write(ProcessOomProto.Detail.CpuRunTime.USED_MS, timeUsed);
12644                         proto.write(ProcessOomProto.Detail.CpuRunTime.ULTILIZATION,
12645                                 (100.0*timeUsed)/uptimeSince);
12646                         proto.end(cpuTimeToken);
12647                     }
12648                 }
12649                 proto.end(detailToken);
12650             }
12651             proto.end(token);
12652         }
12653 
12654         return true;
12655     }
12656 
dumpProcessOomList(PrintWriter pw, ActivityManagerService service, List<ProcessRecord> origList, String prefix, String normalLabel, String persistentLabel, boolean inclDetails, String dumpPackage)12657     private static final boolean dumpProcessOomList(PrintWriter pw,
12658             ActivityManagerService service, List<ProcessRecord> origList,
12659             String prefix, String normalLabel, String persistentLabel,
12660             boolean inclDetails, String dumpPackage) {
12661 
12662         ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage);
12663         if (list.isEmpty()) return false;
12664 
12665         final long curUptime = SystemClock.uptimeMillis();
12666         final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
12667 
12668         for (int i=list.size()-1; i>=0; i--) {
12669             ProcessRecord r = list.get(i).first;
12670             String oomAdj = ProcessList.makeOomAdjString(r.setAdj, false);
12671             char schedGroup;
12672             switch (r.setSchedGroup) {
12673                 case ProcessList.SCHED_GROUP_BACKGROUND:
12674                     schedGroup = 'b';
12675                     break;
12676                 case ProcessList.SCHED_GROUP_DEFAULT:
12677                     schedGroup = 'F';
12678                     break;
12679                 case ProcessList.SCHED_GROUP_TOP_APP:
12680                     schedGroup = 'T';
12681                     break;
12682                 case ProcessList.SCHED_GROUP_RESTRICTED:
12683                     schedGroup = 'R';
12684                     break;
12685                 case ProcessList.SCHED_GROUP_TOP_APP_BOUND:
12686                     schedGroup = 'B';
12687                     break;
12688                 default:
12689                     schedGroup = '?';
12690                     break;
12691             }
12692             char foreground;
12693             if (r.hasForegroundActivities()) {
12694                 foreground = 'A';
12695             } else if (r.hasForegroundServices()) {
12696                 foreground = 'S';
12697             } else {
12698                 foreground = ' ';
12699             }
12700             String procState = ProcessList.makeProcStateString(r.getCurProcState());
12701             pw.print(prefix);
12702             pw.print(r.isPersistent() ? persistentLabel : normalLabel);
12703             pw.print(" #");
12704             int num = (origList.size()-1)-list.get(i).second;
12705             if (num < 10) pw.print(' ');
12706             pw.print(num);
12707             pw.print(": ");
12708             pw.print(oomAdj);
12709             pw.print(' ');
12710             pw.print(schedGroup);
12711             pw.print('/');
12712             pw.print(foreground);
12713             pw.print('/');
12714             pw.print(procState);
12715             pw.print(' ');
12716             ActivityManager.printCapabilitiesSummary(pw, r.curCapability);
12717             pw.print(' ');
12718             pw.print(" t:");
12719             if (r.trimMemoryLevel < 10) pw.print(' ');
12720             pw.print(r.trimMemoryLevel);
12721             pw.print(' ');
12722             pw.print(r.toShortString());
12723             pw.print(" (");
12724             pw.print(r.adjType);
12725             pw.println(')');
12726             if (r.adjSource != null || r.adjTarget != null) {
12727                 pw.print(prefix);
12728                 pw.print("    ");
12729                 if (r.adjTarget instanceof ComponentName) {
12730                     pw.print(((ComponentName)r.adjTarget).flattenToShortString());
12731                 } else if (r.adjTarget != null) {
12732                     pw.print(r.adjTarget.toString());
12733                 } else {
12734                     pw.print("{null}");
12735                 }
12736                 pw.print("<=");
12737                 if (r.adjSource instanceof ProcessRecord) {
12738                     pw.print("Proc{");
12739                     pw.print(((ProcessRecord)r.adjSource).toShortString());
12740                     pw.println("}");
12741                 } else if (r.adjSource != null) {
12742                     pw.println(r.adjSource.toString());
12743                 } else {
12744                     pw.println("{null}");
12745                 }
12746             }
12747             if (inclDetails) {
12748                 pw.print(prefix);
12749                 pw.print("    ");
12750                 pw.print("oom: max="); pw.print(r.maxAdj);
12751                 pw.print(" curRaw="); pw.print(r.getCurRawAdj());
12752                 pw.print(" setRaw="); pw.print(r.setRawAdj);
12753                 pw.print(" cur="); pw.print(r.curAdj);
12754                 pw.print(" set="); pw.println(r.setAdj);
12755                 pw.print(prefix);
12756                 pw.print("    ");
12757                 pw.print("state: cur="); pw.print(
12758                         ProcessList.makeProcStateString(r.getCurProcState()));
12759                 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState));
12760                 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, r.lastPss*1024);
12761                 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, r.lastSwapPss*1024);
12762                 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, r.lastCachedPss*1024);
12763                 pw.println();
12764                 pw.print(prefix);
12765                 pw.print("    ");
12766                 pw.print("cached="); pw.print(r.isCached());
12767                 pw.print(" empty="); pw.print(r.empty);
12768                 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
12769 
12770                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
12771                     if (r.lastCpuTime != 0) {
12772                         long timeUsed = r.curCpuTime - r.lastCpuTime;
12773                         pw.print(prefix);
12774                         pw.print("    ");
12775                         pw.print("run cpu over ");
12776                         TimeUtils.formatDuration(uptimeSince, pw);
12777                         pw.print(" used ");
12778                         TimeUtils.formatDuration(timeUsed, pw);
12779                         pw.print(" (");
12780                         pw.print((timeUsed*100)/uptimeSince);
12781                         pw.println("%)");
12782                     }
12783                 }
12784             }
12785         }
12786         return true;
12787     }
12788 
collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)12789     ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs,
12790             String[] args) {
12791         synchronized (this) {
12792             return mProcessList.collectProcessesLocked(start, allPkgs, args);
12793         }
12794     }
12795 
dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)12796     final void dumpGraphicsHardwareUsage(FileDescriptor fd,
12797             PrintWriter pw, String[] args) {
12798         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
12799         if (procs == null) {
12800             pw.println("No process found for: " + args[0]);
12801             return;
12802         }
12803 
12804         long uptime = SystemClock.uptimeMillis();
12805         long realtime = SystemClock.elapsedRealtime();
12806         pw.println("Applications Graphics Acceleration Info:");
12807         pw.println("Uptime: " + uptime + " Realtime: " + realtime);
12808 
12809         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12810             ProcessRecord r = procs.get(i);
12811             if (r.thread != null) {
12812                 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
12813                 pw.flush();
12814                 try {
12815                     TransferPipe tp = new TransferPipe();
12816                     try {
12817                         r.thread.dumpGfxInfo(tp.getWriteFd(), args);
12818                         tp.go(fd);
12819                     } finally {
12820                         tp.kill();
12821                     }
12822                 } catch (IOException e) {
12823                     pw.println("Failure while dumping the app: " + r);
12824                     pw.flush();
12825                 } catch (RemoteException e) {
12826                     pw.println("Got a RemoteException while dumping the app " + r);
12827                     pw.flush();
12828                 }
12829             }
12830         }
12831     }
12832 
dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args)12833     final void dumpBinderCacheContents(FileDescriptor fd, PrintWriter pw, String[] args) {
12834         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
12835         if (procs == null) {
12836             pw.println("No process found for: " + args[0]);
12837             return;
12838         }
12839 
12840         pw.println("Per-process Binder Cache Contents");
12841 
12842         for (int i = procs.size() - 1; i >= 0; i--) {
12843             ProcessRecord r = procs.get(i);
12844             if (r.thread != null) {
12845                 pw.println("\n\n** Cache info for pid " + r.pid + " [" + r.processName + "] **");
12846                 pw.flush();
12847                 if (r.pid == MY_PID) {
12848                     PropertyInvalidatedCache.dumpCacheInfo(fd, args);
12849                     continue;
12850                 }
12851                 try {
12852                     TransferPipe tp = new TransferPipe();
12853                     try {
12854                         r.thread.dumpCacheInfo(tp.getWriteFd(), args);
12855                         tp.go(fd);
12856                     } finally {
12857                         tp.kill();
12858                     }
12859                 } catch (IOException e) {
12860                     pw.println("Failure while dumping the app " + r);
12861                     pw.flush();
12862                 } catch (RemoteException e) {
12863                     pw.println("Got a RemoteException while dumping the app " + r);
12864                     pw.flush();
12865                 }
12866             }
12867         }
12868     }
12869 
dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)12870     final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
12871         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
12872         if (procs == null) {
12873             pw.println("No process found for: " + args[0]);
12874             return;
12875         }
12876 
12877         pw.println("Applications Database Info:");
12878 
12879         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12880             ProcessRecord r = procs.get(i);
12881             if (r.thread != null) {
12882                 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
12883                 pw.flush();
12884                 try {
12885                     TransferPipe tp = new TransferPipe();
12886                     try {
12887                         r.thread.dumpDbInfo(tp.getWriteFd(), args);
12888                         tp.go(fd);
12889                     } finally {
12890                         tp.kill();
12891                     }
12892                 } catch (IOException e) {
12893                     pw.println("Failure while dumping the app: " + r);
12894                     pw.flush();
12895                 } catch (RemoteException e) {
12896                     pw.println("Got a RemoteException while dumping the app " + r);
12897                     pw.flush();
12898                 }
12899             }
12900         }
12901     }
12902 
12903     final static class MemItem {
12904         final boolean isProc;
12905         final String label;
12906         final String shortLabel;
12907         final long pss;
12908         final long swapPss;
12909         final long mRss;
12910         final int id;
12911         final boolean hasActivities;
12912         ArrayList<MemItem> subitems;
12913 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id, boolean hasActivities)12914         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id,
12915                 boolean hasActivities) {
12916             this.isProc = true;
12917             this.label = label;
12918             this.shortLabel = shortLabel;
12919             this.pss = pss;
12920             this.swapPss = swapPss;
12921             this.mRss = rss;
12922             this.id = id;
12923             this.hasActivities = hasActivities;
12924         }
12925 
MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id)12926         MemItem(String label, String shortLabel, long pss, long swapPss, long rss, int id) {
12927             this.isProc = false;
12928             this.label = label;
12929             this.shortLabel = shortLabel;
12930             this.pss = pss;
12931             this.swapPss = swapPss;
12932             this.mRss = rss;
12933             this.id = id;
12934             this.hasActivities = false;
12935         }
12936     }
12937 
sortMemItems(List<MemItem> items, final boolean pss)12938     private static void sortMemItems(List<MemItem> items, final boolean pss) {
12939         Collections.sort(items, new Comparator<MemItem>() {
12940             @Override
12941             public int compare(MemItem lhs, MemItem rhs) {
12942                 long lss = pss ? lhs.pss : lhs.mRss;
12943                 long rss = pss ? rhs.pss : rhs.mRss;
12944                 if (lss < rss) {
12945                     return 1;
12946                 } else if (lss > rss) {
12947                     return -1;
12948                 }
12949                 return 0;
12950             }
12951         });
12952     }
12953 
dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss, boolean dumpSwapPss)12954     static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
12955             ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpPss,
12956             boolean dumpSwapPss) {
12957         if (sort && !isCompact) {
12958             sortMemItems(items, dumpPss);
12959         }
12960 
12961         for (int i=0; i<items.size(); i++) {
12962             MemItem mi = items.get(i);
12963             if (!isCompact) {
12964                 if (dumpPss && dumpSwapPss) {
12965                     pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss),
12966                             mi.label, stringifyKBSize(mi.swapPss));
12967                 } else {
12968                     pw.printf("%s%s: %s\n", prefix, stringifyKBSize(dumpPss ? mi.pss : mi.mRss),
12969                             mi.label);
12970                 }
12971             } else if (mi.isProc) {
12972                 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
12973                 pw.print(","); pw.print(mi.id); pw.print(",");
12974                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
12975                 pw.print(dumpSwapPss ? mi.swapPss : "N/A");
12976                 pw.println(mi.hasActivities ? ",a" : ",e");
12977             } else {
12978                 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
12979                 pw.print(dumpPss ? mi.pss : mi.mRss); pw.print(",");
12980                 pw.println(dumpSwapPss ? mi.swapPss : "N/A");
12981             }
12982             if (mi.subitems != null) {
12983                 dumpMemItems(pw, prefix + "    ", mi.shortLabel, mi.subitems,
12984                         true, isCompact, dumpPss, dumpSwapPss);
12985             }
12986         }
12987     }
12988 
dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss)12989     static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag,
12990             ArrayList<MemItem> items, boolean sort, boolean dumpPss, boolean dumpSwapPss) {
12991         if (sort) {
12992             sortMemItems(items, dumpPss);
12993         }
12994 
12995         for (int i=0; i<items.size(); i++) {
12996             MemItem mi = items.get(i);
12997             final long token = proto.start(fieldId);
12998 
12999             proto.write(MemInfoDumpProto.MemItem.TAG, tag);
13000             proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel);
13001             proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc);
13002             proto.write(MemInfoDumpProto.MemItem.ID, mi.id);
13003             proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities);
13004             proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss);
13005             proto.write(MemInfoDumpProto.MemItem.RSS_KB, mi.mRss);
13006             if (dumpSwapPss) {
13007                 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss);
13008             }
13009             if (mi.subitems != null) {
13010                 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems,
13011                         true, dumpPss, dumpSwapPss);
13012             }
13013             proto.end(token);
13014         }
13015     }
13016 
13017     // These are in KB.
13018     static final long[] DUMP_MEM_BUCKETS = new long[] {
13019         5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
13020         120*1024, 160*1024, 200*1024,
13021         250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
13022         1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
13023     };
13024 
appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)13025     static final void appendMemBucket(StringBuilder out, long memKB, String label,
13026             boolean stackLike) {
13027         int start = label.lastIndexOf('.');
13028         if (start >= 0) start++;
13029         else start = 0;
13030         int end = label.length();
13031         for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
13032             if (DUMP_MEM_BUCKETS[i] >= memKB) {
13033                 long bucket = DUMP_MEM_BUCKETS[i]/1024;
13034                 out.append(bucket);
13035                 out.append(stackLike ? "MB." : "MB ");
13036                 out.append(label, start, end);
13037                 return;
13038             }
13039         }
13040         out.append(memKB/1024);
13041         out.append(stackLike ? "MB." : "MB ");
13042         out.append(label, start, end);
13043     }
13044 
13045     static final int[] DUMP_MEM_OOM_ADJ = new int[] {
13046             ProcessList.NATIVE_ADJ,
13047             ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ,
13048             ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ,
13049             ProcessList.VISIBLE_APP_ADJ,
13050             ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ,
13051             ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
13052             ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
13053             ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ
13054     };
13055     static final String[] DUMP_MEM_OOM_LABEL = new String[] {
13056             "Native",
13057             "System", "Persistent", "Persistent Service", "Foreground",
13058             "Visible", "Perceptible", "Perceptible Low",
13059             "Heavy Weight", "Backup",
13060             "A Services", "Home",
13061             "Previous", "B Services", "Cached"
13062     };
13063     static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
13064             "native",
13065             "sys", "pers", "persvc", "fore",
13066             "vis", "percept", "perceptl",
13067             "heavy", "backup",
13068             "servicea", "home",
13069             "prev", "serviceb", "cached"
13070     };
13071 
dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)13072     private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
13073             long realtime, boolean isCheckinRequest, boolean isCompact) {
13074         if (isCompact) {
13075             pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION);
13076         }
13077         if (isCheckinRequest || isCompact) {
13078             // short checkin version
13079             pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
13080         } else {
13081             pw.println("Applications Memory Usage (in Kilobytes):");
13082             pw.println("Uptime: " + uptime + " Realtime: " + realtime);
13083         }
13084     }
13085 
13086     private static final int KSM_SHARED = 0;
13087     private static final int KSM_SHARING = 1;
13088     private static final int KSM_UNSHARED = 2;
13089     private static final int KSM_VOLATILE = 3;
13090 
getKsmInfo()13091     private final long[] getKsmInfo() {
13092         long[] longOut = new long[4];
13093         final int[] SINGLE_LONG_FORMAT = new int[] {
13094             PROC_SPACE_TERM| PROC_OUT_LONG
13095         };
13096         long[] longTmp = new long[1];
13097         readProcFile("/sys/kernel/mm/ksm/pages_shared",
13098                 SINGLE_LONG_FORMAT, null, longTmp, null);
13099         longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
13100         longTmp[0] = 0;
13101         readProcFile("/sys/kernel/mm/ksm/pages_sharing",
13102                 SINGLE_LONG_FORMAT, null, longTmp, null);
13103         longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
13104         longTmp[0] = 0;
13105         readProcFile("/sys/kernel/mm/ksm/pages_unshared",
13106                 SINGLE_LONG_FORMAT, null, longTmp, null);
13107         longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
13108         longTmp[0] = 0;
13109         readProcFile("/sys/kernel/mm/ksm/pages_volatile",
13110                 SINGLE_LONG_FORMAT, null, longTmp, null);
13111         longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
13112         return longOut;
13113     }
13114 
stringifySize(long size, int order)13115     private static String stringifySize(long size, int order) {
13116         Locale locale = Locale.US;
13117         switch (order) {
13118             case 1:
13119                 return String.format(locale, "%,13d", size);
13120             case 1024:
13121                 return String.format(locale, "%,9dK", size / 1024);
13122             case 1024 * 1024:
13123                 return String.format(locale, "%,5dM", size / 1024 / 1024);
13124             case 1024 * 1024 * 1024:
13125                 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024);
13126             default:
13127                 throw new IllegalArgumentException("Invalid size order");
13128         }
13129     }
13130 
stringifyKBSize(long size)13131     private static String stringifyKBSize(long size) {
13132         return stringifySize(size * 1024, 1024);
13133     }
13134 
13135     // Update this version number if you change the 'compact' format.
13136     private static final int MEMINFO_COMPACT_VERSION = 1;
13137 
13138     private static class MemoryUsageDumpOptions {
13139         boolean dumpDetails;
13140         boolean dumpFullDetails;
13141         boolean dumpDalvik;
13142         boolean dumpSummaryOnly;
13143         boolean dumpUnreachable;
13144         boolean oomOnly;
13145         boolean isCompact;
13146         boolean localOnly;
13147         boolean packages;
13148         boolean isCheckinRequest;
13149         boolean dumpSwapPss;
13150         boolean dumpProto;
13151     }
13152 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)13153     final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
13154             String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) {
13155         MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions();
13156         opts.dumpDetails = false;
13157         opts.dumpFullDetails = false;
13158         opts.dumpDalvik = false;
13159         opts.dumpSummaryOnly = false;
13160         opts.dumpUnreachable = false;
13161         opts.oomOnly = false;
13162         opts.isCompact = false;
13163         opts.localOnly = false;
13164         opts.packages = false;
13165         opts.isCheckinRequest = false;
13166         opts.dumpSwapPss = false;
13167         opts.dumpProto = asProto;
13168 
13169         int opti = 0;
13170         while (opti < args.length) {
13171             String opt = args[opti];
13172             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13173                 break;
13174             }
13175             opti++;
13176             if ("-a".equals(opt)) {
13177                 opts.dumpDetails = true;
13178                 opts.dumpFullDetails = true;
13179                 opts.dumpDalvik = true;
13180                 opts.dumpSwapPss = true;
13181             } else if ("-d".equals(opt)) {
13182                 opts.dumpDalvik = true;
13183             } else if ("-c".equals(opt)) {
13184                 opts.isCompact = true;
13185             } else if ("-s".equals(opt)) {
13186                 opts.dumpDetails = true;
13187                 opts.dumpSummaryOnly = true;
13188             } else if ("-S".equals(opt)) {
13189                 opts.dumpSwapPss = true;
13190             } else if ("--unreachable".equals(opt)) {
13191                 opts.dumpUnreachable = true;
13192             } else if ("--oom".equals(opt)) {
13193                 opts.oomOnly = true;
13194             } else if ("--local".equals(opt)) {
13195                 opts.localOnly = true;
13196             } else if ("--package".equals(opt)) {
13197                 opts.packages = true;
13198             } else if ("--checkin".equals(opt)) {
13199                 opts.isCheckinRequest = true;
13200             } else if ("--proto".equals(opt)) {
13201                 opts.dumpProto = true;
13202 
13203             } else if ("-h".equals(opt)) {
13204                 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
13205                 pw.println("  -a: include all available information for each process.");
13206                 pw.println("  -d: include dalvik details.");
13207                 pw.println("  -c: dump in a compact machine-parseable representation.");
13208                 pw.println("  -s: dump only summary of application memory usage.");
13209                 pw.println("  -S: dump also SwapPss.");
13210                 pw.println("  --oom: only show processes organized by oom adj.");
13211                 pw.println("  --local: only collect details locally, don't call process.");
13212                 pw.println("  --package: interpret process arg as package, dumping all");
13213                 pw.println("             processes that have loaded that package.");
13214                 pw.println("  --checkin: dump data for a checkin");
13215                 pw.println("  --proto: dump data to proto");
13216                 pw.println("If [process] is specified it can be the name or ");
13217                 pw.println("pid of a specific process to dump.");
13218                 return;
13219             } else {
13220                 pw.println("Unknown argument: " + opt + "; use -h for help");
13221             }
13222         }
13223 
13224         String[] innerArgs = new String[args.length-opti];
13225         System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
13226 
13227         ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args);
13228         if (opts.dumpProto) {
13229             dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs);
13230         } else {
13231             dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw);
13232         }
13233     }
13234 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)13235     private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
13236             MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief,
13237             ArrayList<ProcessRecord> procs, PrintWriter categoryPw) {
13238         long uptime = SystemClock.uptimeMillis();
13239         long realtime = SystemClock.elapsedRealtime();
13240         final long[] tmpLong = new long[3];
13241 
13242         if (procs == null) {
13243             // No Java processes.  Maybe they want to print a native process.
13244             String proc = "N/A";
13245             if (innerArgs.length > 0) {
13246                 proc = innerArgs[0];
13247                 if (proc.charAt(0) != '-') {
13248                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
13249                             = new ArrayList<ProcessCpuTracker.Stats>();
13250                     updateCpuStatsNow();
13251                     int findPid = -1;
13252                     try {
13253                         findPid = Integer.parseInt(innerArgs[0]);
13254                     } catch (NumberFormatException e) {
13255                     }
13256                     synchronized (mProcessCpuTracker) {
13257                         final int N = mProcessCpuTracker.countStats();
13258                         for (int i=0; i<N; i++) {
13259                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13260                             if (st.pid == findPid || (st.baseName != null
13261                                     && st.baseName.equals(innerArgs[0]))) {
13262                                 nativeProcs.add(st);
13263                             }
13264                         }
13265                     }
13266                     if (nativeProcs.size() > 0) {
13267                         dumpApplicationMemoryUsageHeader(pw, uptime, realtime,
13268                                 opts.isCheckinRequest, opts.isCompact);
13269                         Debug.MemoryInfo mi = null;
13270                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
13271                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
13272                             final int pid = r.pid;
13273                             if (mi == null) {
13274                                 mi = new Debug.MemoryInfo();
13275                             }
13276                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
13277                                 if (!Debug.getMemoryInfo(pid, mi)) {
13278                                     continue;
13279                                 }
13280                             } else {
13281                                 long pss = Debug.getPss(pid, tmpLong, null);
13282                                 if (pss == 0) {
13283                                     continue;
13284                                 }
13285                                 mi.nativePss = (int) pss;
13286                                 mi.nativePrivateDirty = (int) tmpLong[0];
13287                                 mi.nativeRss = (int) tmpLong[2];
13288                             }
13289                             if (!opts.isCheckinRequest && opts.dumpDetails) {
13290                                 pw.println("\n** MEMINFO in pid " + pid + " ["
13291                                         + r.baseName + "] **");
13292                             }
13293                             ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest,
13294                                     opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
13295                                     pid, r.baseName, 0, 0, 0, 0, 0, 0);
13296                             if (opts.isCheckinRequest) {
13297                                 pw.println();
13298                             }
13299                         }
13300                         return;
13301                     }
13302                 }
13303             }
13304             pw.println("No process found for: " + proc);
13305             return;
13306         }
13307 
13308         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
13309             opts.dumpDetails = true;
13310         }
13311         final int numProcs = procs.size();
13312         final boolean collectNative = !opts.isCheckinRequest && numProcs > 1 && !opts.packages;
13313         if (collectNative) {
13314             // If we are showing aggregations, also look for native processes to
13315             // include so that our aggregations are more accurate.
13316             updateCpuStatsNow();
13317         }
13318 
13319         dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact);
13320 
13321         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
13322         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
13323         long nativePss = 0;
13324         long nativeSwapPss = 0;
13325         long nativeRss = 0;
13326         long dalvikPss = 0;
13327         long dalvikSwapPss = 0;
13328         long dalvikRss = 0;
13329         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13330                 EmptyArray.LONG;
13331         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13332                 EmptyArray.LONG;
13333         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13334                 EmptyArray.LONG;
13335         long otherPss = 0;
13336         long otherSwapPss = 0;
13337         long otherRss = 0;
13338         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13339         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13340         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13341 
13342         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13343         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13344         long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
13345         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
13346                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
13347 
13348         long totalPss = 0;
13349         long totalSwapPss = 0;
13350         long totalRss = 0;
13351         long cachedPss = 0;
13352         long cachedSwapPss = 0;
13353         boolean hasSwapPss = false;
13354 
13355         Debug.MemoryInfo mi = null;
13356         for (int i = numProcs - 1; i >= 0; i--) {
13357             final ProcessRecord r = procs.get(i);
13358             final IApplicationThread thread;
13359             final int pid;
13360             final int oomAdj;
13361             final boolean hasActivities;
13362             synchronized (this) {
13363                 thread = r.thread;
13364                 pid = r.pid;
13365                 oomAdj = r.getSetAdjWithServices();
13366                 hasActivities = r.hasActivities();
13367             }
13368             if (thread != null) {
13369                 if (mi == null) {
13370                     mi = new Debug.MemoryInfo();
13371                 }
13372                 final int reportType;
13373                 final long startTime;
13374                 final long endTime;
13375                 if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
13376                     reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
13377                     startTime = SystemClock.currentThreadTimeMillis();
13378                     if (!Debug.getMemoryInfo(pid, mi)) {
13379                         continue;
13380                     }
13381                     endTime = SystemClock.currentThreadTimeMillis();
13382                     hasSwapPss = mi.hasSwappedOutPss;
13383                 } else {
13384                     reportType = ProcessStats.ADD_PSS_EXTERNAL;
13385                     startTime = SystemClock.currentThreadTimeMillis();
13386                     long pss = Debug.getPss(pid, tmpLong, null);
13387                     if (pss == 0) {
13388                         continue;
13389                     }
13390                     mi.dalvikPss = (int) pss;
13391                     endTime = SystemClock.currentThreadTimeMillis();
13392                     mi.dalvikPrivateDirty = (int) tmpLong[0];
13393                     mi.dalvikRss = (int) tmpLong[2];
13394                 }
13395                 if (!opts.isCheckinRequest && opts.dumpDetails) {
13396                     pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
13397                 }
13398                 if (opts.dumpDetails) {
13399                     if (opts.localOnly) {
13400                         ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails,
13401                                 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
13402                         if (opts.isCheckinRequest) {
13403                             pw.println();
13404                         }
13405                     } else {
13406                         pw.flush();
13407                         try {
13408                             TransferPipe tp = new TransferPipe();
13409                             try {
13410                                 thread.dumpMemInfo(tp.getWriteFd(),
13411                                         mi, opts.isCheckinRequest, opts.dumpFullDetails,
13412                                         opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs);
13413                                 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000);
13414                             } finally {
13415                                 tp.kill();
13416                             }
13417                         } catch (IOException e) {
13418                             if (!opts.isCheckinRequest) {
13419                                 pw.println("Got IoException! " + e);
13420                                 pw.flush();
13421                             }
13422                         } catch (RemoteException e) {
13423                             if (!opts.isCheckinRequest) {
13424                                 pw.println("Got RemoteException! " + e);
13425                                 pw.flush();
13426                             }
13427                         }
13428                     }
13429                 }
13430 
13431                 final long myTotalPss = mi.getTotalPss();
13432                 final long myTotalUss = mi.getTotalUss();
13433                 final long myTotalRss = mi.getTotalRss();
13434                 final long myTotalSwapPss = mi.getTotalSwappedOutPss();
13435 
13436                 synchronized (this) {
13437                     if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
13438                         // Record this for posterity if the process has been stable.
13439                         r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true,
13440                                 reportType, endTime-startTime, r.pkgList.mPkgList);
13441                         for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) {
13442                             ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg);
13443                             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
13444                                     r.info.uid,
13445                                     holder.state.getName(),
13446                                     holder.state.getPackage(),
13447                                     myTotalPss, myTotalUss, myTotalRss, reportType,
13448                                     endTime-startTime,
13449                                     holder.appVersion);
13450                         }
13451                     }
13452                 }
13453 
13454                 if (!opts.isCheckinRequest && mi != null) {
13455                     totalPss += myTotalPss;
13456                     totalSwapPss += myTotalSwapPss;
13457                     totalRss += myTotalRss;
13458                     MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
13459                             (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
13460                             myTotalSwapPss, myTotalRss, pid, hasActivities);
13461                     procMems.add(pssItem);
13462                     procMemsMap.put(pid, pssItem);
13463 
13464                     nativePss += mi.nativePss;
13465                     nativeSwapPss += mi.nativeSwappedOutPss;
13466                     nativeRss += mi.nativeRss;
13467                     dalvikPss += mi.dalvikPss;
13468                     dalvikSwapPss += mi.dalvikSwappedOutPss;
13469                     dalvikRss += mi.dalvikRss;
13470                     for (int j=0; j<dalvikSubitemPss.length; j++) {
13471                         dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13472                         dalvikSubitemSwapPss[j] +=
13473                                 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13474                         dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13475                     }
13476                     otherPss += mi.otherPss;
13477                     otherRss += mi.otherRss;
13478                     otherSwapPss += mi.otherSwappedOutPss;
13479                     for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13480                         long mem = mi.getOtherPss(j);
13481                         miscPss[j] += mem;
13482                         otherPss -= mem;
13483                         mem = mi.getOtherSwappedOutPss(j);
13484                         miscSwapPss[j] += mem;
13485                         otherSwapPss -= mem;
13486                         mem = mi.getOtherRss(j);
13487                         miscRss[j] += mem;
13488                         otherRss -= mem;
13489                     }
13490 
13491                     if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13492                         cachedPss += myTotalPss;
13493                         cachedSwapPss += myTotalSwapPss;
13494                     }
13495 
13496                     for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
13497                         if (oomIndex == (oomPss.length - 1)
13498                                 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
13499                                         && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
13500                             oomPss[oomIndex] += myTotalPss;
13501                             oomSwapPss[oomIndex] += myTotalSwapPss;
13502                             if (oomProcs[oomIndex] == null) {
13503                                 oomProcs[oomIndex] = new ArrayList<MemItem>();
13504                             }
13505                             oomProcs[oomIndex].add(pssItem);
13506                             oomRss[oomIndex] += myTotalRss;
13507                             break;
13508                         }
13509                     }
13510                 }
13511             }
13512         }
13513 
13514         long nativeProcTotalPss = 0;
13515 
13516         if (collectNative) {
13517             mi = null;
13518             synchronized (mProcessCpuTracker) {
13519                 final int N = mProcessCpuTracker.countStats();
13520                 for (int i=0; i<N; i++) {
13521                     ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13522                     if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
13523                         if (mi == null) {
13524                             mi = new Debug.MemoryInfo();
13525                         }
13526                         if (!brief && !opts.oomOnly) {
13527                             if (!Debug.getMemoryInfo(st.pid, mi)) {
13528                                 continue;
13529                             }
13530                         } else {
13531                             long pss = Debug.getPss(st.pid, tmpLong, null);
13532                             if (pss == 0) {
13533                                 continue;
13534                             }
13535                             mi.nativePss = (int) pss;
13536                             mi.nativePrivateDirty = (int) tmpLong[0];
13537                             mi.nativeRss = (int) tmpLong[2];
13538                         }
13539 
13540                         final long myTotalPss = mi.getTotalPss();
13541                         final long myTotalSwapPss = mi.getTotalSwappedOutPss();
13542                         final long myTotalRss = mi.getTotalRss();
13543                         totalPss += myTotalPss;
13544                         totalSwapPss += myTotalSwapPss;
13545                         totalRss += myTotalRss;
13546                         nativeProcTotalPss += myTotalPss;
13547 
13548                         MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
13549                                 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), myTotalRss,
13550                                 st.pid, false);
13551                         procMems.add(pssItem);
13552 
13553                         nativePss += mi.nativePss;
13554                         nativeSwapPss += mi.nativeSwappedOutPss;
13555                         nativeRss += mi.nativeRss;
13556                         dalvikPss += mi.dalvikPss;
13557                         dalvikSwapPss += mi.dalvikSwappedOutPss;
13558                         dalvikRss += mi.dalvikRss;
13559                         for (int j=0; j<dalvikSubitemPss.length; j++) {
13560                             dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13561                             dalvikSubitemSwapPss[j] +=
13562                                     mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13563                             dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
13564                                     + j);
13565                         }
13566                         otherPss += mi.otherPss;
13567                         otherSwapPss += mi.otherSwappedOutPss;
13568                         otherRss += mi.otherRss;
13569                         for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13570                             long mem = mi.getOtherPss(j);
13571                             miscPss[j] += mem;
13572                             otherPss -= mem;
13573                             mem = mi.getOtherSwappedOutPss(j);
13574                             miscSwapPss[j] += mem;
13575                             otherSwapPss -= mem;
13576                             mem = mi.getOtherRss(j);
13577                             miscRss[j] += mem;
13578                             otherRss -= mem;
13579                         }
13580                         oomPss[0] += myTotalPss;
13581                         oomSwapPss[0] += myTotalSwapPss;
13582                         if (oomProcs[0] == null) {
13583                             oomProcs[0] = new ArrayList<MemItem>();
13584                         }
13585                         oomProcs[0].add(pssItem);
13586                         oomRss[0] += myTotalRss;
13587                     }
13588                 }
13589             }
13590 
13591             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
13592 
13593             catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, nativeRss, -1));
13594             final int dalvikId = -2;
13595             catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikRss,
13596                     dalvikId));
13597             catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, otherRss, -3));
13598             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13599                 String label = Debug.MemoryInfo.getOtherLabel(j);
13600                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j],  j));
13601             }
13602             if (dalvikSubitemPss.length > 0) {
13603                 // Add dalvik subitems.
13604                 for (MemItem memItem : catMems) {
13605                     int memItemStart = 0, memItemEnd = 0;
13606                     if (memItem.id == dalvikId) {
13607                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
13608                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
13609                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
13610                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
13611                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
13612                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
13613                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
13614                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
13615                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
13616                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
13617                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
13618                     } else {
13619                         continue;  // No subitems, continue.
13620                     }
13621                     memItem.subitems = new ArrayList<MemItem>();
13622                     for (int j=memItemStart; j<=memItemEnd; j++) {
13623                         final String name = Debug.MemoryInfo.getOtherLabel(
13624                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
13625                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
13626                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
13627                     }
13628                 }
13629             }
13630 
13631             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
13632             for (int j=0; j<oomPss.length; j++) {
13633                 if (oomPss[j] != 0) {
13634                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
13635                             : DUMP_MEM_OOM_LABEL[j];
13636                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
13637                             DUMP_MEM_OOM_ADJ[j]);
13638                     item.subitems = oomProcs[j];
13639                     oomMems.add(item);
13640                 }
13641             }
13642             if (!opts.isCompact) {
13643                 pw.println();
13644             }
13645             if (!brief && !opts.oomOnly && !opts.isCompact) {
13646                 pw.println();
13647                 pw.println("Total RSS by process:");
13648                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, false, false);
13649                 pw.println();
13650             }
13651             if (!opts.isCompact) {
13652                 pw.println("Total RSS by OOM adjustment:");
13653             }
13654             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, false, false);
13655             if (!brief && !opts.oomOnly) {
13656                 PrintWriter out = categoryPw != null ? categoryPw : pw;
13657                 if (!opts.isCompact) {
13658                     out.println();
13659                     out.println("Total RSS by category:");
13660                 }
13661                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, false, false);
13662             }
13663             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0;
13664             if (!brief && !opts.oomOnly && !opts.isCompact) {
13665                 pw.println();
13666                 pw.println("Total PSS by process:");
13667                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, true,
13668                         opts.dumpSwapPss);
13669                 pw.println();
13670             }
13671             if (!opts.isCompact) {
13672                 pw.println("Total PSS by OOM adjustment:");
13673             }
13674             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, true, opts.dumpSwapPss);
13675             if (!brief && !opts.oomOnly) {
13676                 PrintWriter out = categoryPw != null ? categoryPw : pw;
13677                 if (!opts.isCompact) {
13678                     out.println();
13679                     out.println("Total PSS by category:");
13680                 }
13681                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, true,
13682                         opts.dumpSwapPss);
13683             }
13684             if (!opts.isCompact) {
13685                 pw.println();
13686             }
13687             MemInfoReader memInfo = new MemInfoReader();
13688             memInfo.readMemInfo();
13689             if (nativeProcTotalPss > 0) {
13690                 synchronized (this) {
13691                     final long cachedKb = memInfo.getCachedSizeKb();
13692                     final long freeKb = memInfo.getFreeSizeKb();
13693                     final long zramKb = memInfo.getZramTotalSizeKb();
13694                     final long kernelKb = memInfo.getKernelUsedSizeKb();
13695                     EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
13696                             kernelKb*1024, nativeProcTotalPss*1024);
13697                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
13698                             nativeProcTotalPss);
13699                 }
13700             }
13701             if (!brief) {
13702                 if (!opts.isCompact) {
13703                     pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
13704                     pw.print(" (status ");
13705                     switch (mLastMemoryLevel) {
13706                         case ProcessStats.ADJ_MEM_FACTOR_NORMAL:
13707                             pw.println("normal)");
13708                             break;
13709                         case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
13710                             pw.println("moderate)");
13711                             break;
13712                         case ProcessStats.ADJ_MEM_FACTOR_LOW:
13713                             pw.println("low)");
13714                             break;
13715                         case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
13716                             pw.println("critical)");
13717                             break;
13718                         default:
13719                             pw.print(mLastMemoryLevel);
13720                             pw.println(")");
13721                             break;
13722                     }
13723                     pw.print(" Free RAM: ");
13724                     pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
13725                             + memInfo.getFreeSizeKb()));
13726                     pw.print(" (");
13727                     pw.print(stringifyKBSize(cachedPss));
13728                     pw.print(" cached pss + ");
13729                     pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
13730                     pw.print(" cached kernel + ");
13731                     pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
13732                     pw.println(" free)");
13733                 } else {
13734                     pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
13735                     pw.print(cachedPss + memInfo.getCachedSizeKb()
13736                             + memInfo.getFreeSizeKb()); pw.print(",");
13737                     pw.println(totalPss - cachedPss);
13738                 }
13739             }
13740             long kernelUsed = memInfo.getKernelUsedSizeKb();
13741             final long ionHeap = Debug.getIonHeapsSizeKb();
13742             if (ionHeap > 0) {
13743                 final long ionMapped = Debug.getIonMappedSizeKb();
13744                 final long ionUnmapped = ionHeap - ionMapped;
13745                 final long ionPool = Debug.getIonPoolsSizeKb();
13746                 pw.print("      ION: ");
13747                         pw.print(stringifyKBSize(ionHeap + ionPool));
13748                         pw.print(" (");
13749                         pw.print(stringifyKBSize(ionMapped));
13750                         pw.print(" mapped + ");
13751                         pw.print(stringifyKBSize(ionUnmapped));
13752                         pw.print(" unmapped + ");
13753                         pw.print(stringifyKBSize(ionPool));
13754                         pw.println(" pools)");
13755                 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
13756                 // set on ION VMAs, therefore consider the entire ION heap as used kernel memory
13757                 kernelUsed += ionHeap;
13758             }
13759             final long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss)
13760                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
13761                     - kernelUsed - memInfo.getZramTotalSizeKb();
13762             if (!opts.isCompact) {
13763                 pw.print(" Used RAM: "); pw.print(stringifyKBSize(totalPss - cachedPss
13764                         + kernelUsed)); pw.print(" (");
13765                 pw.print(stringifyKBSize(totalPss - cachedPss)); pw.print(" used pss + ");
13766                 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n");
13767                 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM));
13768             } else {
13769                 pw.print("lostram,"); pw.println(lostRAM);
13770             }
13771             if (!brief) {
13772                 if (memInfo.getZramTotalSizeKb() != 0) {
13773                     if (!opts.isCompact) {
13774                         pw.print("     ZRAM: ");
13775                         pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
13776                                 pw.print(" physical used for ");
13777                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()
13778                                         - memInfo.getSwapFreeSizeKb()));
13779                                 pw.print(" in swap (");
13780                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
13781                                 pw.println(" total swap)");
13782                     } else {
13783                         pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
13784                                 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
13785                                 pw.println(memInfo.getSwapFreeSizeKb());
13786                     }
13787                 }
13788                 final long[] ksm = getKsmInfo();
13789                 if (!opts.isCompact) {
13790                     if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
13791                             || ksm[KSM_VOLATILE] != 0) {
13792                         pw.print("      KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING]));
13793                                 pw.print(" saved from shared ");
13794                                 pw.print(stringifyKBSize(ksm[KSM_SHARED]));
13795                         pw.print("           "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
13796                                 pw.print(" unshared; ");
13797                                 pw.print(stringifyKBSize(
13798                                              ksm[KSM_VOLATILE])); pw.println(" volatile");
13799                     }
13800                     pw.print("   Tuning: ");
13801                     pw.print(ActivityManager.staticGetMemoryClass());
13802                     pw.print(" (large ");
13803                     pw.print(ActivityManager.staticGetLargeMemoryClass());
13804                     pw.print("), oom ");
13805                     pw.print(stringifySize(
13806                                 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
13807                     pw.print(", restore limit ");
13808                     pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
13809                     if (ActivityManager.isLowRamDeviceStatic()) {
13810                         pw.print(" (low-ram)");
13811                     }
13812                     if (ActivityManager.isHighEndGfx()) {
13813                         pw.print(" (high-end-gfx)");
13814                     }
13815                     pw.println();
13816                 } else {
13817                     pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(",");
13818                     pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]);
13819                     pw.print(","); pw.println(ksm[KSM_VOLATILE]);
13820                     pw.print("tuning,");
13821                     pw.print(ActivityManager.staticGetMemoryClass());
13822                     pw.print(',');
13823                     pw.print(ActivityManager.staticGetLargeMemoryClass());
13824                     pw.print(',');
13825                     pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
13826                     if (ActivityManager.isLowRamDeviceStatic()) {
13827                         pw.print(",low-ram");
13828                     }
13829                     if (ActivityManager.isHighEndGfx()) {
13830                         pw.print(",high-end-gfx");
13831                     }
13832                     pw.println();
13833                 }
13834             }
13835         }
13836     }
13837 
dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)13838     private final void dumpApplicationMemoryUsage(FileDescriptor fd,
13839             MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief,
13840             ArrayList<ProcessRecord> procs) {
13841         final long uptimeMs = SystemClock.uptimeMillis();
13842         final long realtimeMs = SystemClock.elapsedRealtime();
13843         final long[] tmpLong = new long[3];
13844 
13845         if (procs == null) {
13846             // No Java processes.  Maybe they want to print a native process.
13847             String proc = "N/A";
13848             if (innerArgs.length > 0) {
13849                 proc = innerArgs[0];
13850                 if (proc.charAt(0) != '-') {
13851                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
13852                             = new ArrayList<ProcessCpuTracker.Stats>();
13853                     updateCpuStatsNow();
13854                     int findPid = -1;
13855                     try {
13856                         findPid = Integer.parseInt(innerArgs[0]);
13857                     } catch (NumberFormatException e) {
13858                     }
13859                     synchronized (mProcessCpuTracker) {
13860                         final int N = mProcessCpuTracker.countStats();
13861                         for (int i=0; i<N; i++) {
13862                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13863                             if (st.pid == findPid || (st.baseName != null
13864                                     && st.baseName.equals(innerArgs[0]))) {
13865                                 nativeProcs.add(st);
13866                             }
13867                         }
13868                     }
13869                     if (nativeProcs.size() > 0) {
13870                         ProtoOutputStream proto = new ProtoOutputStream(fd);
13871 
13872                         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
13873                         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
13874                         Debug.MemoryInfo mi = null;
13875                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
13876                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
13877                             final int pid = r.pid;
13878 
13879                             if (mi == null) {
13880                                 mi = new Debug.MemoryInfo();
13881                             }
13882                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
13883                                 if (!Debug.getMemoryInfo(pid, mi)) {
13884                                     continue;
13885                                 }
13886                             } else {
13887                                 long pss = Debug.getPss(pid, tmpLong, null);
13888                                 if (pss == 0) {
13889                                     continue;
13890                                 }
13891                                 mi.nativePss = (int) pss;
13892                                 mi.nativePrivateDirty = (int) tmpLong[0];
13893                                 mi.nativeRss = (int) tmpLong[2];
13894                             }
13895 
13896                             final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES);
13897 
13898                             proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
13899                             proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName);
13900 
13901                             ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
13902                                     opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
13903 
13904                             proto.end(nToken);
13905                         }
13906 
13907                         proto.flush();
13908                         return;
13909                     }
13910                 }
13911             }
13912             Log.d(TAG, "No process found for: " + innerArgs[0]);
13913             return;
13914         }
13915 
13916         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
13917             opts.dumpDetails = true;
13918         }
13919         final int numProcs = procs.size();
13920         final boolean collectNative = numProcs > 1 && !opts.packages;
13921         if (collectNative) {
13922             // If we are showing aggregations, also look for native processes to
13923             // include so that our aggregations are more accurate.
13924             updateCpuStatsNow();
13925         }
13926 
13927         ProtoOutputStream proto = new ProtoOutputStream(fd);
13928 
13929         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
13930         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
13931 
13932         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
13933         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
13934         long nativePss = 0;
13935         long nativeSwapPss = 0;
13936         long nativeRss = 0;
13937         long dalvikPss = 0;
13938         long dalvikSwapPss = 0;
13939         long dalvikRss = 0;
13940         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13941                 EmptyArray.LONG;
13942         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13943                 EmptyArray.LONG;
13944         long[] dalvikSubitemRss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13945                 EmptyArray.LONG;
13946         long otherPss = 0;
13947         long otherSwapPss = 0;
13948         long otherRss = 0;
13949         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13950         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13951         long[] miscRss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13952 
13953         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13954         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13955         long[] oomRss = new long[DUMP_MEM_OOM_LABEL.length];
13956         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
13957                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
13958 
13959         long totalPss = 0;
13960         long totalSwapPss = 0;
13961         long totalRss = 0;
13962         long cachedPss = 0;
13963         long cachedSwapPss = 0;
13964         boolean hasSwapPss = false;
13965 
13966         Debug.MemoryInfo mi = null;
13967         for (int i = numProcs - 1; i >= 0; i--) {
13968             final ProcessRecord r = procs.get(i);
13969             final IApplicationThread thread;
13970             final int pid;
13971             final int oomAdj;
13972             final boolean hasActivities;
13973             synchronized (this) {
13974                 thread = r.thread;
13975                 pid = r.pid;
13976                 oomAdj = r.getSetAdjWithServices();
13977                 hasActivities = r.hasActivities();
13978             }
13979             if (thread == null) {
13980                 continue;
13981             }
13982             if (mi == null) {
13983                 mi = new Debug.MemoryInfo();
13984             }
13985             final int reportType;
13986             final long startTime;
13987             final long endTime;
13988             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
13989                 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
13990                 startTime = SystemClock.currentThreadTimeMillis();
13991                 if (!Debug.getMemoryInfo(pid, mi)) {
13992                     continue;
13993                 }
13994                 endTime = SystemClock.currentThreadTimeMillis();
13995                 hasSwapPss = mi.hasSwappedOutPss;
13996             } else {
13997                 reportType = ProcessStats.ADD_PSS_EXTERNAL;
13998                 startTime = SystemClock.currentThreadTimeMillis();
13999                 long pss = Debug.getPss(pid, tmpLong, null);
14000                 if (pss == 0) {
14001                     continue;
14002                 }
14003                 mi.dalvikPss = (int) pss;
14004                 endTime = SystemClock.currentThreadTimeMillis();
14005                 mi.dalvikPrivateDirty = (int) tmpLong[0];
14006                 mi.dalvikRss = (int) tmpLong[2];
14007             }
14008             if (opts.dumpDetails) {
14009                 if (opts.localOnly) {
14010                     final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES);
14011                     final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
14012                     proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
14013                     proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName);
14014                     ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
14015                             opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
14016                     proto.end(mToken);
14017                     proto.end(aToken);
14018                 } else {
14019                     try {
14020                         ByteTransferPipe tp = new ByteTransferPipe();
14021                         try {
14022                             thread.dumpMemInfoProto(tp.getWriteFd(),
14023                                 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
14024                                 opts.dumpUnreachable, innerArgs);
14025                             proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get());
14026                         } finally {
14027                             tp.kill();
14028                         }
14029                     } catch (IOException e) {
14030                         Log.e(TAG, "Got IOException!", e);
14031                     } catch (RemoteException e) {
14032                         Log.e(TAG, "Got RemoteException!", e);
14033                     }
14034                 }
14035             }
14036 
14037             final long myTotalPss = mi.getTotalPss();
14038             final long myTotalUss = mi.getTotalUss();
14039             final long myTotalRss = mi.getTotalRss();
14040             final long myTotalSwapPss = mi.getTotalSwappedOutPss();
14041 
14042             synchronized (this) {
14043                 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
14044                     // Record this for posterity if the process has been stable.
14045                     r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true,
14046                             reportType, endTime-startTime, r.pkgList.mPkgList);
14047                     for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) {
14048                         ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg);
14049                         FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
14050                                 r.info.uid,
14051                                 holder.state.getName(),
14052                                 holder.state.getPackage(),
14053                                 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
14054                                 holder.appVersion);
14055                     }
14056                 }
14057             }
14058 
14059             if (!opts.isCheckinRequest && mi != null) {
14060                 totalPss += myTotalPss;
14061                 totalSwapPss += myTotalSwapPss;
14062                 totalRss += myTotalRss;
14063                 MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
14064                         (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
14065                         myTotalSwapPss, myTotalRss, pid, hasActivities);
14066                 procMems.add(pssItem);
14067                 procMemsMap.put(pid, pssItem);
14068 
14069                 nativePss += mi.nativePss;
14070                 nativeSwapPss += mi.nativeSwappedOutPss;
14071                 nativeRss += mi.nativeRss;
14072                 dalvikPss += mi.dalvikPss;
14073                 dalvikSwapPss += mi.dalvikSwappedOutPss;
14074                 dalvikRss += mi.dalvikRss;
14075                 for (int j=0; j<dalvikSubitemPss.length; j++) {
14076                     dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
14077                     dalvikSubitemSwapPss[j] +=
14078                             mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
14079                     dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
14080                 }
14081                 otherPss += mi.otherPss;
14082                 otherRss += mi.otherRss;
14083                 otherSwapPss += mi.otherSwappedOutPss;
14084                 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
14085                     long mem = mi.getOtherPss(j);
14086                     miscPss[j] += mem;
14087                     otherPss -= mem;
14088                     mem = mi.getOtherSwappedOutPss(j);
14089                     miscSwapPss[j] += mem;
14090                     otherSwapPss -= mem;
14091                     mem = mi.getOtherRss(j);
14092                     miscRss[j] += mem;
14093                     otherRss -= mem;
14094                 }
14095 
14096                 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
14097                     cachedPss += myTotalPss;
14098                     cachedSwapPss += myTotalSwapPss;
14099                 }
14100 
14101                 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
14102                     if (oomIndex == (oomPss.length - 1)
14103                             || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
14104                                     && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
14105                         oomPss[oomIndex] += myTotalPss;
14106                         oomSwapPss[oomIndex] += myTotalSwapPss;
14107                         if (oomProcs[oomIndex] == null) {
14108                             oomProcs[oomIndex] = new ArrayList<MemItem>();
14109                         }
14110                         oomProcs[oomIndex].add(pssItem);
14111                         oomRss[oomIndex] += myTotalRss;
14112                         break;
14113                     }
14114                 }
14115             }
14116         }
14117 
14118         long nativeProcTotalPss = 0;
14119 
14120         if (collectNative) {
14121             mi = null;
14122             synchronized (mProcessCpuTracker) {
14123                 final int N = mProcessCpuTracker.countStats();
14124                 for (int i=0; i<N; i++) {
14125                     ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
14126                     if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
14127                         if (mi == null) {
14128                             mi = new Debug.MemoryInfo();
14129                         }
14130                         if (!brief && !opts.oomOnly) {
14131                             if (!Debug.getMemoryInfo(st.pid, mi)) {
14132                                 continue;
14133                             }
14134                         } else {
14135                             long pss = Debug.getPss(st.pid, tmpLong, null);
14136                             if (pss == 0) {
14137                                 continue;
14138                             }
14139                             mi.nativePss = (int) pss;
14140                             mi.nativePrivateDirty = (int) tmpLong[0];
14141                             mi.nativeRss = (int) tmpLong[2];
14142                         }
14143 
14144                         final long myTotalPss = mi.getTotalPss();
14145                         final long myTotalSwapPss = mi.getTotalSwappedOutPss();
14146                         final long myTotalRss = mi.getTotalRss();
14147                         totalPss += myTotalPss;
14148                         totalSwapPss += myTotalSwapPss;
14149                         totalRss += myTotalRss;
14150                         nativeProcTotalPss += myTotalPss;
14151 
14152                         MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
14153                                 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), myTotalRss,
14154                                 st.pid, false);
14155                         procMems.add(pssItem);
14156 
14157                         nativePss += mi.nativePss;
14158                         nativeSwapPss += mi.nativeSwappedOutPss;
14159                         nativeRss += mi.nativeRss;
14160                         dalvikPss += mi.dalvikPss;
14161                         dalvikSwapPss += mi.dalvikSwappedOutPss;
14162                         dalvikRss += mi.dalvikRss;
14163                         for (int j=0; j<dalvikSubitemPss.length; j++) {
14164                             dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
14165                             dalvikSubitemSwapPss[j] +=
14166                                     mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
14167                             dalvikSubitemRss[j] += mi.getOtherRss(Debug.MemoryInfo.NUM_OTHER_STATS
14168                                     + j);
14169                         }
14170                         otherPss += mi.otherPss;
14171                         otherSwapPss += mi.otherSwappedOutPss;
14172                         otherRss += mi.otherRss;
14173                         for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
14174                             long mem = mi.getOtherPss(j);
14175                             miscPss[j] += mem;
14176                             otherPss -= mem;
14177                             mem = mi.getOtherSwappedOutPss(j);
14178                             miscSwapPss[j] += mem;
14179                             otherSwapPss -= mem;
14180                             mem = mi.getOtherRss(j);
14181                             miscRss[j] += mem;
14182                             otherRss -= mem;
14183                         }
14184                         oomPss[0] += myTotalPss;
14185                         oomSwapPss[0] += myTotalSwapPss;
14186                         if (oomProcs[0] == null) {
14187                             oomProcs[0] = new ArrayList<MemItem>();
14188                         }
14189                         oomProcs[0].add(pssItem);
14190                         oomRss[0] += myTotalRss;
14191                     }
14192                 }
14193             }
14194 
14195             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
14196 
14197             catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, nativeRss, -1));
14198             final int dalvikId = -2;
14199             catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikRss,
14200                     dalvikId));
14201             catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, otherRss, -3));
14202             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
14203                 String label = Debug.MemoryInfo.getOtherLabel(j);
14204                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], miscRss[j], j));
14205             }
14206             if (dalvikSubitemPss.length > 0) {
14207                 // Add dalvik subitems.
14208                 for (MemItem memItem : catMems) {
14209                     int memItemStart = 0, memItemEnd = 0;
14210                     if (memItem.id == dalvikId) {
14211                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
14212                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
14213                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
14214                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
14215                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
14216                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
14217                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
14218                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
14219                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
14220                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
14221                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
14222                     } else {
14223                         continue;  // No subitems, continue.
14224                     }
14225                     memItem.subitems = new ArrayList<MemItem>();
14226                     for (int j=memItemStart; j<=memItemEnd; j++) {
14227                         final String name = Debug.MemoryInfo.getOtherLabel(
14228                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
14229                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
14230                                 dalvikSubitemSwapPss[j], dalvikSubitemRss[j], j));
14231                     }
14232                 }
14233             }
14234 
14235             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
14236             for (int j=0; j<oomPss.length; j++) {
14237                 if (oomPss[j] != 0) {
14238                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
14239                             : DUMP_MEM_OOM_LABEL[j];
14240                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j], oomRss[j],
14241                             DUMP_MEM_OOM_ADJ[j]);
14242                     item.subitems = oomProcs[j];
14243                     oomMems.add(item);
14244                 }
14245             }
14246 
14247             if (!opts.oomOnly) {
14248                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_PROCESS, "proc",
14249                         procMems, true, false, false);
14250             }
14251             dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_OOM_ADJUSTMENT, "oom",
14252                     oomMems, false, false, false);
14253             if (!brief && !opts.oomOnly) {
14254                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_RSS_BY_CATEGORY, "cat",
14255                         catMems, true, false, false);
14256             }
14257 
14258             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0;
14259             if (!opts.oomOnly) {
14260                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc",
14261                         procMems, true, true, opts.dumpSwapPss);
14262             }
14263             dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom",
14264                     oomMems, false, true, opts.dumpSwapPss);
14265             if (!brief && !opts.oomOnly) {
14266                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat",
14267                         catMems, true, true, opts.dumpSwapPss);
14268             }
14269             MemInfoReader memInfo = new MemInfoReader();
14270             memInfo.readMemInfo();
14271             if (nativeProcTotalPss > 0) {
14272                 synchronized (this) {
14273                     final long cachedKb = memInfo.getCachedSizeKb();
14274                     final long freeKb = memInfo.getFreeSizeKb();
14275                     final long zramKb = memInfo.getZramTotalSizeKb();
14276                     final long kernelKb = memInfo.getKernelUsedSizeKb();
14277                     EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
14278                             kernelKb*1024, nativeProcTotalPss*1024);
14279                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
14280                             nativeProcTotalPss);
14281                 }
14282             }
14283             if (!brief) {
14284                 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb());
14285                 proto.write(MemInfoDumpProto.STATUS, mLastMemoryLevel);
14286                 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss);
14287                 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb());
14288                 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb());
14289             }
14290             long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss)
14291                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
14292                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
14293             proto.write(MemInfoDumpProto.USED_PSS_KB, totalPss - cachedPss);
14294             proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb());
14295             proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM);
14296             if (!brief) {
14297                 if (memInfo.getZramTotalSizeKb() != 0) {
14298                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb());
14299                     proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB,
14300                             memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb());
14301                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb());
14302                 }
14303                 final long[] ksm = getKsmInfo();
14304                 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]);
14305                 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]);
14306                 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]);
14307                 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]);
14308 
14309                 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass());
14310                 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass());
14311                 proto.write(MemInfoDumpProto.OOM_KB,
14312                         mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
14313                 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB,
14314                         mProcessList.getCachedRestoreThresholdKb());
14315 
14316                 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic());
14317                 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx());
14318             }
14319         }
14320 
14321         proto.flush();
14322     }
14323 
appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)14324     private void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss,
14325             long memtrack, String name) {
14326         sb.append("  ");
14327         sb.append(ProcessList.makeOomAdjString(oomAdj, false));
14328         sb.append(' ');
14329         sb.append(ProcessList.makeProcStateString(procState));
14330         sb.append(' ');
14331         ProcessList.appendRamKb(sb, pss);
14332         sb.append(": ");
14333         sb.append(name);
14334         if (memtrack > 0) {
14335             sb.append(" (");
14336             sb.append(stringifyKBSize(memtrack));
14337             sb.append(" memtrack)");
14338         }
14339     }
14340 
appendMemInfo(StringBuilder sb, ProcessMemInfo mi)14341     private void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) {
14342         appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name);
14343         sb.append(" (pid ");
14344         sb.append(mi.pid);
14345         sb.append(") ");
14346         sb.append(mi.adjType);
14347         sb.append('\n');
14348         if (mi.adjReason != null) {
14349             sb.append("                      ");
14350             sb.append(mi.adjReason);
14351             sb.append('\n');
14352         }
14353     }
14354 
reportMemUsage(ArrayList<ProcessMemInfo> memInfos)14355     void reportMemUsage(ArrayList<ProcessMemInfo> memInfos) {
14356         final SparseArray<ProcessMemInfo> infoMap = new SparseArray<>(memInfos.size());
14357         for (int i=0, N=memInfos.size(); i<N; i++) {
14358             ProcessMemInfo mi = memInfos.get(i);
14359             infoMap.put(mi.pid, mi);
14360         }
14361         updateCpuStatsNow();
14362         long[] memtrackTmp = new long[1];
14363         long[] swaptrackTmp = new long[2];
14364         final List<ProcessCpuTracker.Stats> stats;
14365         // Get a list of Stats that have vsize > 0
14366         synchronized (mProcessCpuTracker) {
14367             stats = mProcessCpuTracker.getStats((st) -> {
14368                 return st.vsize > 0;
14369             });
14370         }
14371         final int statsCount = stats.size();
14372         for (int i = 0; i < statsCount; i++) {
14373             ProcessCpuTracker.Stats st = stats.get(i);
14374             long pss = Debug.getPss(st.pid, swaptrackTmp, memtrackTmp);
14375             if (pss > 0) {
14376                 if (infoMap.indexOfKey(st.pid) < 0) {
14377                     ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid,
14378                             ProcessList.NATIVE_ADJ, -1, "native", null);
14379                     mi.pss = pss;
14380                     mi.swapPss = swaptrackTmp[1];
14381                     mi.memtrack = memtrackTmp[0];
14382                     memInfos.add(mi);
14383                 }
14384             }
14385         }
14386 
14387         long totalPss = 0;
14388         long totalSwapPss = 0;
14389         long totalMemtrack = 0;
14390         for (int i=0, N=memInfos.size(); i<N; i++) {
14391             ProcessMemInfo mi = memInfos.get(i);
14392             if (mi.pss == 0) {
14393                 mi.pss = Debug.getPss(mi.pid, swaptrackTmp, memtrackTmp);
14394                 mi.swapPss = swaptrackTmp[1];
14395                 mi.memtrack = memtrackTmp[0];
14396             }
14397             totalPss += mi.pss;
14398             totalSwapPss += mi.swapPss;
14399             totalMemtrack += mi.memtrack;
14400         }
14401         Collections.sort(memInfos, new Comparator<ProcessMemInfo>() {
14402             @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) {
14403                 if (lhs.oomAdj != rhs.oomAdj) {
14404                     return lhs.oomAdj < rhs.oomAdj ? -1 : 1;
14405                 }
14406                 if (lhs.pss != rhs.pss) {
14407                     return lhs.pss < rhs.pss ? 1 : -1;
14408                 }
14409                 return 0;
14410             }
14411         });
14412 
14413         StringBuilder tag = new StringBuilder(128);
14414         StringBuilder stack = new StringBuilder(128);
14415         tag.append("Low on memory -- ");
14416         appendMemBucket(tag, totalPss, "total", false);
14417         appendMemBucket(stack, totalPss, "total", true);
14418 
14419         StringBuilder fullNativeBuilder = new StringBuilder(1024);
14420         StringBuilder shortNativeBuilder = new StringBuilder(1024);
14421         StringBuilder fullJavaBuilder = new StringBuilder(1024);
14422 
14423         boolean firstLine = true;
14424         int lastOomAdj = Integer.MIN_VALUE;
14425         long extraNativeRam = 0;
14426         long extraNativeMemtrack = 0;
14427         long cachedPss = 0;
14428         for (int i=0, N=memInfos.size(); i<N; i++) {
14429             ProcessMemInfo mi = memInfos.get(i);
14430 
14431             if (mi.oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
14432                 cachedPss += mi.pss;
14433             }
14434 
14435             if (mi.oomAdj != ProcessList.NATIVE_ADJ
14436                     && (mi.oomAdj < ProcessList.SERVICE_ADJ
14437                             || mi.oomAdj == ProcessList.HOME_APP_ADJ
14438                             || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) {
14439                 if (lastOomAdj != mi.oomAdj) {
14440                     lastOomAdj = mi.oomAdj;
14441                     if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14442                         tag.append(" / ");
14443                     }
14444                     if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) {
14445                         if (firstLine) {
14446                             stack.append(":");
14447                             firstLine = false;
14448                         }
14449                         stack.append("\n\t at ");
14450                     } else {
14451                         stack.append("$");
14452                     }
14453                 } else {
14454                     tag.append(" ");
14455                     stack.append("$");
14456                 }
14457                 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14458                     appendMemBucket(tag, mi.pss, mi.name, false);
14459                 }
14460                 appendMemBucket(stack, mi.pss, mi.name, true);
14461                 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ
14462                         && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) {
14463                     stack.append("(");
14464                     for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
14465                         if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) {
14466                             stack.append(DUMP_MEM_OOM_LABEL[k]);
14467                             stack.append(":");
14468                             stack.append(DUMP_MEM_OOM_ADJ[k]);
14469                         }
14470                     }
14471                     stack.append(")");
14472                 }
14473             }
14474 
14475             appendMemInfo(fullNativeBuilder, mi);
14476             if (mi.oomAdj == ProcessList.NATIVE_ADJ) {
14477                 // The short form only has native processes that are >= 512K.
14478                 if (mi.pss >= 512) {
14479                     appendMemInfo(shortNativeBuilder, mi);
14480                 } else {
14481                     extraNativeRam += mi.pss;
14482                     extraNativeMemtrack += mi.memtrack;
14483                 }
14484             } else {
14485                 // Short form has all other details, but if we have collected RAM
14486                 // from smaller native processes let's dump a summary of that.
14487                 if (extraNativeRam > 0) {
14488                     appendBasicMemEntry(shortNativeBuilder, ProcessList.NATIVE_ADJ,
14489                             -1, extraNativeRam, extraNativeMemtrack, "(Other native)");
14490                     shortNativeBuilder.append('\n');
14491                     extraNativeRam = 0;
14492                 }
14493                 appendMemInfo(fullJavaBuilder, mi);
14494             }
14495         }
14496 
14497         fullJavaBuilder.append("           ");
14498         ProcessList.appendRamKb(fullJavaBuilder, totalPss);
14499         fullJavaBuilder.append(": TOTAL");
14500         if (totalMemtrack > 0) {
14501             fullJavaBuilder.append(" (");
14502             fullJavaBuilder.append(stringifyKBSize(totalMemtrack));
14503             fullJavaBuilder.append(" memtrack)");
14504         } else {
14505         }
14506         fullJavaBuilder.append("\n");
14507 
14508         MemInfoReader memInfo = new MemInfoReader();
14509         memInfo.readMemInfo();
14510         final long[] infos = memInfo.getRawInfo();
14511 
14512         StringBuilder memInfoBuilder = new StringBuilder(1024);
14513         Debug.getMemInfo(infos);
14514         memInfoBuilder.append("  MemInfo: ");
14515         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SLAB])).append(" slab, ");
14516         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SHMEM])).append(" shmem, ");
14517         memInfoBuilder.append(stringifyKBSize(
14518                                   infos[Debug.MEMINFO_VM_ALLOC_USED])).append(" vm alloc, ");
14519         memInfoBuilder.append(stringifyKBSize(
14520                                   infos[Debug.MEMINFO_PAGE_TABLES])).append(" page tables ");
14521         memInfoBuilder.append(stringifyKBSize(
14522                                   infos[Debug.MEMINFO_KERNEL_STACK])).append(" kernel stack\n");
14523         memInfoBuilder.append("           ");
14524         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_BUFFERS])).append(" buffers, ");
14525         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_CACHED])).append(" cached, ");
14526         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_MAPPED])).append(" mapped, ");
14527         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_FREE])).append(" free\n");
14528         if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) {
14529             memInfoBuilder.append("  ZRAM: ");
14530             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_ZRAM_TOTAL]));
14531             memInfoBuilder.append(" RAM, ");
14532             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_TOTAL]));
14533             memInfoBuilder.append(" swap total, ");
14534             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_FREE]));
14535             memInfoBuilder.append(" swap free\n");
14536         }
14537         final long[] ksm = getKsmInfo();
14538         if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
14539                 || ksm[KSM_VOLATILE] != 0) {
14540             memInfoBuilder.append("  KSM: ");
14541             memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARING]));
14542             memInfoBuilder.append(" saved from shared ");
14543             memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARED]));
14544             memInfoBuilder.append("\n       ");
14545             memInfoBuilder.append(stringifyKBSize(ksm[KSM_UNSHARED]));
14546             memInfoBuilder.append(" unshared; ");
14547             memInfoBuilder.append(stringifyKBSize(ksm[KSM_VOLATILE]));
14548             memInfoBuilder.append(" volatile\n");
14549         }
14550         memInfoBuilder.append("  Free RAM: ");
14551         memInfoBuilder.append(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
14552                 + memInfo.getFreeSizeKb()));
14553         memInfoBuilder.append("\n");
14554         long kernelUsed = memInfo.getKernelUsedSizeKb();
14555         final long ionHeap = Debug.getIonHeapsSizeKb();
14556         if (ionHeap > 0) {
14557             final long ionMapped = Debug.getIonMappedSizeKb();
14558             final long ionUnmapped = ionHeap - ionMapped;
14559             final long ionPool = Debug.getIonPoolsSizeKb();
14560             memInfoBuilder.append("       ION: ");
14561             memInfoBuilder.append(stringifyKBSize(ionHeap + ionPool));
14562             memInfoBuilder.append("\n");
14563             // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
14564             // set on ION VMAs, therefore consider the entire ION heap as used kernel memory
14565             kernelUsed += ionHeap;
14566         }
14567         memInfoBuilder.append("  Used RAM: ");
14568         memInfoBuilder.append(stringifyKBSize(
14569                                   totalPss - cachedPss + kernelUsed));
14570         memInfoBuilder.append("\n");
14571         memInfoBuilder.append("  Lost RAM: ");
14572         memInfoBuilder.append(stringifyKBSize(memInfo.getTotalSizeKb()
14573                 - (totalPss - totalSwapPss) - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
14574                 - kernelUsed - memInfo.getZramTotalSizeKb()));
14575         memInfoBuilder.append("\n");
14576         Slog.i(TAG, "Low on memory:");
14577         Slog.i(TAG, shortNativeBuilder.toString());
14578         Slog.i(TAG, fullJavaBuilder.toString());
14579         Slog.i(TAG, memInfoBuilder.toString());
14580 
14581         StringBuilder dropBuilder = new StringBuilder(1024);
14582         /*
14583         StringWriter oomSw = new StringWriter();
14584         PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256);
14585         StringWriter catSw = new StringWriter();
14586         PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
14587         String[] emptyArgs = new String[] { };
14588         dumpApplicationMemoryUsage(null, oomPw, "  ", emptyArgs, true, catPw);
14589         oomPw.flush();
14590         String oomString = oomSw.toString();
14591         */
14592         dropBuilder.append("Low on memory:");
14593         dropBuilder.append(stack);
14594         dropBuilder.append('\n');
14595         dropBuilder.append(fullNativeBuilder);
14596         dropBuilder.append(fullJavaBuilder);
14597         dropBuilder.append('\n');
14598         dropBuilder.append(memInfoBuilder);
14599         dropBuilder.append('\n');
14600         /*
14601         dropBuilder.append(oomString);
14602         dropBuilder.append('\n');
14603         */
14604         StringWriter catSw = new StringWriter();
14605         synchronized (ActivityManagerService.this) {
14606             PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
14607             String[] emptyArgs = new String[] { };
14608             catPw.println();
14609             dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null, -1);
14610             catPw.println();
14611             mServices.newServiceDumperLocked(null, catPw, emptyArgs, 0,
14612                     false, null).dumpLocked();
14613             catPw.println();
14614             mAtmInternal.dump(DUMP_ACTIVITIES_CMD, null, catPw, emptyArgs, 0, false, false, null);
14615             catPw.flush();
14616         }
14617         dropBuilder.append(catSw.toString());
14618         FrameworkStatsLog.write(FrameworkStatsLog.LOW_MEM_REPORTED);
14619         addErrorToDropBox("lowmem", null, "system_server", null,
14620                 null, null, tag.toString(), dropBuilder.toString(), null, null);
14621         //Slog.i(TAG, "Sent to dropbox:");
14622         //Slog.i(TAG, dropBuilder.toString());
14623         synchronized (ActivityManagerService.this) {
14624             long now = SystemClock.uptimeMillis();
14625             if (mLastMemUsageReportTime < now) {
14626                 mLastMemUsageReportTime = now;
14627             }
14628         }
14629     }
14630 
14631     /**
14632      * Searches array of arguments for the specified string
14633      * @param args array of argument strings
14634      * @param value value to search for
14635      * @return true if the value is contained in the array
14636      */
scanArgs(String[] args, String value)14637     private static boolean scanArgs(String[] args, String value) {
14638         if (args != null) {
14639             for (String arg : args) {
14640                 if (value.equals(arg)) {
14641                     return true;
14642                 }
14643             }
14644         }
14645         return false;
14646     }
14647 
14648     /**
14649      * Remove the dying provider from known provider map and launching provider map.
14650      * @param proc The dying process recoder
14651      * @param cpr The provider to be removed.
14652      * @param always If true, remove the provider from launching map always, no more restart attempt
14653      * @return true if the given provider is in launching
14654      */
removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, boolean always)14655     private final boolean removeDyingProviderLocked(ProcessRecord proc,
14656             ContentProviderRecord cpr, boolean always) {
14657         boolean inLaunching = mLaunchingProviders.contains(cpr);
14658         if (inLaunching && !always && ++cpr.mRestartCount > ContentProviderRecord.MAX_RETRY_COUNT) {
14659             // It's being launched but we've reached maximum attempts, force the removal
14660             always = true;
14661         }
14662 
14663         if (!inLaunching || always) {
14664             synchronized (cpr) {
14665                 cpr.launchingApp = null;
14666                 cpr.notifyAll();
14667             }
14668             final int userId = UserHandle.getUserId(cpr.uid);
14669             // Don't remove from provider map if it doesn't match
14670             // could be a new content provider is starting
14671             if (mProviderMap.getProviderByClass(cpr.name, userId) == cpr) {
14672                 mProviderMap.removeProviderByClass(cpr.name, userId);
14673             }
14674             String names[] = cpr.info.authority.split(";");
14675             for (int j = 0; j < names.length; j++) {
14676                 // Don't remove from provider map if it doesn't match
14677                 // could be a new content provider is starting
14678                 if (mProviderMap.getProviderByName(names[j], userId) == cpr) {
14679                     mProviderMap.removeProviderByName(names[j], userId);
14680                 }
14681             }
14682         }
14683 
14684         for (int i = cpr.connections.size() - 1; i >= 0; i--) {
14685             ContentProviderConnection conn = cpr.connections.get(i);
14686             if (conn.waiting) {
14687                 // If this connection is waiting for the provider, then we don't
14688                 // need to mess with its process unless we are always removing
14689                 // or for some reason the provider is not currently launching.
14690                 if (inLaunching && !always) {
14691                     continue;
14692                 }
14693             }
14694             ProcessRecord capp = conn.client;
14695             conn.dead = true;
14696             if (conn.stableCount > 0) {
14697                 if (!capp.isPersistent() && capp.thread != null
14698                         && capp.pid != 0
14699                         && capp.pid != MY_PID) {
14700                     capp.kill("depends on provider "
14701                             + cpr.name.flattenToShortString()
14702                             + " in dying proc " + (proc != null ? proc.processName : "??")
14703                             + " (adj " + (proc != null ? proc.setAdj : "??") + ")",
14704                             ApplicationExitInfo.REASON_DEPENDENCY_DIED,
14705                             ApplicationExitInfo.SUBREASON_UNKNOWN,
14706                             true);
14707                 }
14708             } else if (capp.thread != null && conn.provider.provider != null) {
14709                 try {
14710                     capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
14711                 } catch (RemoteException e) {
14712                 }
14713                 // In the protocol here, we don't expect the client to correctly
14714                 // clean up this connection, we'll just remove it.
14715                 cpr.connections.remove(i);
14716                 if (conn.client.conProviders.remove(conn)) {
14717                     stopAssociationLocked(capp.uid, capp.processName, cpr.uid,
14718                             cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
14719                 }
14720             }
14721         }
14722 
14723         if (inLaunching && always) {
14724             mLaunchingProviders.remove(cpr);
14725             cpr.mRestartCount = 0;
14726             inLaunching = false;
14727         }
14728         return inLaunching;
14729     }
14730 
14731     /**
14732      * Main code for cleaning up a process when it has gone away.  This is
14733      * called both as a result of the process dying, or directly when stopping
14734      * a process when running in single process mode.
14735      *
14736      * @return Returns true if the given process has been restarted, so the
14737      * app that was passed in must remain on the process lists.
14738      */
14739     @GuardedBy("this")
cleanUpApplicationRecordLocked(ProcessRecord app, boolean restarting, boolean allowRestart, int index, boolean replacingPid)14740     final boolean cleanUpApplicationRecordLocked(ProcessRecord app,
14741             boolean restarting, boolean allowRestart, int index, boolean replacingPid) {
14742         if (index >= 0) {
14743             removeLruProcessLocked(app);
14744             ProcessList.remove(app.pid);
14745         }
14746 
14747         mProcessesToGc.remove(app);
14748         mPendingPssProcesses.remove(app);
14749         ProcessList.abortNextPssTime(app.procStateMemTracker);
14750 
14751         // Dismiss any open dialogs.
14752         app.getDialogController().clearAllErrorDialogs();
14753 
14754         app.setCrashing(false);
14755         app.setNotResponding(false);
14756 
14757         app.resetPackageList(mProcessStats);
14758         app.unlinkDeathRecipient();
14759         app.makeInactive(mProcessStats);
14760         app.waitingToKill = null;
14761         app.forcingToImportant = null;
14762         updateProcessForegroundLocked(app, false, 0, false);
14763         app.setHasForegroundActivities(false);
14764         app.hasShownUi = false;
14765         app.treatLikeActivity = false;
14766         app.hasAboveClient = false;
14767         app.setHasClientActivities(false);
14768 
14769         mServices.killServicesLocked(app, allowRestart);
14770 
14771         boolean restart = false;
14772 
14773         // Remove published content providers.
14774         for (int i = app.pubProviders.size() - 1; i >= 0; i--) {
14775             ContentProviderRecord cpr = app.pubProviders.valueAt(i);
14776             if (cpr.proc != app) {
14777                 // If the hosting process record isn't really us, bail out
14778                 continue;
14779             }
14780             final boolean alwaysRemove = app.bad || !allowRestart;
14781             final boolean inLaunching = removeDyingProviderLocked(app, cpr, alwaysRemove);
14782             if (!alwaysRemove && inLaunching && cpr.hasConnectionOrHandle()) {
14783                 // We left the provider in the launching list, need to
14784                 // restart it.
14785                 restart = true;
14786             }
14787 
14788             cpr.provider = null;
14789             cpr.setProcess(null);
14790         }
14791         app.pubProviders.clear();
14792 
14793         // Take care of any launching providers waiting for this process.
14794         if (cleanupAppInLaunchingProvidersLocked(app, false)) {
14795             mProcessList.noteProcessDiedLocked(app);
14796             restart = true;
14797         }
14798 
14799         // Unregister from connected content providers.
14800         if (!app.conProviders.isEmpty()) {
14801             for (int i = app.conProviders.size() - 1; i >= 0; i--) {
14802                 ContentProviderConnection conn = app.conProviders.get(i);
14803                 conn.provider.connections.remove(conn);
14804                 stopAssociationLocked(app.uid, app.processName, conn.provider.uid,
14805                         conn.provider.appInfo.longVersionCode, conn.provider.name,
14806                         conn.provider.info.processName);
14807             }
14808             app.conProviders.clear();
14809         }
14810 
14811         // At this point there may be remaining entries in mLaunchingProviders
14812         // where we were the only one waiting, so they are no longer of use.
14813         // Look for these and clean up if found.
14814         // XXX Commented out for now.  Trying to figure out a way to reproduce
14815         // the actual situation to identify what is actually going on.
14816         if (false) {
14817             for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
14818                 ContentProviderRecord cpr = mLaunchingProviders.get(i);
14819                 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
14820                     synchronized (cpr) {
14821                         cpr.launchingApp = null;
14822                         cpr.notifyAll();
14823                     }
14824                 }
14825             }
14826         }
14827 
14828         skipCurrentReceiverLocked(app);
14829 
14830         // Unregister any receivers.
14831         for (int i = app.receivers.size() - 1; i >= 0; i--) {
14832             removeReceiverLocked(app.receivers.valueAt(i));
14833         }
14834         app.receivers.clear();
14835 
14836         // If the app is undergoing backup, tell the backup manager about it
14837         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
14838         if (backupTarget != null && app.pid == backupTarget.app.pid) {
14839             if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App "
14840                     + backupTarget.appInfo + " died during backup");
14841             mHandler.post(new Runnable() {
14842                 @Override
14843                 public void run(){
14844                     try {
14845                         IBackupManager bm = IBackupManager.Stub.asInterface(
14846                                 ServiceManager.getService(Context.BACKUP_SERVICE));
14847                         bm.agentDisconnectedForUser(app.userId, app.info.packageName);
14848                     } catch (RemoteException e) {
14849                         // can't happen; backup manager is local
14850                     }
14851                 }
14852             });
14853         }
14854 
14855         for (int i = mPendingProcessChanges.size() - 1; i >= 0; i--) {
14856             ProcessChangeItem item = mPendingProcessChanges.get(i);
14857             if (app.pid > 0 && item.pid == app.pid) {
14858                 mPendingProcessChanges.remove(i);
14859                 mAvailProcessChanges.add(item);
14860             }
14861         }
14862         mUiHandler.obtainMessage(DISPATCH_PROCESS_DIED_UI_MSG, app.pid, app.info.uid,
14863                 null).sendToTarget();
14864 
14865         // If this is a precede instance of another process instance
14866         allowRestart = true;
14867         synchronized (app) {
14868             if (app.mSuccessor != null) {
14869                 // We don't allow restart with this ProcessRecord now,
14870                 // because we have created a new one already.
14871                 allowRestart = false;
14872                 // If it's persistent, add the successor to mPersistentStartingProcesses
14873                 if (app.isPersistent() && !app.removed) {
14874                     if (mPersistentStartingProcesses.indexOf(app.mSuccessor) < 0) {
14875                         mPersistentStartingProcesses.add(app.mSuccessor);
14876                     }
14877                 }
14878                 // clean up the field so the successor's proc starter could proceed.
14879                 app.mSuccessor.mPrecedence = null;
14880                 app.mSuccessor = null;
14881                 // Notify if anyone is waiting for it.
14882                 app.notifyAll();
14883             }
14884         }
14885 
14886         // If the caller is restarting this app, then leave it in its
14887         // current lists and let the caller take care of it.
14888         if (restarting) {
14889             return false;
14890         }
14891 
14892         if (!app.isPersistent() || app.isolated) {
14893             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
14894                     "Removing non-persistent process during cleanup: " + app);
14895             if (!replacingPid) {
14896                 mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
14897             }
14898             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
14899         } else if (!app.removed) {
14900             // This app is persistent, so we need to keep its record around.
14901             // If it is not already on the pending app list, add it there
14902             // and start a new process for it.
14903             if (mPersistentStartingProcesses.indexOf(app) < 0) {
14904                 mPersistentStartingProcesses.add(app);
14905                 restart = true;
14906             }
14907         }
14908         if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(
14909                 TAG_CLEANUP, "Clean-up removing on hold: " + app);
14910         mProcessesOnHold.remove(app);
14911 
14912         mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController());
14913         mProcessList.noteProcessDiedLocked(app);
14914 
14915         if (restart && allowRestart && !app.isolated) {
14916             // We have components that still need to be running in the
14917             // process, so re-launch it.
14918             if (index < 0) {
14919                 ProcessList.remove(app.pid);
14920             }
14921 
14922             // Remove provider publish timeout because we will start a new timeout when the
14923             // restarted process is attaching (if the process contains launching providers).
14924             mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, app);
14925 
14926             mProcessList.addProcessNameLocked(app);
14927             app.pendingStart = false;
14928             mProcessList.startProcessLocked(app,
14929                     new HostingRecord("restart", app.processName),
14930                     ZYGOTE_POLICY_FLAG_EMPTY);
14931             return true;
14932         } else if (app.pid > 0 && app.pid != MY_PID) {
14933             // Goodbye!
14934             removePidLocked(app);
14935             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
14936             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
14937             if (app.isolated) {
14938                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
14939             }
14940             app.setPid(0);
14941         }
14942         return false;
14943     }
14944 
checkAppInLaunchingProvidersLocked(ProcessRecord app)14945     boolean checkAppInLaunchingProvidersLocked(ProcessRecord app) {
14946         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
14947             ContentProviderRecord cpr = mLaunchingProviders.get(i);
14948             if (cpr.launchingApp == app) {
14949                 return true;
14950             }
14951         }
14952         return false;
14953     }
14954 
cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad)14955     boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
14956         // Look through the content providers we are waiting to have launched,
14957         // and if any run in this process then either schedule a restart of
14958         // the process or kill the client waiting for it if this process has
14959         // gone bad.
14960         boolean restart = false;
14961         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
14962             ContentProviderRecord cpr = mLaunchingProviders.get(i);
14963             if (cpr.launchingApp == app) {
14964                 if (++cpr.mRestartCount > ContentProviderRecord.MAX_RETRY_COUNT) {
14965                     // It's being launched but we've reached maximum attempts, mark it as bad
14966                     alwaysBad = true;
14967                 }
14968                 if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) {
14969                     restart = true;
14970                 } else {
14971                     removeDyingProviderLocked(app, cpr, true);
14972                 }
14973             }
14974         }
14975         return restart;
14976     }
14977 
14978     // =========================================================
14979     // SERVICES
14980     // =========================================================
14981 
14982     @Override
getServices(int maxNum, int flags)14983     public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) {
14984         enforceNotIsolatedCaller("getServices");
14985 
14986         final int callingUid = Binder.getCallingUid();
14987         final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission(
14988             INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED);
14989         final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices",
14990                 Binder.getCallingPid(), callingUid);
14991         synchronized (this) {
14992             return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid,
14993                 allowed, canInteractAcrossUsers);
14994         }
14995     }
14996 
14997     @Override
getRunningServiceControlPanel(ComponentName name)14998     public PendingIntent getRunningServiceControlPanel(ComponentName name) {
14999         enforceNotIsolatedCaller("getRunningServiceControlPanel");
15000         synchronized (this) {
15001             return mServices.getRunningServiceControlPanelLocked(name);
15002         }
15003     }
15004 
15005     @Override
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, String callingFeatureId, int userId)15006     public ComponentName startService(IApplicationThread caller, Intent service,
15007             String resolvedType, boolean requireForeground, String callingPackage,
15008             String callingFeatureId, int userId)
15009             throws TransactionTooLargeException {
15010         enforceNotIsolatedCaller("startService");
15011         // Refuse possible leaked file descriptors
15012         if (service != null && service.hasFileDescriptors() == true) {
15013             throw new IllegalArgumentException("File descriptors passed in Intent");
15014         }
15015 
15016         if (callingPackage == null) {
15017             throw new IllegalArgumentException("callingPackage cannot be null");
15018         }
15019 
15020         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
15021                 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
15022         synchronized(this) {
15023             final int callingPid = Binder.getCallingPid();
15024             final int callingUid = Binder.getCallingUid();
15025             final long origId = Binder.clearCallingIdentity();
15026             ComponentName res;
15027             try {
15028                 res = mServices.startServiceLocked(caller, service,
15029                         resolvedType, callingPid, callingUid,
15030                         requireForeground, callingPackage, callingFeatureId, userId);
15031             } finally {
15032                 Binder.restoreCallingIdentity(origId);
15033             }
15034             return res;
15035         }
15036     }
15037 
15038     @Override
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)15039     public int stopService(IApplicationThread caller, Intent service,
15040             String resolvedType, int userId) {
15041         enforceNotIsolatedCaller("stopService");
15042         // Refuse possible leaked file descriptors
15043         if (service != null && service.hasFileDescriptors() == true) {
15044             throw new IllegalArgumentException("File descriptors passed in Intent");
15045         }
15046 
15047         synchronized(this) {
15048             return mServices.stopServiceLocked(caller, service, resolvedType, userId);
15049         }
15050     }
15051 
15052     @Override
peekService(Intent service, String resolvedType, String callingPackage)15053     public IBinder peekService(Intent service, String resolvedType, String callingPackage) {
15054         enforceNotIsolatedCaller("peekService");
15055         // Refuse possible leaked file descriptors
15056         if (service != null && service.hasFileDescriptors() == true) {
15057             throw new IllegalArgumentException("File descriptors passed in Intent");
15058         }
15059 
15060         if (callingPackage == null) {
15061             throw new IllegalArgumentException("callingPackage cannot be null");
15062         }
15063 
15064         synchronized(this) {
15065             return mServices.peekServiceLocked(service, resolvedType, callingPackage);
15066         }
15067     }
15068 
15069     @Override
stopServiceToken(ComponentName className, IBinder token, int startId)15070     public boolean stopServiceToken(ComponentName className, IBinder token,
15071             int startId) {
15072         synchronized(this) {
15073             return mServices.stopServiceTokenLocked(className, token, startId);
15074         }
15075     }
15076 
15077     @Override
setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)15078     public void setServiceForeground(ComponentName className, IBinder token,
15079             int id, Notification notification, int flags, int foregroundServiceType) {
15080         synchronized(this) {
15081             mServices.setServiceForegroundLocked(className, token, id, notification, flags,
15082                     foregroundServiceType);
15083         }
15084     }
15085 
15086     @Override
getForegroundServiceType(ComponentName className, IBinder token)15087     public int getForegroundServiceType(ComponentName className, IBinder token) {
15088         synchronized (this) {
15089             return mServices.getForegroundServiceTypeLocked(className, token);
15090         }
15091     }
15092 
15093     @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)15094     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
15095             boolean requireFull, String name, String callerPackage) {
15096         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
15097                 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
15098     }
15099 
isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)15100     boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
15101             String className, int flags) {
15102         boolean result = false;
15103         // For apps that don't have pre-defined UIDs, check for permission
15104         if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) {
15105             if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
15106                 if (ActivityManager.checkUidPermission(
15107                         INTERACT_ACROSS_USERS,
15108                         aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
15109                     ComponentName comp = new ComponentName(aInfo.packageName, className);
15110                     String msg = "Permission Denial: Component " + comp.flattenToShortString()
15111                             + " requests FLAG_SINGLE_USER, but app does not hold "
15112                             + INTERACT_ACROSS_USERS;
15113                     Slog.w(TAG, msg);
15114                     throw new SecurityException(msg);
15115                 }
15116                 // Permission passed
15117                 result = true;
15118             }
15119         } else if ("system".equals(componentProcessName)) {
15120             result = true;
15121         } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
15122             // Phone app and persistent apps are allowed to export singleuser providers.
15123             result = UserHandle.isSameApp(aInfo.uid, PHONE_UID)
15124                     || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
15125         }
15126         if (DEBUG_MU) Slog.v(TAG_MU,
15127                 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x"
15128                 + Integer.toHexString(flags) + ") = " + result);
15129         return result;
15130     }
15131 
15132     /**
15133      * Checks to see if the caller is in the same app as the singleton
15134      * component, or the component is in a special app. It allows special apps
15135      * to export singleton components but prevents exporting singleton
15136      * components for regular apps.
15137      */
isValidSingletonCall(int callingUid, int componentUid)15138     boolean isValidSingletonCall(int callingUid, int componentUid) {
15139         int componentAppId = UserHandle.getAppId(componentUid);
15140         return UserHandle.isSameApp(callingUid, componentUid)
15141                 || componentAppId == SYSTEM_UID
15142                 || componentAppId == PHONE_UID
15143                 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
15144                         == PackageManager.PERMISSION_GRANTED;
15145     }
15146 
bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)15147     public int bindService(IApplicationThread caller, IBinder token, Intent service,
15148             String resolvedType, IServiceConnection connection, int flags,
15149             String callingPackage, int userId) throws TransactionTooLargeException {
15150         return bindIsolatedService(caller, token, service, resolvedType, connection, flags,
15151                 null, callingPackage, userId);
15152     }
15153 
bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)15154     public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
15155             String resolvedType, IServiceConnection connection, int flags, String instanceName,
15156             String callingPackage, int userId) throws TransactionTooLargeException {
15157         enforceNotIsolatedCaller("bindService");
15158 
15159         // Refuse possible leaked file descriptors
15160         if (service != null && service.hasFileDescriptors() == true) {
15161             throw new IllegalArgumentException("File descriptors passed in Intent");
15162         }
15163 
15164         if (callingPackage == null) {
15165             throw new IllegalArgumentException("callingPackage cannot be null");
15166         }
15167 
15168         // Ensure that instanceName, which is caller provided, does not contain
15169         // unusual characters.
15170         if (instanceName != null) {
15171             for (int i = 0; i < instanceName.length(); ++i) {
15172                 char c = instanceName.charAt(i);
15173                 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
15174                             || (c >= '0' && c <= '9') || c == '_' || c == '.')) {
15175                     throw new IllegalArgumentException("Illegal instanceName");
15176                 }
15177             }
15178         }
15179 
15180         synchronized(this) {
15181             return mServices.bindServiceLocked(caller, token, service,
15182                     resolvedType, connection, flags, instanceName, callingPackage, userId);
15183         }
15184     }
15185 
updateServiceGroup(IServiceConnection connection, int group, int importance)15186     public void updateServiceGroup(IServiceConnection connection, int group, int importance) {
15187         synchronized (this) {
15188             mServices.updateServiceGroupLocked(connection, group, importance);
15189         }
15190     }
15191 
unbindService(IServiceConnection connection)15192     public boolean unbindService(IServiceConnection connection) {
15193         synchronized (this) {
15194             return mServices.unbindServiceLocked(connection);
15195         }
15196     }
15197 
publishService(IBinder token, Intent intent, IBinder service)15198     public void publishService(IBinder token, Intent intent, IBinder service) {
15199         // Refuse possible leaked file descriptors
15200         if (intent != null && intent.hasFileDescriptors() == true) {
15201             throw new IllegalArgumentException("File descriptors passed in Intent");
15202         }
15203 
15204         synchronized(this) {
15205             if (!(token instanceof ServiceRecord)) {
15206                 throw new IllegalArgumentException("Invalid service token");
15207             }
15208             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
15209         }
15210     }
15211 
unbindFinished(IBinder token, Intent intent, boolean doRebind)15212     public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
15213         // Refuse possible leaked file descriptors
15214         if (intent != null && intent.hasFileDescriptors() == true) {
15215             throw new IllegalArgumentException("File descriptors passed in Intent");
15216         }
15217 
15218         synchronized(this) {
15219             mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
15220         }
15221     }
15222 
serviceDoneExecuting(IBinder token, int type, int startId, int res)15223     public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
15224         synchronized(this) {
15225             if (!(token instanceof ServiceRecord)) {
15226                 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
15227                 throw new IllegalArgumentException("Invalid service token");
15228             }
15229             mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
15230         }
15231     }
15232 
15233     // =========================================================
15234     // BACKUP AND RESTORE
15235     // =========================================================
15236 
15237     // Cause the target app to be launched if necessary and its backup agent
15238     // instantiated.  The backup agent will invoke backupAgentCreated() on the
15239     // activity manager to announce its creation.
bindBackupAgent(String packageName, int backupMode, int targetUserId)15240     public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId) {
15241         if (DEBUG_BACKUP) {
15242             Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
15243                     + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
15244                     + " uid = " + Process.myUid());
15245         }
15246         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
15247 
15248         // The instantiatedUserId is the user of the process the backup agent is started in. This is
15249         // different from the targetUserId which is the user whose data is to be backed up or
15250         // restored. This distinction is important for system-process packages that live in the
15251         // system user's process but backup/restore data for non-system users.
15252         // TODO (b/123688746): Handle all system-process packages with singleton check.
15253         final int instantiatedUserId =
15254                 PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId;
15255 
15256         IPackageManager pm = AppGlobals.getPackageManager();
15257         ApplicationInfo app = null;
15258         try {
15259             app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
15260         } catch (RemoteException e) {
15261             // can't happen; package manager is process-local
15262         }
15263         if (app == null) {
15264             Slog.w(TAG, "Unable to bind backup agent for " + packageName);
15265             return false;
15266         }
15267 
15268         int oldBackupUid;
15269         int newBackupUid;
15270 
15271         synchronized(this) {
15272             // !!! TODO: currently no check here that we're already bound
15273             // Backup agent is now in use, its package can't be stopped.
15274             try {
15275                 AppGlobals.getPackageManager().setPackageStoppedState(
15276                         app.packageName, false, UserHandle.getUserId(app.uid));
15277             } catch (RemoteException e) {
15278             } catch (IllegalArgumentException e) {
15279                 Slog.w(TAG, "Failed trying to unstop package "
15280                         + app.packageName + ": " + e);
15281             }
15282 
15283             BackupRecord r = new BackupRecord(app, backupMode, targetUserId);
15284             ComponentName hostingName =
15285                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL)
15286                             ? new ComponentName(app.packageName, app.backupAgentName)
15287                             : new ComponentName("android", "FullBackupAgent");
15288 
15289             // startProcessLocked() returns existing proc's record if it's already running
15290             ProcessRecord proc = startProcessLocked(app.processName, app,
15291                     false, 0,
15292                     new HostingRecord("backup", hostingName),
15293                     ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false, false);
15294             if (proc == null) {
15295                 Slog.e(TAG, "Unable to start backup agent process " + r);
15296                 return false;
15297             }
15298 
15299             // If the app is a regular app (uid >= 10000) and not the system server or phone
15300             // process, etc, then mark it as being in full backup so that certain calls to the
15301             // process can be blocked. This is not reset to false anywhere because we kill the
15302             // process after the full backup is done and the ProcessRecord will vaporize anyway.
15303             if (UserHandle.isApp(app.uid) &&
15304                     backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) {
15305                 proc.inFullBackup = true;
15306             }
15307             r.app = proc;
15308             final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
15309             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
15310             newBackupUid = proc.inFullBackup ? r.appInfo.uid : -1;
15311             mBackupTargets.put(targetUserId, r);
15312 
15313             // Try not to kill the process during backup
15314             updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE);
15315 
15316             // If the process is already attached, schedule the creation of the backup agent now.
15317             // If it is not yet live, this will be done when it attaches to the framework.
15318             if (proc.thread != null) {
15319                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
15320                 try {
15321                     proc.thread.scheduleCreateBackupAgent(app,
15322                             compatibilityInfoForPackage(app), backupMode, targetUserId);
15323                 } catch (RemoteException e) {
15324                     // Will time out on the backup manager side
15325                 }
15326             } else {
15327                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach");
15328             }
15329             // Invariants: at this point, the target app process exists and the application
15330             // is either already running or in the process of coming up.  mBackupTarget and
15331             // mBackupAppName describe the app, so that when it binds back to the AM we
15332             // know that it's scheduled for a backup-agent operation.
15333         }
15334 
15335         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
15336         if (oldBackupUid != -1) {
15337             js.removeBackingUpUid(oldBackupUid);
15338         }
15339         if (newBackupUid != -1) {
15340             js.addBackingUpUid(newBackupUid);
15341         }
15342 
15343         return true;
15344     }
15345 
clearPendingBackup(int userId)15346     private void clearPendingBackup(int userId) {
15347         if (DEBUG_BACKUP) {
15348             Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = "
15349                     + Binder.getCallingUid() + " uid = " + Process.myUid());
15350         }
15351 
15352         synchronized (this) {
15353             mBackupTargets.delete(userId);
15354         }
15355 
15356         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
15357         js.clearAllBackingUpUids();
15358     }
15359 
15360     // A backup agent has just come up
15361     @Override
backupAgentCreated(String agentPackageName, IBinder agent, int userId)15362     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
15363         // Resolve the target user id and enforce permissions.
15364         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15365                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
15366         if (DEBUG_BACKUP) {
15367             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
15368                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
15369                     + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid());
15370         }
15371 
15372         synchronized(this) {
15373             final BackupRecord backupTarget = mBackupTargets.get(userId);
15374             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
15375             if (!agentPackageName.equals(backupAppName)) {
15376                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
15377                 return;
15378             }
15379         }
15380 
15381         long oldIdent = Binder.clearCallingIdentity();
15382         try {
15383             IBackupManager bm = IBackupManager.Stub.asInterface(
15384                     ServiceManager.getService(Context.BACKUP_SERVICE));
15385             bm.agentConnectedForUser(userId, agentPackageName, agent);
15386         } catch (RemoteException e) {
15387             // can't happen; the backup manager service is local
15388         } catch (Exception e) {
15389             Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
15390             e.printStackTrace();
15391         } finally {
15392             Binder.restoreCallingIdentity(oldIdent);
15393         }
15394     }
15395 
15396     // done with this agent
unbindBackupAgent(ApplicationInfo appInfo)15397     public void unbindBackupAgent(ApplicationInfo appInfo) {
15398         if (DEBUG_BACKUP) {
15399             Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = "
15400                     + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = "
15401                     + Process.myUid());
15402         }
15403 
15404         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent");
15405         if (appInfo == null) {
15406             Slog.w(TAG, "unbind backup agent for null app");
15407             return;
15408         }
15409 
15410         int oldBackupUid;
15411 
15412         final int userId = UserHandle.getUserId(appInfo.uid);
15413         synchronized(this) {
15414             final BackupRecord backupTarget = mBackupTargets.get(userId);
15415             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
15416             try {
15417                 if (backupAppName == null) {
15418                     Slog.w(TAG, "Unbinding backup agent with no active backup");
15419                     return;
15420                 }
15421 
15422                 if (!backupAppName.equals(appInfo.packageName)) {
15423                     Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
15424                     return;
15425                 }
15426 
15427                 // Not backing this app up any more; reset its OOM adjustment
15428                 final ProcessRecord proc = backupTarget.app;
15429                 updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE);
15430                 proc.inFullBackup = false;
15431 
15432                 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
15433 
15434                 // If the app crashed during backup, 'thread' will be null here
15435                 if (proc.thread != null) {
15436                     try {
15437                         proc.thread.scheduleDestroyBackupAgent(appInfo,
15438                                 compatibilityInfoForPackage(appInfo), userId);
15439                     } catch (Exception e) {
15440                         Slog.e(TAG, "Exception when unbinding backup agent:");
15441                         e.printStackTrace();
15442                     }
15443                 }
15444             } finally {
15445                 mBackupTargets.delete(userId);
15446             }
15447         }
15448 
15449         if (oldBackupUid != -1) {
15450             JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
15451             js.removeBackingUpUid(oldBackupUid);
15452         }
15453     }
15454 
15455     // =========================================================
15456     // BROADCASTS
15457     // =========================================================
15458 
isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)15459     private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) {
15460         if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) {
15461             return false;
15462         }
15463         // Easy case -- we have the app's ProcessRecord.
15464         if (record != null) {
15465             return record.info.isInstantApp();
15466         }
15467         // Otherwise check with PackageManager.
15468         IPackageManager pm = AppGlobals.getPackageManager();
15469         try {
15470             if (callerPackage == null) {
15471                 final String[] packageNames = pm.getPackagesForUid(uid);
15472                 if (packageNames == null || packageNames.length == 0) {
15473                     throw new IllegalArgumentException("Unable to determine caller package name");
15474                 }
15475                 // Instant Apps can't use shared uids, so its safe to only check the first package.
15476                 callerPackage = packageNames[0];
15477             }
15478             mAppOpsService.checkPackage(uid, callerPackage);
15479             return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid));
15480         } catch (RemoteException e) {
15481             Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e);
15482             return true;
15483         }
15484     }
15485 
isPendingBroadcastProcessLocked(int pid)15486     boolean isPendingBroadcastProcessLocked(int pid) {
15487         return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
15488                 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
15489                 || mOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid);
15490     }
15491 
skipPendingBroadcastLocked(int pid)15492     void skipPendingBroadcastLocked(int pid) {
15493             Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
15494             for (BroadcastQueue queue : mBroadcastQueues) {
15495                 queue.skipPendingBroadcastLocked(pid);
15496             }
15497     }
15498 
15499     // The app just attached; send any pending broadcasts that it should receive
sendPendingBroadcastsLocked(ProcessRecord app)15500     boolean sendPendingBroadcastsLocked(ProcessRecord app) {
15501         boolean didSomething = false;
15502         for (BroadcastQueue queue : mBroadcastQueues) {
15503             didSomething |= queue.sendPendingBroadcastsLocked(app);
15504         }
15505         return didSomething;
15506     }
15507 
15508     /**
15509      * @deprecated Use {@link #registerReceiverWithFeature}
15510      */
15511     @Deprecated
registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)15512     public Intent registerReceiver(IApplicationThread caller, String callerPackage,
15513             IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
15514             int flags) {
15515         return registerReceiverWithFeature(caller, callerPackage, null, receiver, filter,
15516                 permission, userId, flags);
15517     }
15518 
registerReceiverWithFeature(IApplicationThread caller, String callerPackage, String callerFeatureId, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)15519     public Intent registerReceiverWithFeature(IApplicationThread caller, String callerPackage,
15520             String callerFeatureId, IIntentReceiver receiver, IntentFilter filter,
15521             String permission, int userId, int flags) {
15522         enforceNotIsolatedCaller("registerReceiver");
15523         ArrayList<Intent> stickyIntents = null;
15524         ProcessRecord callerApp = null;
15525         final boolean visibleToInstantApps
15526                 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
15527         int callingUid;
15528         int callingPid;
15529         boolean instantApp;
15530         synchronized(this) {
15531             if (caller != null) {
15532                 callerApp = getRecordForAppLocked(caller);
15533                 if (callerApp == null) {
15534                     throw new SecurityException(
15535                             "Unable to find app for caller " + caller
15536                             + " (pid=" + Binder.getCallingPid()
15537                             + ") when registering receiver " + receiver);
15538                 }
15539                 if (callerApp.info.uid != SYSTEM_UID &&
15540                         !callerApp.pkgList.containsKey(callerPackage) &&
15541                         !"android".equals(callerPackage)) {
15542                     throw new SecurityException("Given caller package " + callerPackage
15543                             + " is not running in process " + callerApp);
15544                 }
15545                 callingUid = callerApp.info.uid;
15546                 callingPid = callerApp.pid;
15547             } else {
15548                 callerPackage = null;
15549                 callingUid = Binder.getCallingUid();
15550                 callingPid = Binder.getCallingPid();
15551             }
15552 
15553             instantApp = isInstantApp(callerApp, callerPackage, callingUid);
15554             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
15555                     ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
15556 
15557             Iterator<String> actions = filter.actionsIterator();
15558             if (actions == null) {
15559                 ArrayList<String> noAction = new ArrayList<String>(1);
15560                 noAction.add(null);
15561                 actions = noAction.iterator();
15562             }
15563 
15564             // Collect stickies of users
15565             int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) };
15566             while (actions.hasNext()) {
15567                 String action = actions.next();
15568                 for (int id : userIds) {
15569                     ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id);
15570                     if (stickies != null) {
15571                         ArrayList<Intent> intents = stickies.get(action);
15572                         if (intents != null) {
15573                             if (stickyIntents == null) {
15574                                 stickyIntents = new ArrayList<Intent>();
15575                             }
15576                             stickyIntents.addAll(intents);
15577                         }
15578                     }
15579                 }
15580             }
15581         }
15582 
15583         ArrayList<Intent> allSticky = null;
15584         if (stickyIntents != null) {
15585             final ContentResolver resolver = mContext.getContentResolver();
15586             // Look for any matching sticky broadcasts...
15587             for (int i = 0, N = stickyIntents.size(); i < N; i++) {
15588                 Intent intent = stickyIntents.get(i);
15589                 // Don't provided intents that aren't available to instant apps.
15590                 if (instantApp &&
15591                         (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) {
15592                     continue;
15593                 }
15594                 // If intent has scheme "content", it will need to acccess
15595                 // provider that needs to lock mProviderMap in ActivityThread
15596                 // and also it may need to wait application response, so we
15597                 // cannot lock ActivityManagerService here.
15598                 if (filter.match(resolver, intent, true, TAG) >= 0) {
15599                     if (allSticky == null) {
15600                         allSticky = new ArrayList<Intent>();
15601                     }
15602                     allSticky.add(intent);
15603                 }
15604             }
15605         }
15606 
15607         // The first sticky in the list is returned directly back to the client.
15608         Intent sticky = allSticky != null ? allSticky.get(0) : null;
15609         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky);
15610         if (receiver == null) {
15611             return sticky;
15612         }
15613 
15614         synchronized (this) {
15615             if (callerApp != null && (callerApp.thread == null
15616                     || callerApp.thread.asBinder() != caller.asBinder())) {
15617                 // Original caller already died
15618                 return null;
15619             }
15620             ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
15621             if (rl == null) {
15622                 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
15623                         userId, receiver);
15624                 if (rl.app != null) {
15625                     final int totalReceiversForApp = rl.app.receivers.size();
15626                     if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) {
15627                         throw new IllegalStateException("Too many receivers, total of "
15628                                 + totalReceiversForApp + ", registered for pid: "
15629                                 + rl.pid + ", callerPackage: " + callerPackage);
15630                     }
15631                     rl.app.receivers.add(rl);
15632                 } else {
15633                     try {
15634                         receiver.asBinder().linkToDeath(rl, 0);
15635                     } catch (RemoteException e) {
15636                         return sticky;
15637                     }
15638                     rl.linkedToDeath = true;
15639                 }
15640                 mRegisteredReceivers.put(receiver.asBinder(), rl);
15641             } else if (rl.uid != callingUid) {
15642                 throw new IllegalArgumentException(
15643                         "Receiver requested to register for uid " + callingUid
15644                         + " was previously registered for uid " + rl.uid
15645                         + " callerPackage is " + callerPackage);
15646             } else if (rl.pid != callingPid) {
15647                 throw new IllegalArgumentException(
15648                         "Receiver requested to register for pid " + callingPid
15649                         + " was previously registered for pid " + rl.pid
15650                         + " callerPackage is " + callerPackage);
15651             } else if (rl.userId != userId) {
15652                 throw new IllegalArgumentException(
15653                         "Receiver requested to register for user " + userId
15654                         + " was previously registered for user " + rl.userId
15655                         + " callerPackage is " + callerPackage);
15656             }
15657             BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, callerFeatureId,
15658                     permission, callingUid, userId, instantApp, visibleToInstantApps);
15659             if (rl.containsFilter(filter)) {
15660                 Slog.w(TAG, "Receiver with filter " + filter
15661                         + " already registered for pid " + rl.pid
15662                         + ", callerPackage is " + callerPackage);
15663             } else {
15664                 rl.add(bf);
15665                 if (!bf.debugCheck()) {
15666                     Slog.w(TAG, "==> For Dynamic broadcast");
15667                 }
15668                 mReceiverResolver.addFilter(bf);
15669             }
15670 
15671             // Enqueue broadcasts for all existing stickies that match
15672             // this filter.
15673             if (allSticky != null) {
15674                 ArrayList receivers = new ArrayList();
15675                 receivers.add(bf);
15676 
15677                 final int stickyCount = allSticky.size();
15678                 for (int i = 0; i < stickyCount; i++) {
15679                     Intent intent = allSticky.get(i);
15680                     BroadcastQueue queue = broadcastQueueForIntent(intent);
15681                     BroadcastRecord r = new BroadcastRecord(queue, intent, null,
15682                             null, null, -1, -1, false, null, null, OP_NONE, null, receivers,
15683                             null, 0, null, null, false, true, true, -1, false,
15684                             false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */);
15685                     queue.enqueueParallelBroadcastLocked(r);
15686                     queue.scheduleBroadcastsLocked();
15687                 }
15688             }
15689 
15690             return sticky;
15691         }
15692     }
15693 
unregisterReceiver(IIntentReceiver receiver)15694     public void unregisterReceiver(IIntentReceiver receiver) {
15695         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver);
15696 
15697         final long origId = Binder.clearCallingIdentity();
15698         try {
15699             boolean doTrim = false;
15700 
15701             synchronized(this) {
15702                 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
15703                 if (rl != null) {
15704                     final BroadcastRecord r = rl.curBroadcast;
15705                     if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) {
15706                         final boolean doNext = r.queue.finishReceiverLocked(
15707                                 r, r.resultCode, r.resultData, r.resultExtras,
15708                                 r.resultAbort, false);
15709                         if (doNext) {
15710                             doTrim = true;
15711                             r.queue.processNextBroadcast(false);
15712                         }
15713                     }
15714 
15715                     if (rl.app != null) {
15716                         rl.app.receivers.remove(rl);
15717                     }
15718                     removeReceiverLocked(rl);
15719                     if (rl.linkedToDeath) {
15720                         rl.linkedToDeath = false;
15721                         rl.receiver.asBinder().unlinkToDeath(rl, 0);
15722                     }
15723                 }
15724             }
15725 
15726             // If we actually concluded any broadcasts, we might now be able
15727             // to trim the recipients' apps from our working set
15728             if (doTrim) {
15729                 trimApplications(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
15730                 return;
15731             }
15732 
15733         } finally {
15734             Binder.restoreCallingIdentity(origId);
15735         }
15736     }
15737 
removeReceiverLocked(ReceiverList rl)15738     void removeReceiverLocked(ReceiverList rl) {
15739         mRegisteredReceivers.remove(rl.receiver.asBinder());
15740         for (int i = rl.size() - 1; i >= 0; i--) {
15741             mReceiverResolver.removeFilter(rl.get(i));
15742         }
15743     }
15744 
sendPackageBroadcastLocked(int cmd, String[] packages, int userId)15745     private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
15746         mProcessList.sendPackageBroadcastLocked(cmd, packages, userId);
15747     }
15748 
collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users, int[] broadcastWhitelist)15749     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
15750             int callingUid, int[] users, int[] broadcastWhitelist) {
15751         // TODO: come back and remove this assumption to triage all broadcasts
15752         int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
15753 
15754         List<ResolveInfo> receivers = null;
15755         try {
15756             HashSet<ComponentName> singleUserReceivers = null;
15757             boolean scannedFirstReceivers = false;
15758             for (int user : users) {
15759                 // Skip users that have Shell restrictions
15760                 if (callingUid == SHELL_UID
15761                         && mUserController.hasUserRestriction(
15762                                 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) {
15763                     continue;
15764                 }
15765                 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
15766                         .queryIntentReceivers(intent, resolvedType, pmFlags, user).getList();
15767                 if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
15768                     // If this is not the system user, we need to check for
15769                     // any receivers that should be filtered out.
15770                     for (int i=0; i<newReceivers.size(); i++) {
15771                         ResolveInfo ri = newReceivers.get(i);
15772                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
15773                             newReceivers.remove(i);
15774                             i--;
15775                         }
15776                     }
15777                 }
15778                 if (newReceivers != null && newReceivers.size() == 0) {
15779                     newReceivers = null;
15780                 }
15781                 if (receivers == null) {
15782                     receivers = newReceivers;
15783                 } else if (newReceivers != null) {
15784                     // We need to concatenate the additional receivers
15785                     // found with what we have do far.  This would be easy,
15786                     // but we also need to de-dup any receivers that are
15787                     // singleUser.
15788                     if (!scannedFirstReceivers) {
15789                         // Collect any single user receivers we had already retrieved.
15790                         scannedFirstReceivers = true;
15791                         for (int i=0; i<receivers.size(); i++) {
15792                             ResolveInfo ri = receivers.get(i);
15793                             if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
15794                                 ComponentName cn = new ComponentName(
15795                                         ri.activityInfo.packageName, ri.activityInfo.name);
15796                                 if (singleUserReceivers == null) {
15797                                     singleUserReceivers = new HashSet<ComponentName>();
15798                                 }
15799                                 singleUserReceivers.add(cn);
15800                             }
15801                         }
15802                     }
15803                     // Add the new results to the existing results, tracking
15804                     // and de-dupping single user receivers.
15805                     for (int i=0; i<newReceivers.size(); i++) {
15806                         ResolveInfo ri = newReceivers.get(i);
15807                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
15808                             ComponentName cn = new ComponentName(
15809                                     ri.activityInfo.packageName, ri.activityInfo.name);
15810                             if (singleUserReceivers == null) {
15811                                 singleUserReceivers = new HashSet<ComponentName>();
15812                             }
15813                             if (!singleUserReceivers.contains(cn)) {
15814                                 singleUserReceivers.add(cn);
15815                                 receivers.add(ri);
15816                             }
15817                         } else {
15818                             receivers.add(ri);
15819                         }
15820                     }
15821                 }
15822             }
15823         } catch (RemoteException ex) {
15824             // pm is in same process, this will never happen.
15825         }
15826         if (receivers != null && broadcastWhitelist != null) {
15827             for (int i = receivers.size() - 1; i >= 0; i--) {
15828                 final int receiverAppId = UserHandle.getAppId(
15829                         receivers.get(i).activityInfo.applicationInfo.uid);
15830                 if (receiverAppId >= Process.FIRST_APPLICATION_UID
15831                         && Arrays.binarySearch(broadcastWhitelist, receiverAppId) < 0) {
15832                     receivers.remove(i);
15833                 }
15834             }
15835         }
15836         return receivers;
15837     }
15838 
checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)15839     private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp,
15840             String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) {
15841         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
15842             // Don't yell about broadcasts sent via shell
15843             return;
15844         }
15845 
15846         final String action = intent.getAction();
15847         if (isProtectedBroadcast
15848                 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
15849                 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
15850                 || Intent.ACTION_MEDIA_BUTTON.equals(action)
15851                 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
15852                 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
15853                 || Intent.ACTION_MASTER_CLEAR.equals(action)
15854                 || Intent.ACTION_FACTORY_RESET.equals(action)
15855                 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
15856                 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
15857                 || LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION.equals(action)
15858                 || TelephonyManager.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action)
15859                 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action)
15860                 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action)
15861                 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) {
15862             // Broadcast is either protected, or it's a public action that
15863             // we've relaxed, so it's fine for system internals to send.
15864             return;
15865         }
15866 
15867         // This broadcast may be a problem...  but there are often system components that
15868         // want to send an internal broadcast to themselves, which is annoying to have to
15869         // explicitly list each action as a protected broadcast, so we will check for that
15870         // one safe case and allow it: an explicit broadcast, only being received by something
15871         // that has protected itself.
15872         if (intent.getPackage() != null || intent.getComponent() != null) {
15873             if (receivers == null || receivers.size() == 0) {
15874                 // Intent is explicit and there's no receivers.
15875                 // This happens, e.g. , when a system component sends a broadcast to
15876                 // its own runtime receiver, and there's no manifest receivers for it,
15877                 // because this method is called twice for each broadcast,
15878                 // for runtime receivers and manifest receivers and the later check would find
15879                 // no receivers.
15880                 return;
15881             }
15882             boolean allProtected = true;
15883             for (int i = receivers.size()-1; i >= 0; i--) {
15884                 Object target = receivers.get(i);
15885                 if (target instanceof ResolveInfo) {
15886                     ResolveInfo ri = (ResolveInfo)target;
15887                     if (ri.activityInfo.exported && ri.activityInfo.permission == null) {
15888                         allProtected = false;
15889                         break;
15890                     }
15891                 } else {
15892                     BroadcastFilter bf = (BroadcastFilter)target;
15893                     if (bf.requiredPermission == null) {
15894                         allProtected = false;
15895                         break;
15896                     }
15897                 }
15898             }
15899             if (allProtected) {
15900                 // All safe!
15901                 return;
15902             }
15903         }
15904 
15905         // The vast majority of broadcasts sent from system internals
15906         // should be protected to avoid security holes, so yell loudly
15907         // to ensure we examine these cases.
15908         if (callerApp != null) {
15909             Log.wtf(TAG, "Sending non-protected broadcast " + action
15910                             + " from system " + callerApp.toShortString() + " pkg " + callerPackage,
15911                     new Throwable());
15912         } else {
15913             Log.wtf(TAG, "Sending non-protected broadcast " + action
15914                             + " from system uid " + UserHandle.formatUid(callingUid)
15915                             + " pkg " + callerPackage,
15916                     new Throwable());
15917         }
15918     }
15919 
15920     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, String callerFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId)15921     final int broadcastIntentLocked(ProcessRecord callerApp,
15922             String callerPackage, String callerFeatureId, Intent intent, String resolvedType,
15923             IIntentReceiver resultTo, int resultCode, String resultData,
15924             Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
15925             boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
15926             int realCallingPid, int userId) {
15927         return broadcastIntentLocked(callerApp, callerPackage, callerFeatureId, intent,
15928                 resolvedType, resultTo, resultCode, resultData, resultExtras, requiredPermissions,
15929                 appOp, bOptions, ordered, sticky, callingPid, callingUid, realCallingUid,
15930                 realCallingPid, userId, false /* allowBackgroundActivityStarts */,
15931                 null /*broadcastWhitelist*/);
15932     }
15933 
15934     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, @Nullable String callerFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid, int realCallingPid, int userId, boolean allowBackgroundActivityStarts, @Nullable int[] broadcastWhitelist)15935     final int broadcastIntentLocked(ProcessRecord callerApp, String callerPackage,
15936             @Nullable String callerFeatureId, Intent intent, String resolvedType,
15937             IIntentReceiver resultTo, int resultCode, String resultData,
15938             Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
15939             boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
15940             int realCallingPid, int userId, boolean allowBackgroundActivityStarts,
15941             @Nullable int[] broadcastWhitelist) {
15942         intent = new Intent(intent);
15943 
15944         final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
15945         // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
15946         if (callerInstantApp) {
15947             intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
15948         }
15949 
15950         if (userId == UserHandle.USER_ALL && broadcastWhitelist != null) {
15951                 Slog.e(TAG, "broadcastWhitelist only applies when sending to individual users. "
15952                         + "Assuming restrictive whitelist.");
15953                 broadcastWhitelist = new int[]{};
15954         }
15955 
15956         // By default broadcasts do not go to stopped apps.
15957         intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
15958 
15959         // If we have not finished booting, don't allow this to launch new processes.
15960         if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
15961             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15962         }
15963 
15964         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
15965                 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
15966                 + " ordered=" + ordered + " userid=" + userId);
15967         if ((resultTo != null) && !ordered) {
15968             Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
15969         }
15970 
15971         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
15972                 ALLOW_NON_FULL, "broadcast", callerPackage);
15973 
15974         // Make sure that the user who is receiving this broadcast or its parent is running.
15975         // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
15976         if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
15977             if ((callingUid != SYSTEM_UID
15978                     || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)
15979                     && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
15980                 Slog.w(TAG, "Skipping broadcast of " + intent
15981                         + ": user " + userId + " and its parent (if any) are stopped");
15982                 return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
15983             }
15984         }
15985 
15986         final String action = intent.getAction();
15987         BroadcastOptions brOptions = null;
15988         if (bOptions != null) {
15989             brOptions = new BroadcastOptions(bOptions);
15990             if (brOptions.getTemporaryAppWhitelistDuration() > 0) {
15991                 // See if the caller is allowed to do this.  Note we are checking against
15992                 // the actual real caller (not whoever provided the operation as say a
15993                 // PendingIntent), because that who is actually supplied the arguments.
15994                 if (checkComponentPermission(
15995                         android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
15996                         realCallingPid, realCallingUid, -1, true)
15997                         != PackageManager.PERMISSION_GRANTED) {
15998                     String msg = "Permission Denial: " + intent.getAction()
15999                             + " broadcast from " + callerPackage + " (pid=" + callingPid
16000                             + ", uid=" + callingUid + ")"
16001                             + " requires "
16002                             + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
16003                     Slog.w(TAG, msg);
16004                     throw new SecurityException(msg);
16005                 }
16006             }
16007             if (brOptions.isDontSendToRestrictedApps()
16008                     && !isUidActiveLocked(callingUid)
16009                     && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
16010                 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
16011                         + " has background restrictions");
16012                 return ActivityManager.START_CANCELED;
16013             }
16014             if (brOptions.allowsBackgroundActivityStarts()) {
16015                 // See if the caller is allowed to do this.  Note we are checking against
16016                 // the actual real caller (not whoever provided the operation as say a
16017                 // PendingIntent), because that who is actually supplied the arguments.
16018                 if (checkComponentPermission(
16019                         android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
16020                         realCallingPid, realCallingUid, -1, true)
16021                         != PackageManager.PERMISSION_GRANTED) {
16022                     String msg = "Permission Denial: " + intent.getAction()
16023                             + " broadcast from " + callerPackage + " (pid=" + callingPid
16024                             + ", uid=" + callingUid + ")"
16025                             + " requires "
16026                             + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
16027                     Slog.w(TAG, msg);
16028                     throw new SecurityException(msg);
16029                 } else {
16030                     allowBackgroundActivityStarts = true;
16031                 }
16032             }
16033         }
16034 
16035         // Verify that protected broadcasts are only being sent by system code,
16036         // and that system code is only sending protected broadcasts.
16037         final boolean isProtectedBroadcast;
16038         try {
16039             isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
16040         } catch (RemoteException e) {
16041             Slog.w(TAG, "Remote exception", e);
16042             return ActivityManager.BROADCAST_SUCCESS;
16043         }
16044 
16045         final boolean isCallerSystem;
16046         switch (UserHandle.getAppId(callingUid)) {
16047             case ROOT_UID:
16048             case SYSTEM_UID:
16049             case PHONE_UID:
16050             case BLUETOOTH_UID:
16051             case NFC_UID:
16052             case SE_UID:
16053             case NETWORK_STACK_UID:
16054                 isCallerSystem = true;
16055                 break;
16056             default:
16057                 isCallerSystem = (callerApp != null) && callerApp.isPersistent();
16058                 break;
16059         }
16060 
16061         // First line security check before anything else: stop non-system apps from
16062         // sending protected broadcasts.
16063         if (!isCallerSystem) {
16064             if (isProtectedBroadcast) {
16065                 String msg = "Permission Denial: not allowed to send broadcast "
16066                         + action + " from pid="
16067                         + callingPid + ", uid=" + callingUid;
16068                 Slog.w(TAG, msg);
16069                 throw new SecurityException(msg);
16070 
16071             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
16072                     || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
16073                 // Special case for compatibility: we don't want apps to send this,
16074                 // but historically it has not been protected and apps may be using it
16075                 // to poke their own app widget.  So, instead of making it protected,
16076                 // just limit it to the caller.
16077                 if (callerPackage == null) {
16078                     String msg = "Permission Denial: not allowed to send broadcast "
16079                             + action + " from unknown caller.";
16080                     Slog.w(TAG, msg);
16081                     throw new SecurityException(msg);
16082                 } else if (intent.getComponent() != null) {
16083                     // They are good enough to send to an explicit component...  verify
16084                     // it is being sent to the calling app.
16085                     if (!intent.getComponent().getPackageName().equals(
16086                             callerPackage)) {
16087                         String msg = "Permission Denial: not allowed to send broadcast "
16088                                 + action + " to "
16089                                 + intent.getComponent().getPackageName() + " from "
16090                                 + callerPackage;
16091                         Slog.w(TAG, msg);
16092                         throw new SecurityException(msg);
16093                     }
16094                 } else {
16095                     // Limit broadcast to their own package.
16096                     intent.setPackage(callerPackage);
16097                 }
16098             }
16099         }
16100 
16101         boolean timeoutExempt = false;
16102 
16103         if (action != null) {
16104             if (getBackgroundLaunchBroadcasts().contains(action)) {
16105                 if (DEBUG_BACKGROUND_CHECK) {
16106                     Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
16107                 }
16108                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
16109             }
16110 
16111             switch (action) {
16112                 case Intent.ACTION_UID_REMOVED:
16113                 case Intent.ACTION_PACKAGE_REMOVED:
16114                 case Intent.ACTION_PACKAGE_CHANGED:
16115                 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
16116                 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
16117                 case Intent.ACTION_PACKAGES_SUSPENDED:
16118                 case Intent.ACTION_PACKAGES_UNSUSPENDED:
16119                     // Handle special intents: if this broadcast is from the package
16120                     // manager about a package being removed, we need to remove all of
16121                     // its activities from the history stack.
16122                     if (checkComponentPermission(
16123                             android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
16124                             callingPid, callingUid, -1, true)
16125                             != PackageManager.PERMISSION_GRANTED) {
16126                         String msg = "Permission Denial: " + intent.getAction()
16127                                 + " broadcast from " + callerPackage + " (pid=" + callingPid
16128                                 + ", uid=" + callingUid + ")"
16129                                 + " requires "
16130                                 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
16131                         Slog.w(TAG, msg);
16132                         throw new SecurityException(msg);
16133                     }
16134                     switch (action) {
16135                         case Intent.ACTION_UID_REMOVED:
16136                             final int uid = getUidFromIntent(intent);
16137                             if (uid >= 0) {
16138                                 mBatteryStatsService.removeUid(uid);
16139                                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
16140                                     mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
16141                                             intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
16142                                 } else {
16143                                     mAppOpsService.uidRemoved(uid);
16144                                 }
16145                             }
16146                             break;
16147                         case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
16148                             // If resources are unavailable just force stop all those packages
16149                             // and flush the attribute cache as well.
16150                             String list[] =
16151                                     intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
16152                             if (list != null && list.length > 0) {
16153                                 for (int i = 0; i < list.length; i++) {
16154                                     forceStopPackageLocked(list[i], -1, false, true, true,
16155                                             false, false, userId, "storage unmount");
16156                                 }
16157                                 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
16158                                 sendPackageBroadcastLocked(
16159                                         ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
16160                                         list, userId);
16161                             }
16162                             break;
16163                         case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
16164                             mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
16165                             break;
16166                         case Intent.ACTION_PACKAGE_REMOVED:
16167                         case Intent.ACTION_PACKAGE_CHANGED:
16168                             Uri data = intent.getData();
16169                             String ssp;
16170                             if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
16171                                 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
16172                                 final boolean replacing =
16173                                         intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
16174                                 final boolean killProcess =
16175                                         !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
16176                                 final boolean fullUninstall = removed && !replacing;
16177                                 if (removed) {
16178                                     if (killProcess) {
16179                                         forceStopPackageLocked(ssp, UserHandle.getAppId(
16180                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
16181                                                 false, true, true, false, fullUninstall, userId,
16182                                                 removed ? "pkg removed" : "pkg changed");
16183                                     } else {
16184                                         // Kill any app zygotes always, since they can't fork new
16185                                         // processes with references to the old code
16186                                         forceStopAppZygoteLocked(ssp, UserHandle.getAppId(
16187                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
16188                                                 userId);
16189                                     }
16190                                     final int cmd = killProcess
16191                                             ? ApplicationThreadConstants.PACKAGE_REMOVED
16192                                             : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
16193                                     sendPackageBroadcastLocked(cmd,
16194                                             new String[] {ssp}, userId);
16195                                     if (fullUninstall) {
16196                                         mAppOpsService.packageRemoved(
16197                                                 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
16198 
16199                                         // Remove all permissions granted from/to this package
16200                                         mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
16201                                                 true, false);
16202 
16203                                         mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
16204 
16205                                         mServices.forceStopPackageLocked(ssp, userId);
16206                                         mAtmInternal.onPackageUninstalled(ssp);
16207                                         mBatteryStatsService.notePackageUninstalled(ssp);
16208                                     }
16209                                 } else {
16210                                     if (killProcess) {
16211                                         final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
16212                                                 -1);
16213                                         mProcessList.killPackageProcessesLocked(ssp,
16214                                                 UserHandle.getAppId(extraUid),
16215                                                 userId, ProcessList.INVALID_ADJ,
16216                                                 ApplicationExitInfo.REASON_USER_REQUESTED,
16217                                                 ApplicationExitInfo.SUBREASON_UNKNOWN,
16218                                                 "change " + ssp);
16219                                     }
16220                                     cleanupDisabledPackageComponentsLocked(ssp, userId,
16221                                             intent.getStringArrayExtra(
16222                                                     Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
16223                                 }
16224                             }
16225                             break;
16226                         case Intent.ACTION_PACKAGES_SUSPENDED:
16227                         case Intent.ACTION_PACKAGES_UNSUSPENDED:
16228                             final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
16229                                     intent.getAction());
16230                             final String[] packageNames = intent.getStringArrayExtra(
16231                                     Intent.EXTRA_CHANGED_PACKAGE_LIST);
16232                             final int userIdExtra = intent.getIntExtra(
16233                                     Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
16234 
16235                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
16236                                     userIdExtra);
16237                             break;
16238                     }
16239                     break;
16240                 case Intent.ACTION_PACKAGE_REPLACED:
16241                 {
16242                     final Uri data = intent.getData();
16243                     final String ssp;
16244                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
16245                         ApplicationInfo aInfo = null;
16246                         try {
16247                             aInfo = AppGlobals.getPackageManager()
16248                                     .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
16249                         } catch (RemoteException ignore) {}
16250                         if (aInfo == null) {
16251                             Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
16252                                     + " ssp=" + ssp + " data=" + data);
16253                             return ActivityManager.BROADCAST_SUCCESS;
16254                         }
16255                         updateAssociationForApp(aInfo);
16256                         mAtmInternal.onPackageReplaced(aInfo);
16257                         mServices.updateServiceApplicationInfoLocked(aInfo);
16258                         sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
16259                                 new String[] {ssp}, userId);
16260                     }
16261                     break;
16262                 }
16263                 case Intent.ACTION_PACKAGE_ADDED:
16264                 {
16265                     // Special case for adding a package: by default turn on compatibility mode.
16266                     Uri data = intent.getData();
16267                     String ssp;
16268                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
16269                         final boolean replacing =
16270                                 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
16271                         mAtmInternal.onPackageAdded(ssp, replacing);
16272 
16273                         try {
16274                             ApplicationInfo ai = AppGlobals.getPackageManager().
16275                                     getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
16276                             mBatteryStatsService.notePackageInstalled(ssp,
16277                                     ai != null ? ai.longVersionCode : 0);
16278                         } catch (RemoteException e) {
16279                         }
16280                     }
16281                     break;
16282                 }
16283                 case Intent.ACTION_PACKAGE_DATA_CLEARED:
16284                 {
16285                     Uri data = intent.getData();
16286                     String ssp;
16287                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
16288                         mAtmInternal.onPackageDataCleared(ssp);
16289                     }
16290                     break;
16291                 }
16292                 case Intent.ACTION_TIMEZONE_CHANGED:
16293                     // If this is the time zone changed action, queue up a message that will reset
16294                     // the timezone of all currently running processes. This message will get
16295                     // queued up before the broadcast happens.
16296                     mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
16297                     break;
16298                 case Intent.ACTION_TIME_CHANGED:
16299                     // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
16300                     // the tri-state value it may contain and "unknown".
16301                     // For convenience we re-use the Intent extra values.
16302                     final int NO_EXTRA_VALUE_FOUND = -1;
16303                     final int timeFormatPreferenceMsgValue = intent.getIntExtra(
16304                             Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
16305                             NO_EXTRA_VALUE_FOUND /* defaultValue */);
16306                     // Only send a message if the time preference is available.
16307                     if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
16308                         Message updateTimePreferenceMsg =
16309                                 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
16310                                         timeFormatPreferenceMsgValue, 0);
16311                         mHandler.sendMessage(updateTimePreferenceMsg);
16312                     }
16313                     BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
16314                     synchronized (stats) {
16315                         stats.noteCurrentTimeChangedLocked();
16316                     }
16317                     break;
16318                 case Intent.ACTION_CLEAR_DNS_CACHE:
16319                     mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
16320                     break;
16321                 case Proxy.PROXY_CHANGE_ACTION:
16322                     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
16323                     break;
16324                 case android.hardware.Camera.ACTION_NEW_PICTURE:
16325                 case android.hardware.Camera.ACTION_NEW_VIDEO:
16326                     // In N we just turned these off; in O we are turing them back on partly,
16327                     // only for registered receivers.  This will still address the main problem
16328                     // (a spam of apps waking up when a picture is taken putting significant
16329                     // memory pressure on the system at a bad point), while still allowing apps
16330                     // that are already actively running to know about this happening.
16331                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
16332                     break;
16333                 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
16334                     mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
16335                     break;
16336                 case "com.android.launcher.action.INSTALL_SHORTCUT":
16337                     // As of O, we no longer support this broadcasts, even for pre-O apps.
16338                     // Apps should now be using ShortcutManager.pinRequestShortcut().
16339                     Log.w(TAG, "Broadcast " + action
16340                             + " no longer supported. It will not be delivered.");
16341                     return ActivityManager.BROADCAST_SUCCESS;
16342                 case Intent.ACTION_PRE_BOOT_COMPLETED:
16343                     timeoutExempt = true;
16344                     break;
16345             }
16346 
16347             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
16348                     Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
16349                     Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
16350                 final int uid = getUidFromIntent(intent);
16351                 if (uid != -1) {
16352                     final UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
16353                     if (uidRec != null) {
16354                         uidRec.updateHasInternetPermission();
16355                     }
16356                 }
16357             }
16358         }
16359 
16360         // Add to the sticky list if requested.
16361         if (sticky) {
16362             if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
16363                     callingPid, callingUid)
16364                     != PackageManager.PERMISSION_GRANTED) {
16365                 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
16366                         + callingPid + ", uid=" + callingUid
16367                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
16368                 Slog.w(TAG, msg);
16369                 throw new SecurityException(msg);
16370             }
16371             if (requiredPermissions != null && requiredPermissions.length > 0) {
16372                 Slog.w(TAG, "Can't broadcast sticky intent " + intent
16373                         + " and enforce permissions " + Arrays.toString(requiredPermissions));
16374                 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
16375             }
16376             if (intent.getComponent() != null) {
16377                 throw new SecurityException(
16378                         "Sticky broadcasts can't target a specific component");
16379             }
16380             // We use userId directly here, since the "all" target is maintained
16381             // as a separate set of sticky broadcasts.
16382             if (userId != UserHandle.USER_ALL) {
16383                 // But first, if this is not a broadcast to all users, then
16384                 // make sure it doesn't conflict with an existing broadcast to
16385                 // all users.
16386                 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
16387                         UserHandle.USER_ALL);
16388                 if (stickies != null) {
16389                     ArrayList<Intent> list = stickies.get(intent.getAction());
16390                     if (list != null) {
16391                         int N = list.size();
16392                         int i;
16393                         for (i=0; i<N; i++) {
16394                             if (intent.filterEquals(list.get(i))) {
16395                                 throw new IllegalArgumentException(
16396                                         "Sticky broadcast " + intent + " for user "
16397                                         + userId + " conflicts with existing global broadcast");
16398                             }
16399                         }
16400                     }
16401                 }
16402             }
16403             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
16404             if (stickies == null) {
16405                 stickies = new ArrayMap<>();
16406                 mStickyBroadcasts.put(userId, stickies);
16407             }
16408             ArrayList<Intent> list = stickies.get(intent.getAction());
16409             if (list == null) {
16410                 list = new ArrayList<>();
16411                 stickies.put(intent.getAction(), list);
16412             }
16413             final int stickiesCount = list.size();
16414             int i;
16415             for (i = 0; i < stickiesCount; i++) {
16416                 if (intent.filterEquals(list.get(i))) {
16417                     // This sticky already exists, replace it.
16418                     list.set(i, new Intent(intent));
16419                     break;
16420                 }
16421             }
16422             if (i >= stickiesCount) {
16423                 list.add(new Intent(intent));
16424             }
16425         }
16426 
16427         int[] users;
16428         if (userId == UserHandle.USER_ALL) {
16429             // Caller wants broadcast to go to all started users.
16430             users = mUserController.getStartedUserArray();
16431         } else {
16432             // Caller wants broadcast to go to one specific user.
16433             users = new int[] {userId};
16434         }
16435 
16436         // Figure out who all will receive this broadcast.
16437         List receivers = null;
16438         List<BroadcastFilter> registeredReceivers = null;
16439         // Need to resolve the intent to interested receivers...
16440         if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
16441                  == 0) {
16442             receivers = collectReceiverComponents(
16443                     intent, resolvedType, callingUid, users, broadcastWhitelist);
16444         }
16445         if (intent.getComponent() == null) {
16446             if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
16447                 // Query one target user at a time, excluding shell-restricted users
16448                 for (int i = 0; i < users.length; i++) {
16449                     if (mUserController.hasUserRestriction(
16450                             UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
16451                         continue;
16452                     }
16453                     List<BroadcastFilter> registeredReceiversForUser =
16454                             mReceiverResolver.queryIntent(intent,
16455                                     resolvedType, false /*defaultOnly*/, users[i]);
16456                     if (registeredReceivers == null) {
16457                         registeredReceivers = registeredReceiversForUser;
16458                     } else if (registeredReceiversForUser != null) {
16459                         registeredReceivers.addAll(registeredReceiversForUser);
16460                     }
16461                 }
16462             } else {
16463                 registeredReceivers = mReceiverResolver.queryIntent(intent,
16464                         resolvedType, false /*defaultOnly*/, userId);
16465             }
16466         }
16467 
16468         final boolean replacePending =
16469                 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
16470 
16471         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
16472                 + " replacePending=" + replacePending);
16473         if (registeredReceivers != null && broadcastWhitelist != null) {
16474             // if a uid whitelist was provided, remove anything in the application space that wasn't
16475             // in it.
16476             for (int i = registeredReceivers.size() - 1; i >= 0; i--) {
16477                 final int owningAppId = UserHandle.getAppId(registeredReceivers.get(i).owningUid);
16478                 if (owningAppId >= Process.FIRST_APPLICATION_UID
16479                         && Arrays.binarySearch(broadcastWhitelist, owningAppId) < 0) {
16480                     registeredReceivers.remove(i);
16481                 }
16482             }
16483         }
16484 
16485         int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
16486         if (!ordered && NR > 0) {
16487             // If we are not serializing this broadcast, then send the
16488             // registered receivers separately so they don't wait for the
16489             // components to be launched.
16490             if (isCallerSystem) {
16491                 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
16492                         isProtectedBroadcast, registeredReceivers);
16493             }
16494             final BroadcastQueue queue = broadcastQueueForIntent(intent);
16495             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
16496                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
16497                     requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
16498                     resultCode, resultData, resultExtras, ordered, sticky, false, userId,
16499                     allowBackgroundActivityStarts, timeoutExempt);
16500             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
16501             final boolean replaced = replacePending
16502                     && (queue.replaceParallelBroadcastLocked(r) != null);
16503             // Note: We assume resultTo is null for non-ordered broadcasts.
16504             if (!replaced) {
16505                 queue.enqueueParallelBroadcastLocked(r);
16506                 queue.scheduleBroadcastsLocked();
16507             }
16508             registeredReceivers = null;
16509             NR = 0;
16510         }
16511 
16512         // Merge into one list.
16513         int ir = 0;
16514         if (receivers != null) {
16515             // A special case for PACKAGE_ADDED: do not allow the package
16516             // being added to see this broadcast.  This prevents them from
16517             // using this as a back door to get run as soon as they are
16518             // installed.  Maybe in the future we want to have a special install
16519             // broadcast or such for apps, but we'd like to deliberately make
16520             // this decision.
16521             String skipPackages[] = null;
16522             if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
16523                     || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
16524                     || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
16525                 Uri data = intent.getData();
16526                 if (data != null) {
16527                     String pkgName = data.getSchemeSpecificPart();
16528                     if (pkgName != null) {
16529                         skipPackages = new String[] { pkgName };
16530                     }
16531                 }
16532             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
16533                 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
16534             }
16535             if (skipPackages != null && (skipPackages.length > 0)) {
16536                 for (String skipPackage : skipPackages) {
16537                     if (skipPackage != null) {
16538                         int NT = receivers.size();
16539                         for (int it=0; it<NT; it++) {
16540                             ResolveInfo curt = (ResolveInfo)receivers.get(it);
16541                             if (curt.activityInfo.packageName.equals(skipPackage)) {
16542                                 receivers.remove(it);
16543                                 it--;
16544                                 NT--;
16545                             }
16546                         }
16547                     }
16548                 }
16549             }
16550 
16551             int NT = receivers != null ? receivers.size() : 0;
16552             int it = 0;
16553             ResolveInfo curt = null;
16554             BroadcastFilter curr = null;
16555             while (it < NT && ir < NR) {
16556                 if (curt == null) {
16557                     curt = (ResolveInfo)receivers.get(it);
16558                 }
16559                 if (curr == null) {
16560                     curr = registeredReceivers.get(ir);
16561                 }
16562                 if (curr.getPriority() >= curt.priority) {
16563                     // Insert this broadcast record into the final list.
16564                     receivers.add(it, curr);
16565                     ir++;
16566                     curr = null;
16567                     it++;
16568                     NT++;
16569                 } else {
16570                     // Skip to the next ResolveInfo in the final list.
16571                     it++;
16572                     curt = null;
16573                 }
16574             }
16575         }
16576         while (ir < NR) {
16577             if (receivers == null) {
16578                 receivers = new ArrayList();
16579             }
16580             receivers.add(registeredReceivers.get(ir));
16581             ir++;
16582         }
16583 
16584         if (isCallerSystem) {
16585             checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
16586                     isProtectedBroadcast, receivers);
16587         }
16588 
16589         if ((receivers != null && receivers.size() > 0)
16590                 || resultTo != null) {
16591             BroadcastQueue queue = broadcastQueueForIntent(intent);
16592             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, callerPackage,
16593                     callerFeatureId, callingPid, callingUid, callerInstantApp, resolvedType,
16594                     requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
16595                     resultData, resultExtras, ordered, sticky, false, userId,
16596                     allowBackgroundActivityStarts, timeoutExempt);
16597 
16598             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
16599 
16600             final BroadcastRecord oldRecord =
16601                     replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
16602             if (oldRecord != null) {
16603                 // Replaced, fire the result-to receiver.
16604                 if (oldRecord.resultTo != null) {
16605                     final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
16606                     try {
16607                         oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
16608                                 oldRecord.intent,
16609                                 Activity.RESULT_CANCELED, null, null,
16610                                 false, false, oldRecord.userId);
16611                     } catch (RemoteException e) {
16612                         Slog.w(TAG, "Failure ["
16613                                 + queue.mQueueName + "] sending broadcast result of "
16614                                 + intent, e);
16615 
16616                     }
16617                 }
16618             } else {
16619                 queue.enqueueOrderedBroadcastLocked(r);
16620                 queue.scheduleBroadcastsLocked();
16621             }
16622         } else {
16623             // There was nobody interested in the broadcast, but we still want to record
16624             // that it happened.
16625             if (intent.getComponent() == null && intent.getPackage() == null
16626                     && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
16627                 // This was an implicit broadcast... let's record it for posterity.
16628                 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
16629             }
16630         }
16631 
16632         return ActivityManager.BROADCAST_SUCCESS;
16633     }
16634 
16635     /**
16636      * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1
16637      */
getUidFromIntent(Intent intent)16638     private int getUidFromIntent(Intent intent) {
16639         if (intent == null) {
16640             return -1;
16641         }
16642         final Bundle intentExtras = intent.getExtras();
16643         return intent.hasExtra(Intent.EXTRA_UID)
16644                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
16645     }
16646 
rotateBroadcastStatsIfNeededLocked()16647     final void rotateBroadcastStatsIfNeededLocked() {
16648         final long now = SystemClock.elapsedRealtime();
16649         if (mCurBroadcastStats == null ||
16650                 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) {
16651             mLastBroadcastStats = mCurBroadcastStats;
16652             if (mLastBroadcastStats != null) {
16653                 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime();
16654                 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis();
16655             }
16656             mCurBroadcastStats = new BroadcastStats();
16657         }
16658     }
16659 
addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)16660     final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount,
16661             int skipCount, long dispatchTime) {
16662         rotateBroadcastStatsIfNeededLocked();
16663         mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime);
16664     }
16665 
addBackgroundCheckViolationLocked(String action, String targetPackage)16666     final void addBackgroundCheckViolationLocked(String action, String targetPackage) {
16667         rotateBroadcastStatsIfNeededLocked();
16668         mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage);
16669     }
16670 
verifyBroadcastLocked(Intent intent)16671     final Intent verifyBroadcastLocked(Intent intent) {
16672         // Refuse possible leaked file descriptors
16673         if (intent != null && intent.hasFileDescriptors() == true) {
16674             throw new IllegalArgumentException("File descriptors passed in Intent");
16675         }
16676 
16677         int flags = intent.getFlags();
16678 
16679         if (!mProcessesReady) {
16680             // if the caller really truly claims to know what they're doing, go
16681             // ahead and allow the broadcast without launching any receivers
16682             if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
16683                 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
16684             } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
16685                 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
16686                         + " before boot completion");
16687                 throw new IllegalStateException("Cannot broadcast before boot completed");
16688             }
16689         }
16690 
16691         if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
16692             throw new IllegalArgumentException(
16693                     "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
16694         }
16695 
16696         if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
16697             switch (Binder.getCallingUid()) {
16698                 case ROOT_UID:
16699                 case SHELL_UID:
16700                     break;
16701                 default:
16702                     Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
16703                             + Binder.getCallingUid());
16704                     intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
16705                     break;
16706             }
16707         }
16708 
16709         return intent;
16710     }
16711 
16712     /**
16713      * @deprecated Use {@link #broadcastIntentWithFeature}
16714      */
16715     @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)16716     public final int broadcastIntent(IApplicationThread caller,
16717             Intent intent, String resolvedType, IIntentReceiver resultTo,
16718             int resultCode, String resultData, Bundle resultExtras,
16719             String[] requiredPermissions, int appOp, Bundle bOptions,
16720             boolean serialized, boolean sticky, int userId) {
16721         return broadcastIntentWithFeature(caller, null, intent, resolvedType, resultTo, resultCode,
16722                 resultData, resultExtras, requiredPermissions, appOp, bOptions, serialized, sticky,
16723                 userId);
16724     }
16725 
broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions, boolean serialized, boolean sticky, int userId)16726     public final int broadcastIntentWithFeature(IApplicationThread caller, String callingFeatureId,
16727             Intent intent, String resolvedType, IIntentReceiver resultTo,
16728             int resultCode, String resultData, Bundle resultExtras,
16729             String[] requiredPermissions, int appOp, Bundle bOptions,
16730             boolean serialized, boolean sticky, int userId) {
16731         enforceNotIsolatedCaller("broadcastIntent");
16732         synchronized(this) {
16733             intent = verifyBroadcastLocked(intent);
16734 
16735             final ProcessRecord callerApp = getRecordForAppLocked(caller);
16736             final int callingPid = Binder.getCallingPid();
16737             final int callingUid = Binder.getCallingUid();
16738 
16739             final long origId = Binder.clearCallingIdentity();
16740             try {
16741                 return broadcastIntentLocked(callerApp,
16742                         callerApp != null ? callerApp.info.packageName : null, callingFeatureId,
16743                         intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
16744                         requiredPermissions, appOp, bOptions, serialized, sticky,
16745                         callingPid, callingUid, callingUid, callingPid, userId);
16746             } finally {
16747                 Binder.restoreCallingIdentity(origId);
16748             }
16749         }
16750     }
16751 
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)16752     int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
16753             int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
16754             IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras,
16755             String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky,
16756             int userId, boolean allowBackgroundActivityStarts) {
16757         synchronized(this) {
16758             intent = verifyBroadcastLocked(intent);
16759 
16760             final long origId = Binder.clearCallingIdentity();
16761             String[] requiredPermissions = requiredPermission == null ? null
16762                     : new String[] {requiredPermission};
16763             try {
16764                 return broadcastIntentLocked(null, packageName, featureId, intent, resolvedType,
16765                         resultTo, resultCode, resultData, resultExtras, requiredPermissions,
16766                         OP_NONE, bOptions, serialized, sticky, -1, uid, realCallingUid,
16767                         realCallingPid, userId, allowBackgroundActivityStarts,
16768                         null /*broadcastWhitelist*/);
16769             } finally {
16770                 Binder.restoreCallingIdentity(origId);
16771             }
16772         }
16773     }
16774 
unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)16775     public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
16776         // Refuse possible leaked file descriptors
16777         if (intent != null && intent.hasFileDescriptors() == true) {
16778             throw new IllegalArgumentException("File descriptors passed in Intent");
16779         }
16780 
16781         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
16782                 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
16783 
16784         synchronized(this) {
16785             if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
16786                     != PackageManager.PERMISSION_GRANTED) {
16787                 String msg = "Permission Denial: unbroadcastIntent() from pid="
16788                         + Binder.getCallingPid()
16789                         + ", uid=" + Binder.getCallingUid()
16790                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
16791                 Slog.w(TAG, msg);
16792                 throw new SecurityException(msg);
16793             }
16794             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
16795             if (stickies != null) {
16796                 ArrayList<Intent> list = stickies.get(intent.getAction());
16797                 if (list != null) {
16798                     int N = list.size();
16799                     int i;
16800                     for (i=0; i<N; i++) {
16801                         if (intent.filterEquals(list.get(i))) {
16802                             list.remove(i);
16803                             break;
16804                         }
16805                     }
16806                     if (list.size() <= 0) {
16807                         stickies.remove(intent.getAction());
16808                     }
16809                 }
16810                 if (stickies.size() <= 0) {
16811                     mStickyBroadcasts.remove(userId);
16812                 }
16813             }
16814         }
16815     }
16816 
backgroundServicesFinishedLocked(int userId)16817     void backgroundServicesFinishedLocked(int userId) {
16818         for (BroadcastQueue queue : mBroadcastQueues) {
16819             queue.backgroundServicesFinishedLocked(userId);
16820         }
16821     }
16822 
finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)16823     public void finishReceiver(IBinder who, int resultCode, String resultData,
16824             Bundle resultExtras, boolean resultAbort, int flags) {
16825         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who);
16826 
16827         // Refuse possible leaked file descriptors
16828         if (resultExtras != null && resultExtras.hasFileDescriptors()) {
16829             throw new IllegalArgumentException("File descriptors passed in Bundle");
16830         }
16831 
16832         final long origId = Binder.clearCallingIdentity();
16833         try {
16834             boolean doNext = false;
16835             BroadcastRecord r;
16836             BroadcastQueue queue;
16837 
16838             synchronized(this) {
16839                 if (isOnOffloadQueue(flags)) {
16840                     queue = mOffloadBroadcastQueue;
16841                 } else {
16842                     queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0
16843                             ? mFgBroadcastQueue : mBgBroadcastQueue;
16844                 }
16845 
16846                 r = queue.getMatchingOrderedReceiver(who);
16847                 if (r != null) {
16848                     doNext = r.queue.finishReceiverLocked(r, resultCode,
16849                         resultData, resultExtras, resultAbort, true);
16850                 }
16851                 if (doNext) {
16852                     r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true);
16853                 }
16854                 // updateOomAdjLocked() will be done here
16855                 trimApplicationsLocked(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
16856             }
16857 
16858         } finally {
16859             Binder.restoreCallingIdentity(origId);
16860         }
16861     }
16862 
16863     // =========================================================
16864     // INSTRUMENTATION
16865     // =========================================================
16866 
startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)16867     public boolean startInstrumentation(ComponentName className,
16868             String profileFile, int flags, Bundle arguments,
16869             IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
16870             int userId, String abiOverride) {
16871         enforceNotIsolatedCaller("startInstrumentation");
16872         final int callingUid = Binder.getCallingUid();
16873         final int callingPid = Binder.getCallingPid();
16874         userId = mUserController.handleIncomingUser(callingPid, callingUid,
16875                 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
16876         // Refuse possible leaked file descriptors
16877         if (arguments != null && arguments.hasFileDescriptors()) {
16878             throw new IllegalArgumentException("File descriptors passed in Bundle");
16879         }
16880 
16881         synchronized(this) {
16882             InstrumentationInfo ii = null;
16883             ApplicationInfo ai = null;
16884             try {
16885                 ii = mContext.getPackageManager().getInstrumentationInfo(
16886                     className, STOCK_PM_FLAGS);
16887                 ai = AppGlobals.getPackageManager().getApplicationInfo(
16888                         ii.targetPackage, STOCK_PM_FLAGS, userId);
16889             } catch (PackageManager.NameNotFoundException e) {
16890             } catch (RemoteException e) {
16891             }
16892             if (ii == null) {
16893                 reportStartInstrumentationFailureLocked(watcher, className,
16894                         "Unable to find instrumentation info for: " + className);
16895                 return false;
16896             }
16897             if (ai == null) {
16898                 reportStartInstrumentationFailureLocked(watcher, className,
16899                         "Unable to find instrumentation target package: " + ii.targetPackage);
16900                 return false;
16901             }
16902             if (!ai.hasCode()) {
16903                 reportStartInstrumentationFailureLocked(watcher, className,
16904                         "Instrumentation target has no code: " + ii.targetPackage);
16905                 return false;
16906             }
16907 
16908             int match = mContext.getPackageManager().checkSignatures(
16909                     ii.targetPackage, ii.packageName);
16910             if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
16911                 String msg = "Permission Denial: starting instrumentation "
16912                         + className + " from pid="
16913                         + Binder.getCallingPid()
16914                         + ", uid=" + Binder.getCallingPid()
16915                         + " not allowed because package " + ii.packageName
16916                         + " does not have a signature matching the target "
16917                         + ii.targetPackage;
16918                 reportStartInstrumentationFailureLocked(watcher, className, msg);
16919                 throw new SecurityException(msg);
16920             }
16921 
16922             ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
16923             activeInstr.mClass = className;
16924             String defProcess = ai.processName;;
16925             if (ii.targetProcesses == null) {
16926                 activeInstr.mTargetProcesses = new String[]{ai.processName};
16927             } else if (ii.targetProcesses.equals("*")) {
16928                 activeInstr.mTargetProcesses = new String[0];
16929             } else {
16930                 activeInstr.mTargetProcesses = ii.targetProcesses.split(",");
16931                 defProcess = activeInstr.mTargetProcesses[0];
16932             }
16933             activeInstr.mTargetInfo = ai;
16934             activeInstr.mProfileFile = profileFile;
16935             activeInstr.mArguments = arguments;
16936             activeInstr.mWatcher = watcher;
16937             activeInstr.mUiAutomationConnection = uiAutomationConnection;
16938             activeInstr.mResultClass = className;
16939             activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
16940                     START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
16941                             == PackageManager.PERMISSION_GRANTED;
16942 
16943             boolean disableHiddenApiChecks = ai.usesNonSdkApi()
16944                     || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
16945             boolean disableTestApiChecks = disableHiddenApiChecks
16946                     || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0;
16947             if (disableHiddenApiChecks || disableTestApiChecks) {
16948                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
16949                         "disable hidden API checks");
16950             }
16951 
16952             // TODO(b/158750470): remove
16953             final boolean mountExtStorageFull = isCallerShell()
16954                     && (flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0;
16955 
16956             final long origId = Binder.clearCallingIdentity();
16957             // Instrumentation can kill and relaunch even persistent processes
16958             forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId,
16959                     "start instr");
16960             // Inform usage stats to make the target package active
16961             if (mUsageStatsService != null) {
16962                 mUsageStatsService.reportEvent(ii.targetPackage, userId,
16963                         UsageEvents.Event.SYSTEM_INTERACTION);
16964             }
16965 
16966             ProcessRecord app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks,
16967                     disableTestApiChecks, mountExtStorageFull, abiOverride,
16968                     ZYGOTE_POLICY_FLAG_EMPTY);
16969             app.setActiveInstrumentation(activeInstr);
16970             activeInstr.mFinished = false;
16971             activeInstr.mSourceUid = callingUid;
16972             activeInstr.mRunningProcesses.add(app);
16973             if (!mActiveInstrumentation.contains(activeInstr)) {
16974                 mActiveInstrumentation.add(activeInstr);
16975             }
16976 
16977             if ((flags & INSTR_FLAG_DISABLE_ISOLATED_STORAGE) != 0) {
16978                 // Allow OP_NO_ISOLATED_STORAGE app op for the package running instrumentation with
16979                 // --no-isolated-storage flag.
16980                 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, ai.uid,
16981                         ii.packageName, AppOpsManager.MODE_ALLOWED);
16982             }
16983             Binder.restoreCallingIdentity(origId);
16984         }
16985 
16986         return true;
16987     }
16988 
isCallerShell()16989     private boolean isCallerShell() {
16990         final int callingUid = Binder.getCallingUid();
16991         return callingUid == SHELL_UID || callingUid == ROOT_UID;
16992     }
16993 
16994     /**
16995      * Report errors that occur while attempting to start Instrumentation.  Always writes the
16996      * error to the logs, but if somebody is watching, send the report there too.  This enables
16997      * the "am" command to report errors with more information.
16998      *
16999      * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
17000      * @param cn The component name of the instrumentation.
17001      * @param report The error report.
17002      */
reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)17003     private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher,
17004             ComponentName cn, String report) {
17005         Slog.w(TAG, report);
17006         if (watcher != null) {
17007             Bundle results = new Bundle();
17008             results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
17009             results.putString("Error", report);
17010             mInstrumentationReporter.reportStatus(watcher, cn, -1, results);
17011         }
17012     }
17013 
addInstrumentationResultsLocked(ProcessRecord app, Bundle results)17014     void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) {
17015         final ActiveInstrumentation instr = app.getActiveInstrumentation();
17016         if (instr == null) {
17017             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
17018             return;
17019         }
17020 
17021         if (!instr.mFinished && results != null) {
17022             if (instr.mCurResults == null) {
17023                 instr.mCurResults = new Bundle(results);
17024             } else {
17025                 instr.mCurResults.putAll(results);
17026             }
17027         }
17028     }
17029 
addInstrumentationResults(IApplicationThread target, Bundle results)17030     public void addInstrumentationResults(IApplicationThread target, Bundle results) {
17031         int userId = UserHandle.getCallingUserId();
17032         // Refuse possible leaked file descriptors
17033         if (results != null && results.hasFileDescriptors()) {
17034             throw new IllegalArgumentException("File descriptors passed in Intent");
17035         }
17036 
17037         synchronized(this) {
17038             ProcessRecord app = getRecordForAppLocked(target);
17039             if (app == null) {
17040                 Slog.w(TAG, "addInstrumentationResults: no app for " + target);
17041                 return;
17042             }
17043             final long origId = Binder.clearCallingIdentity();
17044             addInstrumentationResultsLocked(app, results);
17045             Binder.restoreCallingIdentity(origId);
17046         }
17047     }
17048 
17049     @GuardedBy("this")
finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)17050     void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
17051         final ActiveInstrumentation instr = app.getActiveInstrumentation();
17052         if (instr == null) {
17053             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
17054             return;
17055         }
17056 
17057         if (!instr.mFinished) {
17058             if (instr.mWatcher != null) {
17059                 Bundle finalResults = instr.mCurResults;
17060                 if (finalResults != null) {
17061                     if (instr.mCurResults != null && results != null) {
17062                         finalResults.putAll(results);
17063                     }
17064                 } else {
17065                     finalResults = results;
17066                 }
17067                 mInstrumentationReporter.reportFinished(instr.mWatcher,
17068                         instr.mClass, resultCode, finalResults);
17069             }
17070 
17071             // Can't call out of the system process with a lock held, so post a message.
17072             if (instr.mUiAutomationConnection != null) {
17073                 // Go back to the default mode of denying OP_NO_ISOLATED_STORAGE app op.
17074                 mAppOpsService.setMode(AppOpsManager.OP_NO_ISOLATED_STORAGE, app.uid,
17075                         app.info.packageName, AppOpsManager.MODE_ERRORED);
17076                 mAppOpsService.setAppOpsServiceDelegate(null);
17077                 getPermissionManagerInternalLocked().setCheckPermissionDelegate(null);
17078                 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
17079                         instr.mUiAutomationConnection).sendToTarget();
17080             }
17081             instr.mFinished = true;
17082         }
17083 
17084         instr.removeProcess(app);
17085         app.setActiveInstrumentation(null);
17086 
17087         forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId,
17088                 "finished inst");
17089     }
17090 
finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)17091     public void finishInstrumentation(IApplicationThread target,
17092             int resultCode, Bundle results) {
17093         int userId = UserHandle.getCallingUserId();
17094         // Refuse possible leaked file descriptors
17095         if (results != null && results.hasFileDescriptors()) {
17096             throw new IllegalArgumentException("File descriptors passed in Intent");
17097         }
17098 
17099         synchronized(this) {
17100             ProcessRecord app = getRecordForAppLocked(target);
17101             if (app == null) {
17102                 Slog.w(TAG, "finishInstrumentation: no app for " + target);
17103                 return;
17104             }
17105             final long origId = Binder.clearCallingIdentity();
17106             finishInstrumentationLocked(app, resultCode, results);
17107             Binder.restoreCallingIdentity(origId);
17108         }
17109     }
17110 
17111     @Override
getFocusedStackInfo()17112     public StackInfo getFocusedStackInfo() throws RemoteException {
17113         return mActivityTaskManager.getFocusedStackInfo();
17114     }
17115 
17116     @Override
getConfiguration()17117     public Configuration getConfiguration() {
17118         return mActivityTaskManager.getConfiguration();
17119     }
17120 
17121     @Override
suppressResizeConfigChanges(boolean suppress)17122     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
17123         mActivityTaskManager.suppressResizeConfigChanges(suppress);
17124     }
17125 
17126     @Override
updatePersistentConfiguration(Configuration values)17127     public void updatePersistentConfiguration(Configuration values) {
17128         enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
17129         enforceWriteSettingsPermission("updatePersistentConfiguration()");
17130         if (values == null) {
17131             throw new NullPointerException("Configuration must not be null");
17132         }
17133 
17134         int userId = UserHandle.getCallingUserId();
17135 
17136         mActivityTaskManager.updatePersistentConfiguration(values, userId);
17137     }
17138 
enforceWriteSettingsPermission(String func)17139     private void enforceWriteSettingsPermission(String func) {
17140         int uid = Binder.getCallingUid();
17141         if (uid == ROOT_UID) {
17142             return;
17143         }
17144 
17145         if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
17146                 Settings.getPackageNameForUid(mContext, uid), false)) {
17147             return;
17148         }
17149 
17150         String msg = "Permission Denial: " + func + " from pid="
17151                 + Binder.getCallingPid()
17152                 + ", uid=" + uid
17153                 + " requires " + android.Manifest.permission.WRITE_SETTINGS;
17154         Slog.w(TAG, msg);
17155         throw new SecurityException(msg);
17156     }
17157 
17158     @Override
updateConfiguration(Configuration values)17159     public boolean updateConfiguration(Configuration values) {
17160         return mActivityTaskManager.updateConfiguration(values);
17161     }
17162 
17163     @Override
updateMccMncConfiguration(String mcc, String mnc)17164     public boolean updateMccMncConfiguration(String mcc, String mnc) {
17165         int mccInt, mncInt;
17166         try {
17167             mccInt = Integer.parseInt(mcc);
17168             mncInt = Integer.parseInt(mnc);
17169         } catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
17170             Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex);
17171             return false;
17172         }
17173         Configuration config = new Configuration();
17174         config.mcc = mccInt;
17175         config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;
17176         return mActivityTaskManager.updateConfiguration(config);
17177     }
17178 
17179     @Override
getLaunchedFromUid(IBinder activityToken)17180     public int getLaunchedFromUid(IBinder activityToken) {
17181         return mActivityTaskManager.getLaunchedFromUid(activityToken);
17182     }
17183 
getLaunchedFromPackage(IBinder activityToken)17184     public String getLaunchedFromPackage(IBinder activityToken) {
17185         return mActivityTaskManager.getLaunchedFromPackage(activityToken);
17186     }
17187 
17188     // =========================================================
17189     // LIFETIME MANAGEMENT
17190     // =========================================================
17191 
17192     // Returns whether the app is receiving broadcast.
17193     // If receiving, fetch all broadcast queues which the app is
17194     // the current [or imminent] receiver on.
isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)17195     boolean isReceivingBroadcastLocked(ProcessRecord app,
17196             ArraySet<BroadcastQueue> receivingQueues) {
17197         final int N = app.curReceivers.size();
17198         if (N > 0) {
17199             for (int i = 0; i < N; i++) {
17200                 receivingQueues.add(app.curReceivers.valueAt(i).queue);
17201             }
17202             return true;
17203         }
17204 
17205         // It's not the current receiver, but it might be starting up to become one
17206         for (BroadcastQueue queue : mBroadcastQueues) {
17207             final BroadcastRecord r = queue.mPendingBroadcast;
17208             if (r != null && r.curApp == app) {
17209                 // found it; report which queue it's in
17210                 receivingQueues.add(queue);
17211             }
17212         }
17213 
17214         return !receivingQueues.isEmpty();
17215     }
17216 
startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)17217     Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState,
17218             int targetUid, long targetVersionCode, ComponentName targetComponent,
17219             String targetProcess) {
17220         if (!mTrackingAssociations) {
17221             return null;
17222         }
17223         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
17224                 = mAssociations.get(targetUid);
17225         if (components == null) {
17226             components = new ArrayMap<>();
17227             mAssociations.put(targetUid, components);
17228         }
17229         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
17230         if (sourceUids == null) {
17231             sourceUids = new SparseArray<>();
17232             components.put(targetComponent, sourceUids);
17233         }
17234         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
17235         if (sourceProcesses == null) {
17236             sourceProcesses = new ArrayMap<>();
17237             sourceUids.put(sourceUid, sourceProcesses);
17238         }
17239         Association ass = sourceProcesses.get(sourceProcess);
17240         if (ass == null) {
17241             ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent,
17242                     targetProcess);
17243             sourceProcesses.put(sourceProcess, ass);
17244         }
17245         ass.mCount++;
17246         ass.mNesting++;
17247         if (ass.mNesting == 1) {
17248             ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis();
17249             ass.mLastState = sourceState;
17250         }
17251         return ass;
17252     }
17253 
stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)17254     void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid,
17255             long targetVersionCode, ComponentName targetComponent, String targetProcess) {
17256         if (!mTrackingAssociations) {
17257             return;
17258         }
17259         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
17260                 = mAssociations.get(targetUid);
17261         if (components == null) {
17262             return;
17263         }
17264         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
17265         if (sourceUids == null) {
17266             return;
17267         }
17268         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
17269         if (sourceProcesses == null) {
17270             return;
17271         }
17272         Association ass = sourceProcesses.get(sourceProcess);
17273         if (ass == null || ass.mNesting <= 0) {
17274             return;
17275         }
17276         ass.mNesting--;
17277         if (ass.mNesting == 0) {
17278             long uptime = SystemClock.uptimeMillis();
17279             ass.mTime += uptime - ass.mStartTime;
17280             ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
17281                     += uptime - ass.mLastStateUptime;
17282             ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2;
17283         }
17284     }
17285 
noteUidProcessState(final int uid, final int state, final @ActivityManager.ProcessCapability int capability)17286     void noteUidProcessState(final int uid, final int state,
17287                 final @ActivityManager.ProcessCapability int capability) {
17288         mBatteryStatsService.noteUidProcessState(uid, state);
17289         mAppOpsService.updateUidProcState(uid, state, capability);
17290         if (mTrackingAssociations) {
17291             for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
17292                 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
17293                         = mAssociations.valueAt(i1);
17294                 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
17295                     SparseArray<ArrayMap<String, Association>> sourceUids
17296                             = targetComponents.valueAt(i2);
17297                     ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid);
17298                     if (sourceProcesses != null) {
17299                         for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
17300                             Association ass = sourceProcesses.valueAt(i4);
17301                             if (ass.mNesting >= 1) {
17302                                 // currently associated
17303                                 long uptime = SystemClock.uptimeMillis();
17304                                 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
17305                                         += uptime - ass.mLastStateUptime;
17306                                 ass.mLastState = state;
17307                                 ass.mLastStateUptime = uptime;
17308                             }
17309                         }
17310                     }
17311                 }
17312             }
17313         }
17314     }
17315 
17316     /** @hide */
makeHeapDumpUri(String procName)17317     public static Uri makeHeapDumpUri(String procName) {
17318         return Uri.parse("content://com.android.shell.heapdump/" + procName + "_javaheap.bin");
17319     }
17320 
17321     private final class RecordPssRunnable implements Runnable {
17322         private final ProcessRecord mProc;
17323         private final Uri mDumpUri;
17324         private final ContentResolver mContentResolver;
17325 
RecordPssRunnable(ProcessRecord proc, Uri dumpUri, ContentResolver contentResolver)17326         RecordPssRunnable(ProcessRecord proc, Uri dumpUri, ContentResolver contentResolver) {
17327             mProc = proc;
17328             mDumpUri = dumpUri;
17329             mContentResolver = contentResolver;
17330         }
17331 
17332         @Override
run()17333         public void run() {
17334             try (ParcelFileDescriptor fd = mContentResolver.openFileDescriptor(mDumpUri, "rw")) {
17335                 IApplicationThread thread = mProc.thread;
17336                 if (thread != null) {
17337                     try {
17338                         if (DEBUG_PSS) {
17339                             Slog.d(TAG_PSS, "Requesting dump heap from "
17340                                     + mProc + " to " + mDumpUri.getPath());
17341                         }
17342                         thread.dumpHeap(/* managed= */ true,
17343                                 /* mallocInfo= */ false, /* runGc= */ false,
17344                                 mDumpUri.getPath(), fd,
17345                                 /* finishCallback= */ null);
17346                     } catch (RemoteException e) {
17347                     }
17348                 }
17349             } catch (IOException e) {
17350                 Slog.e(TAG, "Failed to dump heap", e);
17351                 // Need to clear the heap dump variables, otherwise no further heap dumps will be
17352                 // attempted.
17353                 abortHeapDump(mProc.processName);
17354             }
17355         }
17356     }
17357 
17358     /**
17359      * Record new PSS sample for a process.
17360      */
recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss, long rss, int statType, long pssDuration, long now)17361     void recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss,
17362             long rss, int statType, long pssDuration, long now) {
17363         EventLogTags.writeAmPss(proc.pid, proc.uid, proc.processName, pss * 1024, uss * 1024,
17364                 swapPss * 1024, rss * 1024, statType, procState, pssDuration);
17365         proc.lastPssTime = now;
17366         proc.baseProcessTracker.addPss(
17367                 pss, uss, rss, true, statType, pssDuration, proc.pkgList.mPkgList);
17368         for (int ipkg = proc.pkgList.mPkgList.size() - 1; ipkg >= 0; ipkg--) {
17369             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
17370             FrameworkStatsLog.write(FrameworkStatsLog.PROCESS_MEMORY_STAT_REPORTED,
17371                     proc.info.uid,
17372                     holder.state.getName(),
17373                     holder.state.getPackage(),
17374                     pss, uss, rss, statType, pssDuration,
17375                     holder.appVersion);
17376         }
17377         if (DEBUG_PSS) Slog.d(TAG_PSS,
17378                 "pss of " + proc.toShortString() + ": " + pss + " lastPss=" + proc.lastPss
17379                 + " state=" + ProcessList.makeProcStateString(procState));
17380         if (proc.initialIdlePss == 0) {
17381             proc.initialIdlePss = pss;
17382         }
17383         proc.lastPss = pss;
17384         proc.lastSwapPss = swapPss;
17385         if (procState >= ActivityManager.PROCESS_STATE_HOME) {
17386             proc.lastCachedPss = pss;
17387             proc.lastCachedSwapPss = swapPss;
17388         }
17389         proc.mLastRss = rss;
17390 
17391         final SparseArray<Pair<Long, String>> watchUids
17392                 = mMemWatchProcesses.getMap().get(proc.processName);
17393         Long check = null;
17394         if (watchUids != null) {
17395             Pair<Long, String> val = watchUids.get(proc.uid);
17396             if (val == null) {
17397                 val = watchUids.get(0);
17398             }
17399             if (val != null) {
17400                 check = val.first;
17401             }
17402         }
17403         if (check != null) {
17404             if ((pss * 1024) >= check && proc.thread != null && mMemWatchDumpProcName == null) {
17405                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
17406                 if (!isDebuggable) {
17407                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
17408                         isDebuggable = true;
17409                     }
17410                 }
17411                 if (isDebuggable) {
17412                     Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting");
17413                     startHeapDumpLocked(proc, false);
17414                 } else {
17415                     Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check
17416                             + ", but debugging not enabled");
17417                 }
17418             }
17419         }
17420     }
17421 
startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated)17422     private void startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated) {
17423         mMemWatchDumpProcName = proc.processName;
17424         mMemWatchDumpUri = makeHeapDumpUri(proc.processName);
17425         mMemWatchDumpPid = proc.pid;
17426         mMemWatchDumpUid = proc.uid;
17427         mMemWatchIsUserInitiated = isUserInitiated;
17428         Context ctx;
17429         try {
17430             ctx = mContext.createPackageContextAsUser("android", 0,
17431                     UserHandle.getUserHandleForUid(mMemWatchDumpUid));
17432         } catch (NameNotFoundException e) {
17433             throw new RuntimeException("android package not found.");
17434         }
17435         BackgroundThread.getHandler().post(
17436                 new RecordPssRunnable(proc, mMemWatchDumpUri, ctx.getContentResolver()));
17437     }
17438 
17439     /**
17440      * Schedule PSS collection of a process.
17441      */
requestPssLocked(ProcessRecord proc, int procState)17442     boolean requestPssLocked(ProcessRecord proc, int procState) {
17443         if (mPendingPssProcesses.contains(proc)) {
17444             return false;
17445         }
17446         if (mPendingPssProcesses.size() == 0) {
17447             final long deferral = (mPssDeferralTime > 0 && mActivityStartingNesting.get() > 0)
17448                     ? mPssDeferralTime : 0;
17449             if (DEBUG_PSS && deferral > 0) {
17450                 Slog.d(TAG_PSS, "requestPssLocked() deferring PSS request by "
17451                         + deferral + " ms");
17452             }
17453             mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, deferral);
17454         }
17455         if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of: " + proc);
17456         proc.pssProcState = procState;
17457         proc.pssStatType = ProcessStats.ADD_PSS_INTERNAL_SINGLE;
17458         mPendingPssProcesses.add(proc);
17459         return true;
17460     }
17461 
17462     /**
17463      * Re-defer a posted PSS collection pass, if one exists.  Assumes deferral is
17464      * currently active policy when called.
17465      */
deferPssIfNeededLocked()17466     private void deferPssIfNeededLocked() {
17467         if (mPendingPssProcesses.size() > 0) {
17468             mBgHandler.removeMessages(COLLECT_PSS_BG_MSG);
17469             mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, mPssDeferralTime);
17470         }
17471     }
17472 
deferPssForActivityStart()17473     private void deferPssForActivityStart() {
17474         synchronized (ActivityManagerService.this) {
17475             if (mPssDeferralTime > 0) {
17476                 if (DEBUG_PSS) {
17477                     Slog.d(TAG_PSS, "Deferring PSS collection for activity start");
17478                 }
17479                 deferPssIfNeededLocked();
17480                 mActivityStartingNesting.getAndIncrement();
17481                 mBgHandler.sendEmptyMessageDelayed(STOP_DEFERRING_PSS_MSG, mPssDeferralTime);
17482             }
17483         }
17484     }
17485 
17486     /**
17487      * Schedule PSS collection of all processes.
17488      */
requestPssAllProcsLocked(long now, boolean always, boolean memLowered)17489     void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) {
17490         if (!always) {
17491             if (now < (mLastFullPssTime +
17492                     (memLowered ? mConstants.FULL_PSS_LOWERED_INTERVAL
17493                             : mConstants.FULL_PSS_MIN_INTERVAL))) {
17494                 return;
17495             }
17496         }
17497         if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of all procs!  memLowered=" + memLowered);
17498         mLastFullPssTime = now;
17499         mFullPssPending = true;
17500         for (int i = mPendingPssProcesses.size() - 1; i >= 0; i--) {
17501             ProcessList.abortNextPssTime(mPendingPssProcesses.get(i).procStateMemTracker);;
17502         }
17503         mPendingPssProcesses.ensureCapacity(mProcessList.getLruSizeLocked());
17504         mPendingPssProcesses.clear();
17505         for (int i = mProcessList.getLruSizeLocked() - 1; i >= 0; i--) {
17506             ProcessRecord app = mProcessList.mLruProcesses.get(i);
17507             if (app.thread == null || app.getCurProcState() == PROCESS_STATE_NONEXISTENT) {
17508                 continue;
17509             }
17510             if (memLowered || (always && now >
17511                             app.lastStateTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
17512                     || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) {
17513                 app.pssProcState = app.setProcState;
17514                 app.pssStatType = always ? ProcessStats.ADD_PSS_INTERNAL_ALL_POLL
17515                         : ProcessStats.ADD_PSS_INTERNAL_ALL_MEM;
17516                 app.nextPssTime = ProcessList.computeNextPssTime(app.getCurProcState(),
17517                         app.procStateMemTracker, mTestPssMode, mAtmInternal.isSleeping(), now);
17518                 mPendingPssProcesses.add(app);
17519             }
17520         }
17521         if (!mBgHandler.hasMessages(COLLECT_PSS_BG_MSG)) {
17522             mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
17523         }
17524     }
17525 
setTestPssMode(boolean enabled)17526     public void setTestPssMode(boolean enabled) {
17527         synchronized (this) {
17528             mTestPssMode = enabled;
17529             if (enabled) {
17530                 // Whenever we enable the mode, we want to take a snapshot all of current
17531                 // process mem use.
17532                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, true);
17533             }
17534         }
17535     }
17536 
17537     /**
17538      * Ask a given process to GC right now.
17539      */
performAppGcLocked(ProcessRecord app)17540     final void performAppGcLocked(ProcessRecord app) {
17541         try {
17542             app.lastRequestedGc = SystemClock.uptimeMillis();
17543             if (app.thread != null) {
17544                 if (app.reportLowMemory) {
17545                     app.reportLowMemory = false;
17546                     app.thread.scheduleLowMemory();
17547                 } else {
17548                     app.thread.processInBackground();
17549                 }
17550             }
17551         } catch (Exception e) {
17552             // whatever.
17553         }
17554     }
17555 
17556     /**
17557      * Returns true if things are idle enough to perform GCs.
17558      */
canGcNowLocked()17559     private final boolean canGcNowLocked() {
17560         for (BroadcastQueue q : mBroadcastQueues) {
17561             if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isEmpty()) {
17562                 return false;
17563             }
17564         }
17565         return mAtmInternal.canGcNow();
17566     }
17567 
17568     /**
17569      * Perform GCs on all processes that are waiting for it, but only
17570      * if things are idle.
17571      */
performAppGcsLocked()17572     final void performAppGcsLocked() {
17573         final int N = mProcessesToGc.size();
17574         if (N <= 0) {
17575             return;
17576         }
17577         if (canGcNowLocked()) {
17578             while (mProcessesToGc.size() > 0) {
17579                 ProcessRecord proc = mProcessesToGc.remove(0);
17580                 if (proc.getCurRawAdj() > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
17581                     if ((proc.lastRequestedGc+mConstants.GC_MIN_INTERVAL)
17582                             <= SystemClock.uptimeMillis()) {
17583                         // To avoid spamming the system, we will GC processes one
17584                         // at a time, waiting a few seconds between each.
17585                         performAppGcLocked(proc);
17586                         scheduleAppGcsLocked();
17587                         return;
17588                     } else {
17589                         // It hasn't been long enough since we last GCed this
17590                         // process...  put it in the list to wait for its time.
17591                         addProcessToGcListLocked(proc);
17592                         break;
17593                     }
17594                 }
17595             }
17596 
17597             scheduleAppGcsLocked();
17598         }
17599     }
17600 
17601     /**
17602      * If all looks good, perform GCs on all processes waiting for them.
17603      */
performAppGcsIfAppropriateLocked()17604     final void performAppGcsIfAppropriateLocked() {
17605         if (canGcNowLocked()) {
17606             performAppGcsLocked();
17607             return;
17608         }
17609         // Still not idle, wait some more.
17610         scheduleAppGcsLocked();
17611     }
17612 
17613     /**
17614      * Schedule the execution of all pending app GCs.
17615      */
scheduleAppGcsLocked()17616     final void scheduleAppGcsLocked() {
17617         mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
17618 
17619         if (mProcessesToGc.size() > 0) {
17620             // Schedule a GC for the time to the next process.
17621             ProcessRecord proc = mProcessesToGc.get(0);
17622             Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
17623 
17624             long when = proc.lastRequestedGc + mConstants.GC_MIN_INTERVAL;
17625             long now = SystemClock.uptimeMillis();
17626             if (when < (now+mConstants.GC_TIMEOUT)) {
17627                 when = now + mConstants.GC_TIMEOUT;
17628             }
17629             mHandler.sendMessageAtTime(msg, when);
17630         }
17631     }
17632 
17633     /**
17634      * Add a process to the array of processes waiting to be GCed.  Keeps the
17635      * list in sorted order by the last GC time.  The process can't already be
17636      * on the list.
17637      */
addProcessToGcListLocked(ProcessRecord proc)17638     final void addProcessToGcListLocked(ProcessRecord proc) {
17639         boolean added = false;
17640         for (int i=mProcessesToGc.size()-1; i>=0; i--) {
17641             if (mProcessesToGc.get(i).lastRequestedGc <
17642                     proc.lastRequestedGc) {
17643                 added = true;
17644                 mProcessesToGc.add(i+1, proc);
17645                 break;
17646             }
17647         }
17648         if (!added) {
17649             mProcessesToGc.add(0, proc);
17650         }
17651     }
17652 
17653     /**
17654      * Set up to ask a process to GC itself.  This will either do it
17655      * immediately, or put it on the list of processes to gc the next
17656      * time things are idle.
17657      */
scheduleAppGcLocked(ProcessRecord app)17658     final void scheduleAppGcLocked(ProcessRecord app) {
17659         long now = SystemClock.uptimeMillis();
17660         if ((app.lastRequestedGc+mConstants.GC_MIN_INTERVAL) > now) {
17661             return;
17662         }
17663         if (!mProcessesToGc.contains(app)) {
17664             addProcessToGcListLocked(app);
17665             scheduleAppGcsLocked();
17666         }
17667     }
17668 
checkExcessivePowerUsageLocked()17669     final void checkExcessivePowerUsageLocked() {
17670         updateCpuStatsNow();
17671 
17672         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
17673         boolean doCpuKills = true;
17674         if (mLastPowerCheckUptime == 0) {
17675             doCpuKills = false;
17676         }
17677         final long curUptime = SystemClock.uptimeMillis();
17678         final long uptimeSince = curUptime - mLastPowerCheckUptime;
17679         mLastPowerCheckUptime = curUptime;
17680         int i = mProcessList.mLruProcesses.size();
17681         while (i > 0) {
17682             i--;
17683             ProcessRecord app = mProcessList.mLruProcesses.get(i);
17684             if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
17685                 if (app.lastCpuTime <= 0) {
17686                     continue;
17687                 }
17688                 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
17689                 if (DEBUG_POWER) {
17690                     StringBuilder sb = new StringBuilder(128);
17691                     sb.append("CPU for ");
17692                     app.toShortString(sb);
17693                     sb.append(": over ");
17694                     TimeUtils.formatDuration(uptimeSince, sb);
17695                     sb.append(" used ");
17696                     TimeUtils.formatDuration(cputimeUsed, sb);
17697                     sb.append(" (");
17698                     sb.append((cputimeUsed*100)/uptimeSince);
17699                     sb.append("%)");
17700                     Slog.i(TAG_POWER, sb.toString());
17701                 }
17702                 // If the process has used too much CPU over the last duration, the
17703                 // user probably doesn't want this, so kill!
17704                 if (doCpuKills && uptimeSince > 0) {
17705                     // What is the limit for this process?
17706                     int cpuLimit;
17707                     long checkDur = curUptime - app.getWhenUnimportant();
17708                     if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
17709                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
17710                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*2)
17711                             || app.setProcState <= ActivityManager.PROCESS_STATE_HOME) {
17712                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
17713                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*3)) {
17714                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
17715                     } else {
17716                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
17717                     }
17718                     if (((cputimeUsed*100)/uptimeSince) >= cpuLimit) {
17719                         synchronized (stats) {
17720                             stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
17721                                     uptimeSince, cputimeUsed);
17722                         }
17723                         app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince
17724                                 + " dur=" + checkDur + " limit=" + cpuLimit,
17725                                 ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE,
17726                                 ApplicationExitInfo.SUBREASON_EXCESSIVE_CPU,
17727                                 true);
17728                         app.baseProcessTracker.reportExcessiveCpu(app.pkgList.mPkgList);
17729                         for (int ipkg = app.pkgList.size() - 1; ipkg >= 0; ipkg--) {
17730                             ProcessStats.ProcessStateHolder holder = app.pkgList.valueAt(ipkg);
17731                             FrameworkStatsLog.write(FrameworkStatsLog.EXCESSIVE_CPU_USAGE_REPORTED,
17732                                     app.info.uid,
17733                                     holder.state.getName(),
17734                                     holder.state.getPackage(),
17735                                     holder.appVersion);
17736                         }
17737                     }
17738                 }
17739                 app.lastCpuTime = app.curCpuTime;
17740             }
17741         }
17742     }
17743 
isEphemeralLocked(int uid)17744     private boolean isEphemeralLocked(int uid) {
17745         String packages[] = mContext.getPackageManager().getPackagesForUid(uid);
17746         if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid
17747             return false;
17748         }
17749         return getPackageManagerInternalLocked().isPackageEphemeral(UserHandle.getUserId(uid),
17750                 packages[0]);
17751     }
17752 
17753     @VisibleForTesting
enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)17754     final void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) {
17755         final UidRecord.ChangeItem pendingChange;
17756         if (uidRec == null || uidRec.pendingChange == null) {
17757             if (mPendingUidChanges.size() == 0) {
17758                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
17759                         "*** Enqueueing dispatch uid changed!");
17760                 mUiHandler.obtainMessage(DISPATCH_UIDS_CHANGED_UI_MSG).sendToTarget();
17761             }
17762             final int NA = mAvailUidChanges.size();
17763             if (NA > 0) {
17764                 pendingChange = mAvailUidChanges.remove(NA-1);
17765                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
17766                         "Retrieving available item: " + pendingChange);
17767             } else {
17768                 pendingChange = new UidRecord.ChangeItem();
17769                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
17770                         "Allocating new item: " + pendingChange);
17771             }
17772             if (uidRec != null) {
17773                 uidRec.pendingChange = pendingChange;
17774                 if ((change & UidRecord.CHANGE_GONE) != 0 && !uidRec.idle) {
17775                     // If this uid is going away, and we haven't yet reported it is gone,
17776                     // then do so now.
17777                     change |= UidRecord.CHANGE_IDLE;
17778                 }
17779             } else if (uid < 0) {
17780                 throw new IllegalArgumentException("No UidRecord or uid");
17781             }
17782             pendingChange.uidRecord = uidRec;
17783             pendingChange.uid = uidRec != null ? uidRec.uid : uid;
17784             mPendingUidChanges.add(pendingChange);
17785         } else {
17786             pendingChange = uidRec.pendingChange;
17787             // If there is no change in idle or active state, then keep whatever was pending.
17788             if ((change & (UidRecord.CHANGE_IDLE | UidRecord.CHANGE_ACTIVE)) == 0) {
17789                 change |= (pendingChange.change & (UidRecord.CHANGE_IDLE
17790                         | UidRecord.CHANGE_ACTIVE));
17791             }
17792             // If there is no change in cached or uncached state, then keep whatever was pending.
17793             if ((change & (UidRecord.CHANGE_CACHED | UidRecord.CHANGE_UNCACHED)) == 0) {
17794                 change |= (pendingChange.change & (UidRecord.CHANGE_CACHED
17795                         | UidRecord.CHANGE_UNCACHED));
17796             }
17797             // If this is a report of the UID being gone, then we shouldn't keep any previous
17798             // report of it being active or cached.  (That is, a gone uid is never active,
17799             // and never cached.)
17800             if ((change & UidRecord.CHANGE_GONE) != 0) {
17801                 change &= ~(UidRecord.CHANGE_ACTIVE | UidRecord.CHANGE_CACHED);
17802                 if (!uidRec.idle) {
17803                     // If this uid is going away, and we haven't yet reported it is gone,
17804                     // then do so now.
17805                     change |= UidRecord.CHANGE_IDLE;
17806                 }
17807             }
17808         }
17809         pendingChange.change = change;
17810         pendingChange.processState = uidRec != null ? uidRec.setProcState : PROCESS_STATE_NONEXISTENT;
17811         pendingChange.capability = uidRec != null ? uidRec.setCapability : 0;
17812         pendingChange.ephemeral = uidRec != null ? uidRec.ephemeral : isEphemeralLocked(uid);
17813         pendingChange.procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0;
17814         if (uidRec != null) {
17815             uidRec.lastReportedChange = change;
17816             uidRec.updateLastDispatchedProcStateSeq(change);
17817         }
17818 
17819         // Directly update the power manager, since we sit on top of it and it is critical
17820         // it be kept in sync (so wake locks will be held as soon as appropriate).
17821         if (mLocalPowerManager != null) {
17822             // TO DO: dispatch cached/uncached changes here, so we don't need to report
17823             // all proc state changes.
17824             if ((change & UidRecord.CHANGE_ACTIVE) != 0) {
17825                 mLocalPowerManager.uidActive(pendingChange.uid);
17826             }
17827             if ((change & UidRecord.CHANGE_IDLE) != 0) {
17828                 mLocalPowerManager.uidIdle(pendingChange.uid);
17829             }
17830             if ((change & UidRecord.CHANGE_GONE) != 0) {
17831                 mLocalPowerManager.uidGone(pendingChange.uid);
17832             } else {
17833                 mLocalPowerManager.updateUidProcState(pendingChange.uid,
17834                         pendingChange.processState);
17835             }
17836         }
17837     }
17838 
maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, String authority)17839     private void maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName,
17840             String authority) {
17841         if (app == null) return;
17842         if (app.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
17843             UserState userState = mUserController.getStartedUserState(app.userId);
17844             if (userState == null) return;
17845             final long now = SystemClock.elapsedRealtime();
17846             Long lastReported = userState.mProviderLastReportedFg.get(authority);
17847             if (lastReported == null || lastReported < now - 60 * 1000L) {
17848                 if (mSystemReady) {
17849                     // Cannot touch the user stats if not system ready
17850                     mUsageStatsService.reportContentProviderUsage(
17851                             authority, providerPkgName, app.userId);
17852                 }
17853                 userState.mProviderLastReportedFg.put(authority, now);
17854             }
17855         }
17856     }
17857 
setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now)17858     final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) {
17859         if (proc.thread != null && proc.baseProcessTracker != null) {
17860             final int procState = proc.getReportedProcState();
17861             if (procState != PROCESS_STATE_NONEXISTENT) {
17862                 proc.baseProcessTracker.setState(
17863                         procState, memFactor, now, proc.pkgList.mPkgList);
17864             }
17865         }
17866     }
17867 
17868     @GuardedBy("this")
updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)17869     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
17870             int fgServiceTypes, boolean oomAdj) {
17871         if (isForeground != proc.hasForegroundServices()
17872                 || proc.getForegroundServiceTypes() != fgServiceTypes) {
17873             proc.setHasForegroundServices(isForeground, fgServiceTypes);
17874             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
17875                     proc.info.uid);
17876             if (isForeground) {
17877                 if (curProcs == null) {
17878                     curProcs = new ArrayList<ProcessRecord>();
17879                     mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
17880                 }
17881                 if (!curProcs.contains(proc)) {
17882                     curProcs.add(proc);
17883                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
17884                             proc.info.packageName, proc.info.uid);
17885                 }
17886             } else {
17887                 if (curProcs != null) {
17888                     if (curProcs.remove(proc)) {
17889                         mBatteryStatsService.noteEvent(
17890                                 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
17891                                 proc.info.packageName, proc.info.uid);
17892                         if (curProcs.size() <= 0) {
17893                             mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
17894                         }
17895                     }
17896                 }
17897             }
17898 
17899             proc.setReportedForegroundServiceTypes(fgServiceTypes);
17900             ProcessChangeItem item = enqueueProcessChangeItemLocked(proc.pid, proc.info.uid);
17901             item.changes |= ProcessChangeItem.CHANGE_FOREGROUND_SERVICES;
17902             item.foregroundServiceTypes = fgServiceTypes;
17903         }
17904         if (oomAdj) {
17905             updateOomAdjLocked(proc, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
17906         }
17907     }
17908 
17909     // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update
17910     // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities
getTopAppLocked()17911     ProcessRecord getTopAppLocked() {
17912         final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null;
17913         final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null;
17914         String pkg;
17915         int uid;
17916         if (r != null) {
17917             pkg = r.processName;
17918             uid = r.info.uid;
17919         } else {
17920             pkg = null;
17921             uid = -1;
17922         }
17923         // Has the UID or resumed package name changed?
17924         if (uid != mCurResumedUid || (pkg != mCurResumedPackage
17925                 && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
17926 
17927             final long identity = Binder.clearCallingIdentity();
17928             try {
17929                 if (mCurResumedPackage != null) {
17930                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
17931                             mCurResumedPackage, mCurResumedUid);
17932                 }
17933                 mCurResumedPackage = pkg;
17934                 mCurResumedUid = uid;
17935                 if (mCurResumedPackage != null) {
17936                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
17937                             mCurResumedPackage, mCurResumedUid);
17938                 }
17939             } finally {
17940                 Binder.restoreCallingIdentity(identity);
17941             }
17942 
17943         }
17944         return r;
17945     }
17946 
17947     /**
17948      * Update OomAdj for a specific process.
17949      * @param app The process to update
17950      * @param oomAdjAll If it's ok to call updateOomAdjLocked() for all running apps
17951      *                  if necessary, or skip.
17952      * @param oomAdjReason
17953      * @return whether updateOomAdjLocked(app) was successful.
17954      */
17955     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll, String oomAdjReason)17956     final boolean updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll,
17957             String oomAdjReason) {
17958         return mOomAdjuster.updateOomAdjLocked(app, oomAdjAll, oomAdjReason);
17959     }
17960 
17961     static final class ProcStatsRunnable implements Runnable {
17962         private final ActivityManagerService mService;
17963         private final ProcessStatsService mProcessStats;
17964 
ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)17965         ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) {
17966             this.mService = service;
17967             this.mProcessStats = mProcessStats;
17968         }
17969 
run()17970         @Override public void run() {
17971             synchronized (mService) {
17972                 mProcessStats.writeStateAsyncLocked();
17973             }
17974         }
17975     }
17976 
17977     @GuardedBy("this")
updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming)17978     final boolean updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming) {
17979         final int N = mProcessList.getLruSizeLocked();
17980         final long now = SystemClock.uptimeMillis();
17981         int memFactor;
17982         if (mLowMemDetector != null && mLowMemDetector.isAvailable()) {
17983             memFactor = mLowMemDetector.getMemFactor();
17984         } else {
17985             // Now determine the memory trimming level of background processes.
17986             // Unfortunately we need to start at the back of the list to do this
17987             // properly.  We only do this if the number of background apps we
17988             // are managing to keep around is less than half the maximum we desire;
17989             // if we are keeping a good number around, we'll let them use whatever
17990             // memory they want.
17991             if (numCached <= mConstants.CUR_TRIM_CACHED_PROCESSES
17992                 && numEmpty <= mConstants.CUR_TRIM_EMPTY_PROCESSES) {
17993                 final int numCachedAndEmpty = numCached + numEmpty;
17994                 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
17995                     memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL;
17996                 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
17997                     memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW;
17998                 } else {
17999                     memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE;
18000                 }
18001             } else {
18002                 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
18003             }
18004         }
18005         // We always allow the memory level to go up (better).  We only allow it to go
18006         // down if we are in a state where that is allowed, *and* the total number of processes
18007         // has gone down since last time.
18008         if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "oom: memFactor=" + memFactor
18009                 + " last=" + mLastMemoryLevel + " allowLow=" + mAllowLowerMemLevel
18010                 + " numProcs=" + mProcessList.getLruSizeLocked() + " last=" + mLastNumProcesses);
18011         if (memFactor > mLastMemoryLevel) {
18012             if (!mAllowLowerMemLevel || mProcessList.getLruSizeLocked() >= mLastNumProcesses) {
18013                 memFactor = mLastMemoryLevel;
18014                 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "Keeping last mem factor!");
18015             }
18016         }
18017         if (memFactor != mLastMemoryLevel) {
18018             EventLogTags.writeAmMemFactor(memFactor, mLastMemoryLevel);
18019             FrameworkStatsLog.write(FrameworkStatsLog.MEMORY_FACTOR_STATE_CHANGED, memFactor);
18020         }
18021         mLastMemoryLevel = memFactor;
18022         mLastNumProcesses = mProcessList.getLruSizeLocked();
18023         boolean allChanged = mProcessStats.setMemFactorLocked(
18024                 memFactor, mAtmInternal != null ? !mAtmInternal.isSleeping() : true, now);
18025         final int trackerMemFactor = mProcessStats.getMemFactorLocked();
18026         if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) {
18027             if (mLowRamStartTime == 0) {
18028                 mLowRamStartTime = now;
18029             }
18030             int step = 0;
18031             int fgTrimLevel;
18032             switch (memFactor) {
18033                 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
18034                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
18035                     break;
18036                 case ProcessStats.ADJ_MEM_FACTOR_LOW:
18037                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
18038                     break;
18039                 default:
18040                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
18041                     break;
18042             }
18043             int factor = numTrimming/3;
18044             int minFactor = 2;
18045             if (mAtmInternal.getHomeProcess() != null) minFactor++;
18046             if (mAtmInternal.getPreviousProcess() != null) minFactor++;
18047             if (factor < minFactor) factor = minFactor;
18048             int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
18049             for (int i=N-1; i>=0; i--) {
18050                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
18051                 if (allChanged || app.procStateChanged) {
18052                     setProcessTrackerStateLocked(app, trackerMemFactor, now);
18053                     app.procStateChanged = false;
18054                 }
18055                 if (app.getCurProcState() >= ActivityManager.PROCESS_STATE_HOME
18056                         && !app.killedByAm) {
18057                     if (app.trimMemoryLevel < curLevel && app.thread != null) {
18058                         try {
18059                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
18060                                     "Trimming memory of " + app.processName + " to " + curLevel);
18061                             app.thread.scheduleTrimMemory(curLevel);
18062                         } catch (RemoteException e) {
18063                         }
18064                     }
18065                     app.trimMemoryLevel = curLevel;
18066                     step++;
18067                     if (step >= factor) {
18068                         step = 0;
18069                         switch (curLevel) {
18070                             case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
18071                                 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
18072                                 break;
18073                             case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
18074                                 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
18075                                 break;
18076                         }
18077                     }
18078                 } else if (app.getCurProcState() == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
18079                         && !app.killedByAm) {
18080                     if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
18081                             && app.thread != null) {
18082                         try {
18083                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
18084                                     "Trimming memory of heavy-weight " + app.processName
18085                                     + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
18086                             app.thread.scheduleTrimMemory(
18087                                     ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
18088                         } catch (RemoteException e) {
18089                         }
18090                     }
18091                     app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
18092                 } else {
18093                     if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
18094                             || app.systemNoUi) && app.hasPendingUiClean()) {
18095                         // If this application is now in the background and it
18096                         // had done UI, then give it the special trim level to
18097                         // have it free UI resources.
18098                         final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
18099                         if (app.trimMemoryLevel < level && app.thread != null) {
18100                             try {
18101                                 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
18102                                         "Trimming memory of bg-ui " + app.processName
18103                                         + " to " + level);
18104                                 app.thread.scheduleTrimMemory(level);
18105                             } catch (RemoteException e) {
18106                             }
18107                         }
18108                         app.setPendingUiClean(false);
18109                     }
18110                     if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
18111                         try {
18112                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
18113                                     "Trimming memory of fg " + app.processName
18114                                     + " to " + fgTrimLevel);
18115                             app.thread.scheduleTrimMemory(fgTrimLevel);
18116                         } catch (RemoteException e) {
18117                         }
18118                     }
18119                     app.trimMemoryLevel = fgTrimLevel;
18120                 }
18121             }
18122         } else {
18123             if (mLowRamStartTime != 0) {
18124                 mLowRamTimeSinceLastIdle += now - mLowRamStartTime;
18125                 mLowRamStartTime = 0;
18126             }
18127             for (int i=N-1; i>=0; i--) {
18128                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
18129                 if (allChanged || app.procStateChanged) {
18130                     setProcessTrackerStateLocked(app, trackerMemFactor, now);
18131                     app.procStateChanged = false;
18132                 }
18133                 if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
18134                         || app.systemNoUi) && app.hasPendingUiClean()) {
18135                     if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
18136                             && app.thread != null) {
18137                         try {
18138                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
18139                                     "Trimming memory of ui hidden " + app.processName
18140                                     + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
18141                             app.thread.scheduleTrimMemory(
18142                                     ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
18143                         } catch (RemoteException e) {
18144                         }
18145                     }
18146                     app.setPendingUiClean(false);
18147                 }
18148                 app.trimMemoryLevel = 0;
18149             }
18150         }
18151         return allChanged;
18152     }
18153 
18154     @GuardedBy("this")
updateOomAdjLocked(String oomAdjReason)18155     final void updateOomAdjLocked(String oomAdjReason) {
18156         mOomAdjuster.updateOomAdjLocked(oomAdjReason);
18157     }
18158 
18159     /*
18160      * Update OomAdj for a specific process and its reachable processes.
18161      * @param app The process to update
18162      * @param oomAdjReason
18163      */
18164     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, String oomAdjReason)18165     final void updateOomAdjLocked(ProcessRecord app, String oomAdjReason) {
18166         mOomAdjuster.updateOomAdjLocked(app, oomAdjReason);
18167     }
18168 
18169     @Override
makePackageIdle(String packageName, int userId)18170     public void makePackageIdle(String packageName, int userId) {
18171         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
18172                 != PackageManager.PERMISSION_GRANTED) {
18173             String msg = "Permission Denial: makePackageIdle() from pid="
18174                     + Binder.getCallingPid()
18175                     + ", uid=" + Binder.getCallingUid()
18176                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
18177             Slog.w(TAG, msg);
18178             throw new SecurityException(msg);
18179         }
18180         final int callingPid = Binder.getCallingPid();
18181         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
18182                 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null);
18183         long callingId = Binder.clearCallingIdentity();
18184         synchronized(this) {
18185             try {
18186                 IPackageManager pm = AppGlobals.getPackageManager();
18187                 int pkgUid = -1;
18188                 try {
18189                     pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES
18190                             | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM);
18191                 } catch (RemoteException e) {
18192                 }
18193                 if (pkgUid == -1) {
18194                     throw new IllegalArgumentException("Unknown package name " + packageName);
18195                 }
18196 
18197                 if (mLocalPowerManager != null) {
18198                     mLocalPowerManager.startUidChanges();
18199                 }
18200                 final int appId = UserHandle.getAppId(pkgUid);
18201                 final int N = mProcessList.mActiveUids.size();
18202                 for (int i = N - 1; i >= 0; i--) {
18203                     final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
18204                     final long bgTime = uidRec.lastBackgroundTime;
18205                     if (bgTime > 0 && !uidRec.idle) {
18206                         if (UserHandle.getAppId(uidRec.uid) == appId) {
18207                             if (userId == UserHandle.USER_ALL ||
18208                                     userId == UserHandle.getUserId(uidRec.uid)) {
18209                                 EventLogTags.writeAmUidIdle(uidRec.uid);
18210                                 uidRec.idle = true;
18211                                 uidRec.setIdle = true;
18212                                 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uidRec.uid)
18213                                         + " from package " + packageName + " user " + userId);
18214                                 doStopUidLocked(uidRec.uid, uidRec);
18215                             }
18216                         }
18217                     }
18218                 }
18219             } finally {
18220                 if (mLocalPowerManager != null) {
18221                     mLocalPowerManager.finishUidChanges();
18222                 }
18223                 Binder.restoreCallingIdentity(callingId);
18224             }
18225         }
18226     }
18227 
18228     /** Make the currently active UIDs idle after a certain grace period. */
idleUids()18229     final void idleUids() {
18230         synchronized (this) {
18231             mOomAdjuster.idleUidsLocked();
18232         }
18233     }
18234 
runInBackgroundDisabled(int uid)18235     final void runInBackgroundDisabled(int uid) {
18236         synchronized (this) {
18237             UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
18238             if (uidRec != null) {
18239                 // This uid is actually running...  should it be considered background now?
18240                 if (uidRec.idle) {
18241                     doStopUidLocked(uidRec.uid, uidRec);
18242                 }
18243             } else {
18244                 // This uid isn't actually running...  still send a report about it being "stopped".
18245                 doStopUidLocked(uid, null);
18246             }
18247         }
18248     }
18249 
cameraActiveChanged(@serIdInt int uid, boolean active)18250     final void cameraActiveChanged(@UserIdInt int uid, boolean active) {
18251         synchronized (mActiveCameraUids) {
18252             final int curIndex = mActiveCameraUids.indexOf(uid);
18253             if (active) {
18254                 if (curIndex < 0) {
18255                     mActiveCameraUids.add(uid);
18256                 }
18257             } else {
18258                 if (curIndex >= 0) {
18259                     mActiveCameraUids.remove(curIndex);
18260                 }
18261             }
18262         }
18263     }
18264 
isCameraActiveForUid(@serIdInt int uid)18265     final boolean isCameraActiveForUid(@UserIdInt int uid) {
18266         synchronized (mActiveCameraUids) {
18267             return mActiveCameraUids.indexOf(uid) >= 0;
18268         }
18269     }
18270 
18271     @GuardedBy("this")
doStopUidLocked(int uid, final UidRecord uidRec)18272     final void doStopUidLocked(int uid, final UidRecord uidRec) {
18273         mServices.stopInBackgroundLocked(uid);
18274         enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE);
18275     }
18276 
18277     /**
18278      * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
18279      */
18280     @GuardedBy("this")
tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, String tag)18281     void tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid,
18282             long duration, String tag) {
18283         if (DEBUG_WHITELISTS) {
18284             Slog.d(TAG, "tempWhitelistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", "
18285                     + targetUid + ", " + duration + ")");
18286         }
18287 
18288         synchronized (mPidsSelfLocked) {
18289             final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
18290             if (pr == null) {
18291                 Slog.w(TAG, "tempWhitelistForPendingIntentLocked() no ProcessRecord for pid "
18292                         + callerPid);
18293                 return;
18294             }
18295             if (!pr.whitelistManager) {
18296                 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid)
18297                         != PackageManager.PERMISSION_GRANTED) {
18298                     if (DEBUG_WHITELISTS) {
18299                         Slog.d(TAG, "tempWhitelistForPendingIntentLocked() for target " + targetUid
18300                                 + ": pid " + callerPid + " is not allowed");
18301                     }
18302                     return;
18303                 }
18304             }
18305         }
18306 
18307         tempWhitelistUidLocked(targetUid, duration, tag);
18308     }
18309 
18310     /**
18311      * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
18312      */
18313     @GuardedBy("this")
tempWhitelistUidLocked(int targetUid, long duration, String tag)18314     void tempWhitelistUidLocked(int targetUid, long duration, String tag) {
18315         mPendingTempWhitelist.put(targetUid, new PendingTempWhitelist(targetUid, duration, tag));
18316         setUidTempWhitelistStateLocked(targetUid, true);
18317         mUiHandler.obtainMessage(PUSH_TEMP_WHITELIST_UI_MSG).sendToTarget();
18318     }
18319 
pushTempWhitelist()18320     void pushTempWhitelist() {
18321         final int N;
18322         final PendingTempWhitelist[] list;
18323 
18324         // First copy out the pending changes...  we need to leave them in the map for now,
18325         // in case someone needs to check what is coming up while we don't have the lock held.
18326         synchronized(this) {
18327             N = mPendingTempWhitelist.size();
18328             list = new PendingTempWhitelist[N];
18329             for (int i = 0; i < N; i++) {
18330                 list[i] = mPendingTempWhitelist.valueAt(i);
18331             }
18332         }
18333 
18334         // Now safely dispatch changes to device idle controller.  Skip this if we're early
18335         // in boot and the controller hasn't yet been brought online:  we do not apply
18336         // device idle policy anyway at this phase.
18337         if (mLocalDeviceIdleController != null) {
18338             for (int i = 0; i < N; i++) {
18339                 PendingTempWhitelist ptw = list[i];
18340                 mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid,
18341                         ptw.duration, true, ptw.tag);
18342             }
18343         }
18344 
18345         // And now we can safely remove them from the map.
18346         synchronized(this) {
18347             for (int i = 0; i < N; i++) {
18348                 PendingTempWhitelist ptw = list[i];
18349                 int index = mPendingTempWhitelist.indexOfKey(ptw.targetUid);
18350                 if (index >= 0 && mPendingTempWhitelist.valueAt(index) == ptw) {
18351                     mPendingTempWhitelist.removeAt(index);
18352                 }
18353             }
18354         }
18355     }
18356 
18357     @GuardedBy("this")
setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist)18358     final void setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist) {
18359         mOomAdjuster.setAppIdTempWhitelistStateLocked(appId, onWhitelist);
18360     }
18361 
18362     @GuardedBy("this")
setUidTempWhitelistStateLocked(int uid, boolean onWhitelist)18363     final void setUidTempWhitelistStateLocked(int uid, boolean onWhitelist) {
18364         mOomAdjuster.setUidTempWhitelistStateLocked(uid, onWhitelist);
18365     }
18366 
trimApplications(String oomAdjReason)18367     final void trimApplications(String oomAdjReason) {
18368         synchronized (this) {
18369             trimApplicationsLocked(oomAdjReason);
18370         }
18371     }
18372 
18373     @GuardedBy("this")
trimApplicationsLocked(String oomAdjReason)18374     final void trimApplicationsLocked(String oomAdjReason) {
18375         // First remove any unused application processes whose package
18376         // has been removed.
18377         for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) {
18378             final ProcessRecord app = mProcessList.mRemovedProcesses.get(i);
18379             if (!app.hasActivitiesOrRecentTasks()
18380                     && app.curReceivers.isEmpty() && app.numberOfRunningServices() == 0) {
18381                 Slog.i(
18382                     TAG, "Exiting empty application process "
18383                     + app.toShortString() + " ("
18384                     + (app.thread != null ? app.thread.asBinder() : null)
18385                     + ")\n");
18386                 if (app.pid > 0 && app.pid != MY_PID) {
18387                     app.kill("empty",
18388                             ApplicationExitInfo.REASON_OTHER,
18389                             ApplicationExitInfo.SUBREASON_TRIM_EMPTY,
18390                             false);
18391                 } else if (app.thread != null) {
18392                     try {
18393                         app.thread.scheduleExit();
18394                     } catch (Exception e) {
18395                         // Ignore exceptions.
18396                     }
18397                 }
18398                 cleanUpApplicationRecordLocked(app, false, true, -1, false /*replacingPid*/);
18399                 mProcessList.mRemovedProcesses.remove(i);
18400 
18401                 if (app.isPersistent()) {
18402                     addAppLocked(app.info, null, false, null /* ABI override */,
18403                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
18404                 }
18405             }
18406         }
18407 
18408         // Now update the oom adj for all processes. Don't skip this, since other callers
18409         // might be depending on it.
18410         updateOomAdjLocked(oomAdjReason);
18411     }
18412 
18413     /** This method sends the specified signal to each of the persistent apps */
signalPersistentProcesses(int sig)18414     public void signalPersistentProcesses(int sig) throws RemoteException {
18415         if (sig != SIGNAL_USR1) {
18416             throw new SecurityException("Only SIGNAL_USR1 is allowed");
18417         }
18418 
18419         synchronized (this) {
18420             if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
18421                     != PackageManager.PERMISSION_GRANTED) {
18422                 throw new SecurityException("Requires permission "
18423                         + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
18424             }
18425 
18426             for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) {
18427                 ProcessRecord r = mProcessList.mLruProcesses.get(i);
18428                 if (r.thread != null && r.isPersistent()) {
18429                     sendSignal(r.pid, sig);
18430                 }
18431             }
18432         }
18433     }
18434 
stopProfilerLocked(ProcessRecord proc, int profileType)18435     private void stopProfilerLocked(ProcessRecord proc, int profileType) {
18436         if (proc == null || proc == mProfileData.getProfileProc()) {
18437             proc = mProfileData.getProfileProc();
18438             profileType = mProfileType;
18439             clearProfilerLocked();
18440         }
18441         if (proc == null) {
18442             return;
18443         }
18444         try {
18445             proc.thread.profilerControl(false, null, profileType);
18446         } catch (RemoteException e) {
18447             throw new IllegalStateException("Process disappeared");
18448         }
18449     }
18450 
clearProfilerLocked()18451     void clearProfilerLocked() {
18452         if (mProfileData.getProfilerInfo() != null
18453                 && mProfileData.getProfilerInfo().profileFd != null) {
18454             try {
18455                 mProfileData.getProfilerInfo().profileFd.close();
18456             } catch (IOException e) {
18457             }
18458         }
18459         mProfileData.setProfileApp(null);
18460         mProfileData.setProfileProc(null);
18461         mProfileData.setProfilerInfo(null);
18462     }
18463 
profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)18464     public boolean profileControl(String process, int userId, boolean start,
18465             ProfilerInfo profilerInfo, int profileType) throws RemoteException {
18466 
18467         try {
18468             synchronized (this) {
18469                 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
18470                 // its own permission.
18471                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
18472                         != PackageManager.PERMISSION_GRANTED) {
18473                     throw new SecurityException("Requires permission "
18474                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
18475                 }
18476 
18477                 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
18478                     throw new IllegalArgumentException("null profile info or fd");
18479                 }
18480 
18481                 ProcessRecord proc = null;
18482                 if (process != null) {
18483                     proc = findProcessLocked(process, userId, "profileControl");
18484                 }
18485 
18486                 if (start && (proc == null || proc.thread == null)) {
18487                     throw new IllegalArgumentException("Unknown process: " + process);
18488                 }
18489 
18490                 if (start) {
18491                     stopProfilerLocked(null, 0);
18492                     setProfileApp(proc.info, proc.processName, profilerInfo);
18493                     mProfileData.setProfileProc(proc);
18494                     mProfileType = profileType;
18495                     ParcelFileDescriptor fd = profilerInfo.profileFd;
18496                     try {
18497                         fd = fd.dup();
18498                     } catch (IOException e) {
18499                         fd = null;
18500                     }
18501                     profilerInfo.profileFd = fd;
18502                     proc.thread.profilerControl(start, profilerInfo, profileType);
18503                     fd = null;
18504                     try {
18505                         mProfileData.getProfilerInfo().profileFd.close();
18506                     } catch (IOException e) {
18507                     }
18508                     mProfileData.getProfilerInfo().profileFd = null;
18509 
18510                     if (proc.pid == MY_PID) {
18511                         // When profiling the system server itself, avoid closing the file
18512                         // descriptor, as profilerControl will not create a copy.
18513                         // Note: it is also not correct to just set profileFd to null, as the
18514                         //       whole ProfilerInfo instance is passed down!
18515                         profilerInfo = null;
18516                     }
18517                 } else {
18518                     stopProfilerLocked(proc, profileType);
18519                     if (profilerInfo != null && profilerInfo.profileFd != null) {
18520                         try {
18521                             profilerInfo.profileFd.close();
18522                         } catch (IOException e) {
18523                         }
18524                     }
18525                 }
18526 
18527                 return true;
18528             }
18529         } catch (RemoteException e) {
18530             throw new IllegalStateException("Process disappeared");
18531         } finally {
18532             if (profilerInfo != null && profilerInfo.profileFd != null) {
18533                 try {
18534                     profilerInfo.profileFd.close();
18535                 } catch (IOException e) {
18536                 }
18537             }
18538         }
18539     }
18540 
findProcessLocked(String process, int userId, String callName)18541     private ProcessRecord findProcessLocked(String process, int userId, String callName) {
18542         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
18543                 userId, true, ALLOW_FULL_ONLY, callName, null);
18544         ProcessRecord proc = null;
18545         try {
18546             int pid = Integer.parseInt(process);
18547             synchronized (mPidsSelfLocked) {
18548                 proc = mPidsSelfLocked.get(pid);
18549             }
18550         } catch (NumberFormatException e) {
18551         }
18552 
18553         if (proc == null) {
18554             ArrayMap<String, SparseArray<ProcessRecord>> all
18555                     = mProcessList.mProcessNames.getMap();
18556             SparseArray<ProcessRecord> procs = all.get(process);
18557             if (procs != null && procs.size() > 0) {
18558                 proc = procs.valueAt(0);
18559                 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
18560                     for (int i=1; i<procs.size(); i++) {
18561                         ProcessRecord thisProc = procs.valueAt(i);
18562                         if (thisProc.userId == userId) {
18563                             proc = thisProc;
18564                             break;
18565                         }
18566                     }
18567                 }
18568             }
18569         }
18570 
18571         return proc;
18572     }
18573 
18574     @Override
dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)18575     public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo,
18576             boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) {
18577 
18578         try {
18579             synchronized (this) {
18580                 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
18581                 // its own permission (same as profileControl).
18582                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
18583                         != PackageManager.PERMISSION_GRANTED) {
18584                     throw new SecurityException("Requires permission "
18585                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
18586                 }
18587 
18588                 if (fd == null) {
18589                     throw new IllegalArgumentException("null fd");
18590                 }
18591 
18592                 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
18593                 if (proc == null || proc.thread == null) {
18594                     throw new IllegalArgumentException("Unknown process: " + process);
18595                 }
18596 
18597                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
18598                 if (!isDebuggable) {
18599                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
18600                         throw new SecurityException("Process not debuggable: " + proc);
18601                     }
18602                 }
18603 
18604                 mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
18605 
18606                 final RemoteCallback intermediateCallback = new RemoteCallback(
18607                         new RemoteCallback.OnResultListener() {
18608                         @Override
18609                         public void onResult(Bundle result) {
18610                             finishCallback.sendResult(result);
18611                             mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
18612                         }
18613                     }, null);
18614 
18615                 proc.thread.dumpHeap(managed, mallocInfo, runGc, path, fd, intermediateCallback);
18616                 fd = null;
18617                 return true;
18618             }
18619         } catch (RemoteException e) {
18620             throw new IllegalStateException("Process disappeared");
18621         } finally {
18622             if (fd != null) {
18623                 try {
18624                     fd.close();
18625                 } catch (IOException e) {
18626                 }
18627             }
18628         }
18629     }
18630 
18631     @Override
setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)18632     public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize,
18633             String reportPackage) {
18634         if (processName != null) {
18635             enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
18636                     "setDumpHeapDebugLimit()");
18637         } else {
18638             synchronized (mPidsSelfLocked) {
18639                 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid());
18640                 if (proc == null) {
18641                     throw new SecurityException("No process found for calling pid "
18642                             + Binder.getCallingPid());
18643                 }
18644                 if (!Build.IS_DEBUGGABLE
18645                         && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
18646                     throw new SecurityException("Not running a debuggable build");
18647                 }
18648                 processName = proc.processName;
18649                 uid = proc.uid;
18650                 if (reportPackage != null && !proc.pkgList.containsKey(reportPackage)) {
18651                     throw new SecurityException("Package " + reportPackage + " is not running in "
18652                             + proc);
18653                 }
18654             }
18655         }
18656         synchronized (this) {
18657             if (maxMemSize > 0) {
18658                 mMemWatchProcesses.put(processName, uid, new Pair(maxMemSize, reportPackage));
18659             } else {
18660                 if (uid != 0) {
18661                     mMemWatchProcesses.remove(processName, uid);
18662                 } else {
18663                     mMemWatchProcesses.getMap().remove(processName);
18664                 }
18665             }
18666         }
18667     }
18668 
18669     @Override
dumpHeapFinished(String path)18670     public void dumpHeapFinished(String path) {
18671         synchronized (this) {
18672             if (Binder.getCallingPid() != mMemWatchDumpPid) {
18673                 Slog.w(TAG, "dumpHeapFinished: Calling pid " + Binder.getCallingPid()
18674                         + " does not match last pid " + mMemWatchDumpPid);
18675                 return;
18676             }
18677             if (mMemWatchDumpUri == null || !mMemWatchDumpUri.getPath().equals(path)) {
18678                 Slog.w(TAG, "dumpHeapFinished: Calling path " + path
18679                         + " does not match last path " + mMemWatchDumpUri);
18680                 return;
18681             }
18682             if (DEBUG_PSS) Slog.d(TAG_PSS, "Dump heap finished for " + path);
18683             mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG);
18684 
18685             // Forced gc to clean up the remnant hprof fd.
18686             Runtime.getRuntime().gc();
18687         }
18688     }
18689 
18690     /** Clear the currently executing heap dump variables so a new heap dump can be started. */
abortHeapDump(String procName)18691     private void abortHeapDump(String procName) {
18692         Message msg = mHandler.obtainMessage(ABORT_DUMPHEAP_MSG);
18693         msg.obj = procName;
18694         mHandler.sendMessage(msg);
18695     }
18696 
18697     /** In this method we try to acquire our lock to make sure that we have not deadlocked */
monitor()18698     public void monitor() {
18699         synchronized (this) { }
18700     }
18701 
onCoreSettingsChange(Bundle settings)18702     void onCoreSettingsChange(Bundle settings) {
18703         synchronized (this) {
18704             mProcessList.updateCoreSettingsLocked(settings);
18705         }
18706     }
18707 
18708     // Multi-user methods
18709 
18710     /**
18711      * Start user, if its not already running, but don't bring it to foreground.
18712      */
18713     @Override
startUserInBackground(final int userId)18714     public boolean startUserInBackground(final int userId) {
18715         return startUserInBackgroundWithListener(userId, null);
18716     }
18717 
18718     @Override
startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)18719     public boolean startUserInBackgroundWithListener(final int userId,
18720                 @Nullable IProgressListener unlockListener) {
18721         return mUserController.startUser(userId, /* foreground */ false, unlockListener);
18722     }
18723 
18724     @Override
startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)18725     public boolean startUserInForegroundWithListener(final int userId,
18726             @Nullable IProgressListener unlockListener) {
18727         // Permission check done inside UserController.
18728         return mUserController.startUser(userId, /* foreground */ true, unlockListener);
18729     }
18730 
18731     @Override
unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener)18732     public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) {
18733         return mUserController.unlockUser(userId, token, secret, listener);
18734     }
18735 
18736     @Override
switchUser(final int targetUserId)18737     public boolean switchUser(final int targetUserId) {
18738         return mUserController.switchUser(targetUserId);
18739     }
18740 
18741     @Override
stopUser(final int userId, boolean force, final IStopUserCallback callback)18742     public int stopUser(final int userId, boolean force, final IStopUserCallback callback) {
18743         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ false,
18744                 /* callback= */ callback, /* keyEvictedCallback= */ null);
18745     }
18746 
18747     /**
18748      * Stops user but allow delayed locking. Delayed locking keeps user unlocked even after
18749      * stopping only if {@code config_multiuserDelayUserDataLocking} overlay is set true.
18750      *
18751      * <p>When delayed locking is not enabled through the overlay, this call becomes the same
18752      * with {@link #stopUser(int, boolean, IStopUserCallback)} call.
18753      *
18754      * @param userId User id to stop.
18755      * @param force Force stop the user even if the user is related with system user or current
18756      *              user.
18757      * @param callback Callback called when user has stopped.
18758      *
18759      * @return {@link ActivityManager#USER_OP_SUCCESS} when user is stopped successfully. Returns
18760      *         other {@code ActivityManager#USER_OP_*} codes for failure.
18761      *
18762      */
18763     @Override
stopUserWithDelayedLocking(final int userId, boolean force, final IStopUserCallback callback)18764     public int stopUserWithDelayedLocking(final int userId, boolean force,
18765             final IStopUserCallback callback) {
18766         return mUserController.stopUser(userId, force, /* allowDelayedLocking= */ true,
18767                 /* callback= */ callback, /* keyEvictedCallback= */ null);
18768     }
18769 
18770     @Override
getCurrentUser()18771     public UserInfo getCurrentUser() {
18772         return mUserController.getCurrentUser();
18773     }
18774 
getStartedUserState(int userId)18775     String getStartedUserState(int userId) {
18776         final UserState userState = mUserController.getStartedUserState(userId);
18777         return UserState.stateToString(userState.state);
18778     }
18779 
18780     @Override
isUserRunning(int userId, int flags)18781     public boolean isUserRunning(int userId, int flags) {
18782         if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId())
18783                 && checkCallingPermission(INTERACT_ACROSS_USERS)
18784                     != PackageManager.PERMISSION_GRANTED) {
18785             String msg = "Permission Denial: isUserRunning() from pid="
18786                     + Binder.getCallingPid()
18787                     + ", uid=" + Binder.getCallingUid()
18788                     + " requires " + INTERACT_ACROSS_USERS;
18789             Slog.w(TAG, msg);
18790             throw new SecurityException(msg);
18791         }
18792         return mUserController.isUserRunning(userId, flags);
18793     }
18794 
18795     @Override
getRunningUserIds()18796     public int[] getRunningUserIds() {
18797         if (checkCallingPermission(INTERACT_ACROSS_USERS)
18798                 != PackageManager.PERMISSION_GRANTED) {
18799             String msg = "Permission Denial: isUserRunning() from pid="
18800                     + Binder.getCallingPid()
18801                     + ", uid=" + Binder.getCallingUid()
18802                     + " requires " + INTERACT_ACROSS_USERS;
18803             Slog.w(TAG, msg);
18804             throw new SecurityException(msg);
18805         }
18806         return mUserController.getStartedUserArray();
18807     }
18808 
18809     @Override
registerUserSwitchObserver(IUserSwitchObserver observer, String name)18810     public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
18811         mUserController.registerUserSwitchObserver(observer, name);
18812     }
18813 
18814     @Override
unregisterUserSwitchObserver(IUserSwitchObserver observer)18815     public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
18816         mUserController.unregisterUserSwitchObserver(observer);
18817     }
18818 
getAppInfoForUser(ApplicationInfo info, int userId)18819     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
18820         if (info == null) return null;
18821         ApplicationInfo newInfo = new ApplicationInfo(info);
18822         newInfo.initForUser(userId);
18823         return newInfo;
18824     }
18825 
isUserStopped(int userId)18826     public boolean isUserStopped(int userId) {
18827         return mUserController.getStartedUserState(userId) == null;
18828     }
18829 
getActivityInfoForUser(ActivityInfo aInfo, int userId)18830     ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
18831         if (aInfo == null
18832                 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
18833             return aInfo;
18834         }
18835 
18836         ActivityInfo info = new ActivityInfo(aInfo);
18837         info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
18838         return info;
18839     }
18840 
processSanityChecksLocked(ProcessRecord process)18841     private boolean processSanityChecksLocked(ProcessRecord process) {
18842         if (process == null || process.thread == null) {
18843             return false;
18844         }
18845 
18846         boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
18847         if (!isDebuggable) {
18848             if ((process.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
18849                 return false;
18850             }
18851         }
18852 
18853         return true;
18854     }
18855 
startBinderTracking()18856     public boolean startBinderTracking() throws RemoteException {
18857         synchronized (this) {
18858             mBinderTransactionTrackingEnabled = true;
18859             // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
18860             // permission (same as profileControl).
18861             if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
18862                     != PackageManager.PERMISSION_GRANTED) {
18863                 throw new SecurityException("Requires permission "
18864                         + android.Manifest.permission.SET_ACTIVITY_WATCHER);
18865             }
18866 
18867             for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
18868                 ProcessRecord process = mProcessList.mLruProcesses.get(i);
18869                 if (!processSanityChecksLocked(process)) {
18870                     continue;
18871                 }
18872                 try {
18873                     process.thread.startBinderTracking();
18874                 } catch (RemoteException e) {
18875                     Log.v(TAG, "Process disappared");
18876                 }
18877             }
18878             return true;
18879         }
18880     }
18881 
stopBinderTrackingAndDump(ParcelFileDescriptor fd)18882     public boolean stopBinderTrackingAndDump(ParcelFileDescriptor fd) throws RemoteException {
18883         try {
18884             synchronized (this) {
18885                 mBinderTransactionTrackingEnabled = false;
18886                 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
18887                 // permission (same as profileControl).
18888                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
18889                         != PackageManager.PERMISSION_GRANTED) {
18890                     throw new SecurityException("Requires permission "
18891                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
18892                 }
18893 
18894                 if (fd == null) {
18895                     throw new IllegalArgumentException("null fd");
18896                 }
18897 
18898                 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor()));
18899                 pw.println("Binder transaction traces for all processes.\n");
18900                 for (ProcessRecord process : mProcessList.mLruProcesses) {
18901                     if (!processSanityChecksLocked(process)) {
18902                         continue;
18903                     }
18904 
18905                     pw.println("Traces for process: " + process.processName);
18906                     pw.flush();
18907                     try {
18908                         TransferPipe tp = new TransferPipe();
18909                         try {
18910                             process.thread.stopBinderTrackingAndDump(tp.getWriteFd());
18911                             tp.go(fd.getFileDescriptor());
18912                         } finally {
18913                             tp.kill();
18914                         }
18915                     } catch (IOException e) {
18916                         pw.println("Failure while dumping IPC traces from " + process +
18917                                 ".  Exception: " + e);
18918                         pw.flush();
18919                     } catch (RemoteException e) {
18920                         pw.println("Got a RemoteException while dumping IPC traces from " +
18921                                 process + ".  Exception: " + e);
18922                         pw.flush();
18923                     }
18924                 }
18925                 fd = null;
18926                 return true;
18927             }
18928         } finally {
18929             if (fd != null) {
18930                 try {
18931                     fd.close();
18932                 } catch (IOException e) {
18933                 }
18934             }
18935         }
18936     }
18937 
18938     @VisibleForTesting
18939     public final class LocalService extends ActivityManagerInternal {
18940         @Override
checkContentProviderAccess(String authority, int userId)18941         public String checkContentProviderAccess(String authority, int userId) {
18942             return ActivityManagerService.this.checkContentProviderAccess(authority, userId);
18943         }
18944 
18945         @Override
checkContentProviderUriPermission(Uri uri, int userId, int callingUid, int modeFlags)18946         public int checkContentProviderUriPermission(Uri uri, int userId,
18947                 int callingUid, int modeFlags) {
18948             return ActivityManagerService.this.checkContentProviderUriPermission(uri,
18949                     userId, callingUid, modeFlags);
18950         }
18951 
18952         @Override
onWakefulnessChanged(int wakefulness)18953         public void onWakefulnessChanged(int wakefulness) {
18954             ActivityManagerService.this.onWakefulnessChanged(wakefulness);
18955         }
18956 
18957         @Override
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)18958         public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
18959                 String processName, String abiOverride, int uid, Runnable crashHandler) {
18960             return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
18961                     processName, abiOverride, uid, crashHandler);
18962         }
18963 
18964         @Override
onUserRemoved(@serIdInt int userId)18965         public void onUserRemoved(@UserIdInt int userId) {
18966             // Clean up any ActivityTaskManager state (by telling it the user is stopped)
18967             mAtmInternal.onUserStopped(userId);
18968             // Clean up various services by removing the user
18969             mBatteryStatsService.onUserRemoved(userId);
18970             mUserController.onUserRemoved(userId);
18971         }
18972 
18973         @Override
killForegroundAppsForUser(@serIdInt int userId)18974         public void killForegroundAppsForUser(@UserIdInt int userId) {
18975             synchronized (ActivityManagerService.this) {
18976                 final ArrayList<ProcessRecord> procs = new ArrayList<>();
18977                 final int NP = mProcessList.mProcessNames.getMap().size();
18978                 for (int ip = 0; ip < NP; ip++) {
18979                     final SparseArray<ProcessRecord> apps =
18980                             mProcessList.mProcessNames.getMap().valueAt(ip);
18981                     final int NA = apps.size();
18982                     for (int ia = 0; ia < NA; ia++) {
18983                         final ProcessRecord app = apps.valueAt(ia);
18984                         if (app.isPersistent()) {
18985                             // We don't kill persistent processes.
18986                             continue;
18987                         }
18988                         if (app.removed
18989                                 || (app.userId == userId && app.hasForegroundActivities())) {
18990                             procs.add(app);
18991                         }
18992                     }
18993                 }
18994 
18995                 final int N = procs.size();
18996                 for (int i = 0; i < N; i++) {
18997                     mProcessList.removeProcessLocked(procs.get(i), false, true,
18998                             ApplicationExitInfo.REASON_OTHER,
18999                             ApplicationExitInfo.SUBREASON_KILL_ALL_FG,
19000                             "kill all fg");
19001                 }
19002             }
19003         }
19004 
19005         @Override
setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken, long duration)19006         public void setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken,
19007                 long duration) {
19008             mPendingIntentController.setPendingIntentWhitelistDuration(target, whitelistToken,
19009                     duration);
19010         }
19011 
19012         @Override
setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken, int flags)19013         public void setPendingIntentAllowBgActivityStarts(IIntentSender target,
19014                 IBinder whitelistToken, int flags) {
19015             if (!(target instanceof PendingIntentRecord)) {
19016                 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():"
19017                         + " not a PendingIntentRecord: " + target);
19018                 return;
19019             }
19020             synchronized (ActivityManagerService.this) {
19021                 ((PendingIntentRecord) target).setAllowBgActivityStarts(whitelistToken, flags);
19022             }
19023         }
19024 
19025         @Override
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken)19026         public void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
19027                 IBinder whitelistToken) {
19028             if (!(target instanceof PendingIntentRecord)) {
19029                 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():"
19030                         + " not a PendingIntentRecord: " + target);
19031                 return;
19032             }
19033             synchronized (ActivityManagerService.this) {
19034                 ((PendingIntentRecord) target).clearAllowBgActivityStarts(whitelistToken);
19035             }
19036         }
19037 
19038         @Override
setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids)19039         public void setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids) {
19040             synchronized (ActivityManagerService.this) {
19041                 mDeviceIdleWhitelist = allAppids;
19042                 mDeviceIdleExceptIdleWhitelist = exceptIdleAppids;
19043             }
19044         }
19045 
19046         @Override
updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding)19047         public void updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding) {
19048             synchronized (ActivityManagerService.this) {
19049                 mDeviceIdleTempWhitelist = appids;
19050                 setAppIdTempWhitelistStateLocked(changingAppId, adding);
19051             }
19052         }
19053 
19054         @Override
getUidProcessState(int uid)19055         public int getUidProcessState(int uid) {
19056             return getUidState(uid);
19057         }
19058 
19059         @Override
getProcessesWithPendingBindMounts(int userId)19060         public Map<Integer, String> getProcessesWithPendingBindMounts(int userId) {
19061             return mProcessList.getProcessesWithPendingBindMounts(userId);
19062         }
19063 
19064         @Override
isSystemReady()19065         public boolean isSystemReady() {
19066             // no need to synchronize(this) just to read & return the value
19067             return mSystemReady;
19068         }
19069 
19070         /**
19071          * Sets if the given pid has an overlay UI or not.
19072          *
19073          * @param pid The pid we are setting overlay UI for.
19074          * @param hasOverlayUi True if the process has overlay UI.
19075          * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
19076          */
19077         @Override
setHasOverlayUi(int pid, boolean hasOverlayUi)19078         public void setHasOverlayUi(int pid, boolean hasOverlayUi) {
19079             synchronized (ActivityManagerService.this) {
19080                 final ProcessRecord pr;
19081                 synchronized (mPidsSelfLocked) {
19082                     pr = mPidsSelfLocked.get(pid);
19083                     if (pr == null) {
19084                         Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid);
19085                         return;
19086                     }
19087                 }
19088                 if (pr.hasOverlayUi() == hasOverlayUi) {
19089                     return;
19090                 }
19091                 pr.setHasOverlayUi(hasOverlayUi);
19092                 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid);
19093                 updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
19094             }
19095         }
19096 
19097         /**
19098          * Called after the network policy rules are updated by
19099          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
19100          * and {@param procStateSeq}.
19101          */
19102         @Override
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)19103         public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
19104             if (DEBUG_NETWORK) {
19105                 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: "
19106                         + uid + " seq: " + procStateSeq);
19107             }
19108             UidRecord record;
19109             synchronized (ActivityManagerService.this) {
19110                 record = mProcessList.getUidRecordLocked(uid);
19111                 if (record == null) {
19112                     if (DEBUG_NETWORK) {
19113                         Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
19114                                 + " procStateSeq: " + procStateSeq);
19115                     }
19116                     return;
19117                 }
19118             }
19119             synchronized (record.networkStateLock) {
19120                 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
19121                     if (DEBUG_NETWORK) {
19122                         Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already"
19123                                 + " been handled for uid: " + uid);
19124                     }
19125                     return;
19126                 }
19127                 record.lastNetworkUpdatedProcStateSeq = procStateSeq;
19128                 if (record.curProcStateSeq > procStateSeq) {
19129                     if (DEBUG_NETWORK) {
19130                         Slog.d(TAG_NETWORK, "No need to handle older seq no., Uid: " + uid
19131                                 + ", curProcstateSeq: " + record.curProcStateSeq
19132                                 + ", procStateSeq: " + procStateSeq);
19133                     }
19134                     return;
19135                 }
19136                 if (record.waitingForNetwork) {
19137                     if (DEBUG_NETWORK) {
19138                         Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid
19139                                 + ", procStateSeq: " + procStateSeq);
19140                     }
19141                     record.networkStateLock.notifyAll();
19142                 }
19143             }
19144         }
19145 
19146         @Override
isRuntimeRestarted()19147         public boolean isRuntimeRestarted() {
19148             return mSystemServiceManager.isRuntimeRestarted();
19149         }
19150 
19151         @Override
canStartMoreUsers()19152         public boolean canStartMoreUsers() {
19153             return mUserController.canStartMoreUsers();
19154         }
19155 
19156         @Override
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)19157         public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
19158             mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage);
19159         }
19160 
19161         @Override
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)19162         public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
19163             mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage);
19164         }
19165 
19166         @Override
getMaxRunningUsers()19167         public int getMaxRunningUsers() {
19168             return mUserController.getMaxRunningUsers();
19169         }
19170 
19171         @Override
isUidActive(int uid)19172         public boolean isUidActive(int uid) {
19173             synchronized (ActivityManagerService.this) {
19174                 return isUidActiveLocked(uid);
19175             }
19176         }
19177 
19178         @Override
getMemoryStateForProcesses()19179         public List<ProcessMemoryState> getMemoryStateForProcesses() {
19180             List<ProcessMemoryState> processMemoryStates = new ArrayList<>();
19181             synchronized (mPidsSelfLocked) {
19182                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
19183                     final ProcessRecord r = mPidsSelfLocked.valueAt(i);
19184                     processMemoryStates.add(
19185                             new ProcessMemoryState(r.uid, r.pid, r.processName, r.curAdj));
19186                 }
19187             }
19188             return processMemoryStates;
19189         }
19190 
19191         @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)19192         public int handleIncomingUser(int callingPid, int callingUid, int userId,
19193                 boolean allowAll, int allowMode, String name, String callerPackage) {
19194             return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
19195                     allowMode, name, callerPackage);
19196         }
19197 
19198         @Override
enforceCallingPermission(String permission, String func)19199         public void enforceCallingPermission(String permission, String func) {
19200             ActivityManagerService.this.enforceCallingPermission(permission, func);
19201         }
19202 
19203         @Override
getCurrentUserId()19204         public int getCurrentUserId() {
19205             return mUserController.getCurrentUserId();
19206         }
19207 
19208         @Override
isUserRunning(int userId, int flags)19209         public boolean isUserRunning(int userId, int flags) {
19210             // Holding am lock isn't required to call into user controller.
19211             return mUserController.isUserRunning(userId, flags);
19212         }
19213 
19214         @Override
trimApplications()19215         public void trimApplications() {
19216             ActivityManagerService.this.trimApplications(OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
19217         }
19218 
killProcessesForRemovedTask(ArrayList<Object> procsToKill)19219         public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) {
19220             synchronized (ActivityManagerService.this) {
19221                 for (int i = 0; i < procsToKill.size(); i++) {
19222                     final WindowProcessController wpc =
19223                             (WindowProcessController) procsToKill.get(i);
19224                     final ProcessRecord pr = (ProcessRecord) wpc.mOwner;
19225                     if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
19226                             && pr.curReceivers.isEmpty()) {
19227                         pr.kill("remove task", ApplicationExitInfo.REASON_USER_REQUESTED,
19228                                 ApplicationExitInfo.SUBREASON_UNKNOWN, true);
19229                     } else {
19230                         // We delay killing processes that are not in the background or running a
19231                         // receiver.
19232                         pr.waitingToKill = "remove task";
19233                     }
19234                 }
19235             }
19236         }
19237 
19238         @Override
killProcess(String processName, int uid, String reason)19239         public void killProcess(String processName, int uid, String reason) {
19240             synchronized (ActivityManagerService.this) {
19241                 final ProcessRecord proc = getProcessRecordLocked(processName, uid,
19242                         true /* keepIfLarge */);
19243                 if (proc != null) {
19244                     mProcessList.removeProcessLocked(proc, false /* callerWillRestart */,
19245                             true /* allowRestart */,  ApplicationExitInfo.REASON_OTHER, reason);
19246                 }
19247             }
19248         }
19249 
19250         @Override
hasRunningActivity(int uid, @Nullable String packageName)19251         public boolean hasRunningActivity(int uid, @Nullable String packageName) {
19252             if (packageName == null) return false;
19253 
19254             synchronized (ActivityManagerService.this) {
19255                 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
19256                     final ProcessRecord pr = mProcessList.mLruProcesses.get(i);
19257                     if (pr.uid != uid) {
19258                         continue;
19259                     }
19260                     if (pr.getWindowProcessController().hasRunningActivity(packageName)) {
19261                         return true;
19262                     }
19263                 }
19264             }
19265             return false;
19266         }
19267 
19268         @Override
updateOomAdj()19269         public void updateOomAdj() {
19270             synchronized (ActivityManagerService.this) {
19271                 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
19272             }
19273         }
19274 
19275         @Override
updateCpuStats()19276         public void updateCpuStats() {
19277             synchronized (ActivityManagerService.this) {
19278                 ActivityManagerService.this.updateCpuStats();
19279             }
19280         }
19281 
19282         @Override
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)19283         public void updateBatteryStats(ComponentName activity, int uid, int userId,
19284                 boolean resumed) {
19285             synchronized (ActivityManagerService.this) {
19286                 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed);
19287             }
19288         }
19289 
19290         @Override
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)19291         public void updateActivityUsageStats(ComponentName activity, int userId, int event,
19292                 IBinder appToken, ComponentName taskRoot) {
19293             synchronized (ActivityManagerService.this) {
19294                 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event,
19295                         appToken, taskRoot);
19296             }
19297         }
19298 
19299         @Override
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)19300         public void updateForegroundTimeIfOnBattery(
19301                 String packageName, int uid, long cpuTimeDiff) {
19302             synchronized (ActivityManagerService.this) {
19303                 if (!mBatteryStatsService.isOnBattery()) {
19304                     return;
19305                 }
19306                 final BatteryStatsImpl bsi = mBatteryStatsService.getActiveStatistics();
19307                 synchronized (bsi) {
19308                     final BatteryStatsImpl.Uid.Proc ps =
19309                             bsi.getProcessStatsLocked(uid, packageName);
19310                     if (ps != null) {
19311                         ps.addForegroundTimeLocked(cpuTimeDiff);
19312                     }
19313                 }
19314             }
19315         }
19316 
19317         @Override
sendForegroundProfileChanged(int userId)19318         public void sendForegroundProfileChanged(int userId) {
19319             mUserController.sendForegroundProfileChanged(userId);
19320         }
19321 
19322         @Override
shouldConfirmCredentials(int userId)19323         public boolean shouldConfirmCredentials(int userId) {
19324             return mUserController.shouldConfirmCredentials(userId);
19325         }
19326 
19327         @Override
getCurrentProfileIds()19328         public int[] getCurrentProfileIds() {
19329             return mUserController.getCurrentProfileIds();
19330         }
19331 
19332         @Override
getCurrentUser()19333         public UserInfo getCurrentUser() {
19334             return mUserController.getCurrentUser();
19335         }
19336 
19337         @Override
ensureNotSpecialUser(int userId)19338         public void ensureNotSpecialUser(int userId) {
19339             mUserController.ensureNotSpecialUser(userId);
19340         }
19341 
19342         @Override
isCurrentProfile(int userId)19343         public boolean isCurrentProfile(int userId) {
19344             return mUserController.isCurrentProfile(userId);
19345         }
19346 
19347         @Override
hasStartedUserState(int userId)19348         public boolean hasStartedUserState(int userId) {
19349             return mUserController.hasStartedUserState(userId);
19350         }
19351 
19352         @Override
finishUserSwitch(Object uss)19353         public void finishUserSwitch(Object uss) {
19354             mUserController.finishUserSwitch((UserState) uss);
19355         }
19356 
19357         @Override
scheduleAppGcs()19358         public void scheduleAppGcs() {
19359             synchronized (ActivityManagerService.this) {
19360                 ActivityManagerService.this.scheduleAppGcsLocked();
19361             }
19362         }
19363 
19364         @Override
getTaskIdForActivity(IBinder token, boolean onlyRoot)19365         public int getTaskIdForActivity(IBinder token, boolean onlyRoot) {
19366             synchronized (ActivityManagerService.this) {
19367                 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot);
19368             }
19369         }
19370 
19371         @Override
getActivityPresentationInfo(IBinder token)19372         public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
19373             int displayId = Display.INVALID_DISPLAY;
19374             try {
19375                 displayId = mActivityTaskManager.getDisplayId(token);
19376             } catch (RemoteException e) {
19377             }
19378 
19379             return new ActivityPresentationInfo(mActivityTaskManager.getTaskForActivity(token,
19380                     /*onlyRoot=*/ false), displayId,
19381                     mActivityTaskManager.getActivityClassForToken(token));
19382         }
19383 
19384         @Override
setBooting(boolean booting)19385         public void setBooting(boolean booting) {
19386             mBooting = booting;
19387         }
19388 
19389         @Override
isBooting()19390         public boolean isBooting() {
19391             return mBooting;
19392         }
19393 
19394         @Override
setBooted(boolean booted)19395         public void setBooted(boolean booted) {
19396             mBooted = booted;
19397         }
19398 
19399         @Override
isBooted()19400         public boolean isBooted() {
19401             return mBooted;
19402         }
19403 
19404         @Override
finishBooting()19405         public void finishBooting() {
19406             ActivityManagerService.this.finishBooting();
19407         }
19408 
19409         @Override
tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, String tag)19410         public void tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid,
19411                 long duration, String tag) {
19412             synchronized (ActivityManagerService.this) {
19413                 ActivityManagerService.this.tempWhitelistForPendingIntentLocked(
19414                         callerPid, callerUid, targetUid, duration, tag);
19415             }
19416         }
19417 
19418         @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)19419         public int broadcastIntentInPackage(String packageName, @Nullable String featureId, int uid,
19420                 int realCallingUid, int realCallingPid, Intent intent, String resolvedType,
19421                 IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras,
19422                 String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky,
19423                 int userId, boolean allowBackgroundActivityStarts) {
19424             synchronized (ActivityManagerService.this) {
19425                 return ActivityManagerService.this.broadcastIntentInPackage(packageName, featureId,
19426                         uid, realCallingUid, realCallingPid, intent, resolvedType, resultTo,
19427                         resultCode, resultData, resultExtras, requiredPermission, bOptions,
19428                         serialized, sticky, userId, allowBackgroundActivityStarts);
19429             }
19430         }
19431 
19432         @Override
broadcastIntent(Intent intent, IIntentReceiver resultTo, String[] requiredPermissions, boolean serialized, int userId, int[] appIdWhitelist)19433         public int broadcastIntent(Intent intent,
19434                 IIntentReceiver resultTo,
19435                 String[] requiredPermissions,
19436                 boolean serialized, int userId, int[] appIdWhitelist) {
19437             synchronized (ActivityManagerService.this) {
19438                 intent = verifyBroadcastLocked(intent);
19439 
19440                 final int callingPid = Binder.getCallingPid();
19441                 final int callingUid = Binder.getCallingUid();
19442                 final long origId = Binder.clearCallingIdentity();
19443                 try {
19444                     return ActivityManagerService.this.broadcastIntentLocked(null /*callerApp*/,
19445                             null /*callerPackage*/, null /*callingFeatureId*/, intent,
19446                             null /*resolvedType*/, resultTo, 0 /*resultCode*/, null /*resultData*/,
19447                             null /*resultExtras*/, requiredPermissions, AppOpsManager.OP_NONE,
19448                             null /*options*/, serialized, false /*sticky*/, callingPid, callingUid,
19449                             callingUid, callingPid, userId, false /*allowBackgroundStarts*/,
19450                             appIdWhitelist);
19451                 } finally {
19452                     Binder.restoreCallingIdentity(origId);
19453                 }
19454             }
19455 
19456         }
19457 
19458         @Override
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, int userId, boolean allowBackgroundActivityStarts)19459         public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType,
19460                 boolean fgRequired, String callingPackage, @Nullable String callingFeatureId,
19461                 int userId, boolean allowBackgroundActivityStarts)
19462                 throws TransactionTooLargeException {
19463             synchronized(ActivityManagerService.this) {
19464                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
19465                         "startServiceInPackage: " + service + " type=" + resolvedType);
19466                 final long origId = Binder.clearCallingIdentity();
19467                 ComponentName res;
19468                 try {
19469                     res = mServices.startServiceLocked(null, service,
19470                             resolvedType, -1, uid, fgRequired, callingPackage,
19471                             callingFeatureId, userId, allowBackgroundActivityStarts);
19472                 } finally {
19473                     Binder.restoreCallingIdentity(origId);
19474                 }
19475                 return res;
19476             }
19477         }
19478 
19479         // The arguments here are untyped because the base ActivityManagerInternal class
19480         // doesn't have compile-time visibility into ActivityServiceConnectionHolder or
19481         // ConnectionRecord.
19482         @Override
disconnectActivityFromServices(Object connectionHolder)19483         public void disconnectActivityFromServices(Object connectionHolder) {
19484             // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder
19485             final ActivityServiceConnectionsHolder holder =
19486                     (ActivityServiceConnectionsHolder) connectionHolder;
19487             synchronized (ActivityManagerService.this) {
19488                 holder.forEachConnection(cr -> mServices.removeConnectionLocked(
19489                         (ConnectionRecord) cr, null /* skipApp */, holder /* skipAct */));
19490             }
19491         }
19492 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)19493         public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
19494             synchronized(ActivityManagerService.this) {
19495                 mServices.cleanUpServices(userId, component, baseIntent);
19496             }
19497         }
19498 
getActivityInfoForUser(ActivityInfo aInfo, int userId)19499         public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
19500             // Locked intentionally not held as it isn't needed for this case.
19501             return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId);
19502         }
19503 
ensureBootCompleted()19504         public void ensureBootCompleted() {
19505             // Locked intentionally not held as it isn't needed for this case.
19506             ActivityManagerService.this.ensureBootCompleted();
19507         }
19508 
updateOomLevelsForDisplay(int displayId)19509         public void updateOomLevelsForDisplay(int displayId) {
19510             synchronized(ActivityManagerService.this) {
19511                 if (mWindowManager != null) {
19512                     mProcessList.applyDisplaySize(mWindowManager);
19513                 }
19514             }
19515         }
19516 
isActivityStartsLoggingEnabled()19517         public boolean isActivityStartsLoggingEnabled() {
19518             return mConstants.mFlagActivityStartsLoggingEnabled;
19519         }
19520 
isBackgroundActivityStartsEnabled()19521         public boolean isBackgroundActivityStartsEnabled() {
19522             return mConstants.mFlagBackgroundActivityStartsEnabled;
19523         }
19524 
reportCurKeyguardUsageEvent(boolean keyguardShowing)19525         public void reportCurKeyguardUsageEvent(boolean keyguardShowing) {
19526             synchronized(ActivityManagerService.this) {
19527                 ActivityManagerService.this.reportGlobalUsageEventLocked(keyguardShowing
19528                         ? UsageEvents.Event.KEYGUARD_SHOWN
19529                         : UsageEvents.Event.KEYGUARD_HIDDEN);
19530             }
19531         }
19532 
19533         @Override
monitor()19534         public void monitor() {
19535             ActivityManagerService.this.monitor();
19536         }
19537 
19538         @Override
inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)19539         public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) {
19540             return ActivityManagerService.this.inputDispatchingTimedOut(pid, aboveSystem, reason);
19541         }
19542 
19543         @Override
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)19544         public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
19545                 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
19546                 boolean aboveSystem, String reason) {
19547             return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc,
19548                     activityShortComponentName, aInfo, parentShortComponentName,
19549                     (WindowProcessController) parentProc, aboveSystem, reason);
19550 
19551         }
19552 
19553         @Override
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)19554         public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) {
19555             synchronized (ActivityManagerService.this) {
19556                 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
19557                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
19558                         | Intent.FLAG_RECEIVER_REPLACE_PENDING
19559                         | Intent.FLAG_RECEIVER_FOREGROUND
19560                         | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
19561                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
19562                         OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
19563                         Binder.getCallingPid(), UserHandle.USER_ALL);
19564                 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
19565                     intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
19566                     intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
19567                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
19568                             | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
19569                     if (initLocale || !mProcessesReady) {
19570                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
19571                     }
19572                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
19573                             OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
19574                             Binder.getCallingPid(), UserHandle.USER_ALL);
19575                 }
19576 
19577                 // Send a broadcast to PackageInstallers if the configuration change is interesting
19578                 // for the purposes of installing additional splits.
19579                 if (!initLocale && isSplitConfigurationChange(changes)) {
19580                     intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
19581                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
19582                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
19583 
19584                     // Typically only app stores will have this permission.
19585                     String[] permissions =
19586                             new String[] { android.Manifest.permission.INSTALL_PACKAGES };
19587                     broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null,
19588                             permissions, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
19589                             Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
19590                 }
19591             }
19592         }
19593 
19594         /**
19595          * Returns true if this configuration change is interesting enough to send an
19596          * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
19597          */
isSplitConfigurationChange(int configDiff)19598         private boolean isSplitConfigurationChange(int configDiff) {
19599             return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
19600         }
19601 
19602         @Override
broadcastCloseSystemDialogs(String reason)19603         public void broadcastCloseSystemDialogs(String reason) {
19604             synchronized (ActivityManagerService.this) {
19605                 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
19606                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
19607                         | Intent.FLAG_RECEIVER_FOREGROUND);
19608                 if (reason != null) {
19609                     intent.putExtra("reason", reason);
19610                 }
19611 
19612                 broadcastIntentLocked(null, null, null, intent, null, null, 0, null, null, null,
19613                         OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
19614                         Binder.getCallingPid(), UserHandle.USER_ALL);
19615             }
19616         }
19617 
19618         @Override
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)19619         public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
19620             synchronized (ActivityManagerService.this) {
19621                 ActivityManagerService.this.killAllBackgroundProcessesExcept(
19622                         minTargetSdk, maxProcState);
19623             }
19624         }
19625 
19626         @Override
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)19627         public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
19628                 boolean isTop, String hostingType, ComponentName hostingName) {
19629             try {
19630                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
19631                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
19632                             + processName);
19633                 }
19634                 synchronized (ActivityManagerService.this) {
19635                     // If the process is known as top app, set a hint so when the process is
19636                     // started, the top priority can be applied immediately to avoid cpu being
19637                     // preempted by other processes before attaching the process of top app.
19638                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
19639                             new HostingRecord(hostingType, hostingName, isTop),
19640                             ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
19641                             false /* isolated */, true /* keepIfLarge */);
19642                 }
19643             } finally {
19644                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
19645             }
19646         }
19647 
19648         @Override
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)19649         public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
19650                 ProfilerInfo profilerInfo, Object wmLock) {
19651             synchronized (ActivityManagerService.this) {
19652                 /**
19653                  * This function is called from the window manager context and needs to be executed
19654                  * synchronously.  To avoid deadlock, we pass a message to AMS to execute the
19655                  * function and notify the passed in lock when it has been completed.
19656                  */
19657                 synchronized (wmLock) {
19658                     if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
19659                         setDebugApp(aInfo.processName, true, false);
19660                     }
19661 
19662                     if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
19663                         setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
19664                     }
19665 
19666                     if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
19667                         setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
19668                     }
19669 
19670                     if (profilerInfo != null) {
19671                         setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
19672                     }
19673                     wmLock.notify();
19674                 }
19675             }
19676         }
19677 
19678         @Override
getStorageMountMode(int pid, int uid)19679         public int getStorageMountMode(int pid, int uid) {
19680             if (uid == SHELL_UID || uid == ROOT_UID) {
19681                 return Zygote.MOUNT_EXTERNAL_FULL;
19682             }
19683             synchronized (mPidsSelfLocked) {
19684                 final ProcessRecord pr = mPidsSelfLocked.get(pid);
19685                 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.mountMode;
19686             }
19687         }
19688 
19689         @Override
isAppForeground(int uid)19690         public boolean isAppForeground(int uid) {
19691             return ActivityManagerService.this.isAppForeground(uid);
19692         }
19693 
19694         @Override
isAppBad(ApplicationInfo info)19695         public boolean isAppBad(ApplicationInfo info) {
19696             return ActivityManagerService.this.isAppBad(info);
19697         }
19698 
19699         @Override
clearPendingBackup(int userId)19700         public void clearPendingBackup(int userId) {
19701             ActivityManagerService.this.clearPendingBackup(userId);
19702         }
19703 
19704         /**
19705          * When power button is very long pressed, call this interface to do some pre-shutdown work
19706          * like persisting database etc.
19707          */
19708         @Override
prepareForPossibleShutdown()19709         public void prepareForPossibleShutdown() {
19710             ActivityManagerService.this.prepareForPossibleShutdown();
19711         }
19712 
19713         @Override
hasRunningForegroundService(int uid, int foregroundServicetype)19714         public boolean hasRunningForegroundService(int uid, int foregroundServicetype) {
19715             synchronized (ActivityManagerService.this) {
19716                 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
19717                     final ProcessRecord pr = mProcessList.mLruProcesses.get(i);
19718                     if (pr.uid != uid) {
19719                         continue;
19720                     }
19721 
19722                     if ((pr.getForegroundServiceTypes() & foregroundServicetype) != 0) {
19723                         return true;
19724                     }
19725                 }
19726             }
19727 
19728             return false;
19729         }
19730 
19731         @Override
hasForegroundServiceNotification(String pkg, int userId, String channelId)19732         public boolean hasForegroundServiceNotification(String pkg, int userId,
19733                 String channelId) {
19734             synchronized (ActivityManagerService.this) {
19735                 return mServices.hasForegroundServiceNotificationLocked(pkg, userId, channelId);
19736             }
19737         }
19738 
19739         @Override
stopForegroundServicesForChannel(String pkg, int userId, String channelId)19740         public void stopForegroundServicesForChannel(String pkg, int userId,
19741                 String channelId) {
19742             synchronized (ActivityManagerService.this) {
19743                 mServices.stopForegroundServicesForChannelLocked(pkg, userId, channelId);
19744             }
19745         }
19746 
19747         @Override
registerProcessObserver(IProcessObserver processObserver)19748         public void registerProcessObserver(IProcessObserver processObserver) {
19749             ActivityManagerService.this.registerProcessObserver(processObserver);
19750         }
19751 
19752         @Override
unregisterProcessObserver(IProcessObserver processObserver)19753         public void unregisterProcessObserver(IProcessObserver processObserver) {
19754             ActivityManagerService.this.unregisterProcessObserver(processObserver);
19755         }
19756 
19757         @Override
isUidCurrentlyInstrumented(int uid)19758         public boolean isUidCurrentlyInstrumented(int uid) {
19759             synchronized (ActivityManagerService.this) {
19760                 for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) {
19761                     ActiveInstrumentation activeInst = mActiveInstrumentation.get(i);
19762                     if (!activeInst.mFinished && activeInst.mTargetInfo != null
19763                             && activeInst.mTargetInfo.uid == uid) {
19764                         return true;
19765                     }
19766                 }
19767             }
19768             return false;
19769         }
19770 
19771         @Override
setDeviceOwnerUid(int uid)19772         public void setDeviceOwnerUid(int uid) {
19773             synchronized (ActivityManagerService.this) {
19774                 mDeviceOwnerUid = uid;
19775             }
19776         }
19777 
19778         @Override
isDeviceOwner(int uid)19779         public boolean isDeviceOwner(int uid) {
19780             synchronized (ActivityManagerService.this) {
19781                 return uid >= 0 && mDeviceOwnerUid == uid;
19782             }
19783         }
19784 
19785         @Override
addPendingTopUid(int uid, int pid)19786         public void addPendingTopUid(int uid, int pid) {
19787                 mPendingStartActivityUids.add(uid, pid);
19788         }
19789 
19790         @Override
deletePendingTopUid(int uid)19791         public void deletePendingTopUid(int uid) {
19792             mPendingStartActivityUids.delete(uid);
19793         }
19794 
19795         @Override
isPendingTopUid(int uid)19796         public boolean isPendingTopUid(int uid) {
19797             return mPendingStartActivityUids.isPendingTopUid(uid);
19798         }
19799 
19800         @Override
tempAllowWhileInUsePermissionInFgs(int uid, long duration)19801         public void tempAllowWhileInUsePermissionInFgs(int uid, long duration) {
19802             mFgsWhileInUseTempAllowList.add(uid, duration);
19803         }
19804 
19805         @Override
isTempAllowlistedForFgsWhileInUse(int uid)19806         public boolean isTempAllowlistedForFgsWhileInUse(int uid) {
19807             return mFgsWhileInUseTempAllowList.isAllowed(uid);
19808         }
19809 
19810         @Override
canAllowWhileInUsePermissionInFgs(int pid, int uid, @NonNull String packageName)19811         public boolean canAllowWhileInUsePermissionInFgs(int pid, int uid,
19812                 @NonNull String packageName) {
19813             synchronized (ActivityManagerService.this) {
19814                 return mServices.canAllowWhileInUsePermissionInFgsLocked(pid, uid, packageName);
19815             }
19816         }
19817     }
19818 
inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason)19819     long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
19820         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
19821             throw new SecurityException("Requires permission " + FILTER_EVENTS);
19822         }
19823         ProcessRecord proc;
19824         long timeout;
19825         synchronized (this) {
19826             synchronized (mPidsSelfLocked) {
19827                 proc = mPidsSelfLocked.get(pid);
19828             }
19829             timeout = proc != null ? proc.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
19830         }
19831 
19832         if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) {
19833             return -1;
19834         }
19835 
19836         return timeout;
19837     }
19838 
19839     /**
19840      * Handle input dispatching timeouts.
19841      * @return whether input dispatching should be aborted or not.
19842      */
inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, WindowProcessController parentProcess, boolean aboveSystem, String reason)19843     boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName,
19844             ApplicationInfo aInfo, String parentShortComponentName,
19845             WindowProcessController parentProcess, boolean aboveSystem, String reason) {
19846         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
19847             throw new SecurityException("Requires permission " + FILTER_EVENTS);
19848         }
19849 
19850         final String annotation;
19851         if (reason == null) {
19852             annotation = "Input dispatching timed out";
19853         } else {
19854             annotation = "Input dispatching timed out (" + reason + ")";
19855         }
19856 
19857         if (proc != null) {
19858             synchronized (this) {
19859                 if (proc.isDebugging()) {
19860                     return false;
19861                 }
19862 
19863                 if (proc.getActiveInstrumentation() != null) {
19864                     Bundle info = new Bundle();
19865                     info.putString("shortMsg", "keyDispatchingTimedOut");
19866                     info.putString("longMsg", annotation);
19867                     finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
19868                     return true;
19869                 }
19870             }
19871             mAnrHelper.appNotResponding(proc, activityShortComponentName, aInfo,
19872                     parentShortComponentName, parentProcess, aboveSystem, annotation);
19873         }
19874 
19875         return true;
19876     }
19877 
19878     /**
19879      * Called by app main thread to wait for the network policy rules to get updated.
19880      *
19881      * @param procStateSeq The sequence number indicating the process state change that the main
19882      *                     thread is interested in.
19883      */
19884     @Override
waitForNetworkStateUpdate(long procStateSeq)19885     public void waitForNetworkStateUpdate(long procStateSeq) {
19886         final int callingUid = Binder.getCallingUid();
19887         if (DEBUG_NETWORK) {
19888             Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq);
19889         }
19890         UidRecord record;
19891         synchronized (this) {
19892             record = mProcessList.getUidRecordLocked(callingUid);
19893             if (record == null) {
19894                 return;
19895             }
19896         }
19897         synchronized (record.networkStateLock) {
19898             if (record.lastDispatchedProcStateSeq < procStateSeq) {
19899                 if (DEBUG_NETWORK) {
19900                     Slog.d(TAG_NETWORK, "Uid state change for seq no. " + procStateSeq + " is not "
19901                             + "dispatched to NPMS yet, so don't wait. Uid: " + callingUid
19902                             + " lastProcStateSeqDispatchedToObservers: "
19903                             + record.lastDispatchedProcStateSeq);
19904                 }
19905                 return;
19906             }
19907             if (record.curProcStateSeq > procStateSeq) {
19908                 if (DEBUG_NETWORK) {
19909                     Slog.d(TAG_NETWORK, "Ignore the wait requests for older seq numbers. Uid: "
19910                             + callingUid + ", curProcStateSeq: " + record.curProcStateSeq
19911                             + ", procStateSeq: " + procStateSeq);
19912                 }
19913                 return;
19914             }
19915             if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
19916                 if (DEBUG_NETWORK) {
19917                     Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. "
19918                             + procStateSeq + ", so no need to wait. Uid: "
19919                             + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: "
19920                             + record.lastNetworkUpdatedProcStateSeq);
19921                 }
19922                 return;
19923             }
19924             try {
19925                 if (DEBUG_NETWORK) {
19926                     Slog.d(TAG_NETWORK, "Starting to wait for the network rules update."
19927                         + " Uid: " + callingUid + " procStateSeq: " + procStateSeq);
19928                 }
19929                 final long startTime = SystemClock.uptimeMillis();
19930                 record.waitingForNetwork = true;
19931                 record.networkStateLock.wait(mWaitForNetworkTimeoutMs);
19932                 record.waitingForNetwork = false;
19933                 final long totalTime = SystemClock.uptimeMillis() - startTime;
19934                 if (totalTime >= mWaitForNetworkTimeoutMs || DEBUG_NETWORK) {
19935                     Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: "
19936                             + totalTime + ". Uid: " + callingUid + " procStateSeq: "
19937                             + procStateSeq + " UidRec: " + record
19938                             + " validateUidRec: " + mValidateUids.get(callingUid));
19939                 }
19940             } catch (InterruptedException e) {
19941                 Thread.currentThread().interrupt();
19942             }
19943         }
19944     }
19945 
waitForBroadcastIdle(PrintWriter pw)19946     public void waitForBroadcastIdle(PrintWriter pw) {
19947         enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()");
19948         while (true) {
19949             boolean idle = true;
19950             synchronized (this) {
19951                 for (BroadcastQueue queue : mBroadcastQueues) {
19952                     if (!queue.isIdle()) {
19953                         final String msg = "Waiting for queue " + queue + " to become idle...";
19954                         pw.println(msg);
19955                         pw.println(queue.describeState());
19956                         pw.flush();
19957                         Slog.v(TAG, msg);
19958                         queue.cancelDeferrals();
19959                         idle = false;
19960                     }
19961                 }
19962             }
19963 
19964             if (idle) {
19965                 final String msg = "All broadcast queues are idle!";
19966                 pw.println(msg);
19967                 pw.flush();
19968                 Slog.v(TAG, msg);
19969                 return;
19970             } else {
19971                 SystemClock.sleep(1000);
19972             }
19973         }
19974     }
19975 
19976     /**
19977      * Force the settings cache to be loaded
19978      */
refreshSettingsCache()19979     void refreshSettingsCache() {
19980         mCoreSettingsObserver.onChange(true);
19981     }
19982 
19983     /**
19984      * Kill processes for the user with id userId and that depend on the package named packageName
19985      */
19986     @Override
killPackageDependents(String packageName, int userId)19987     public void killPackageDependents(String packageName, int userId) {
19988         enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()");
19989         if (packageName == null) {
19990             throw new NullPointerException(
19991                     "Cannot kill the dependents of a package without its name.");
19992         }
19993 
19994         long callingId = Binder.clearCallingIdentity();
19995         IPackageManager pm = AppGlobals.getPackageManager();
19996         int pkgUid = -1;
19997         try {
19998             pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
19999         } catch (RemoteException e) {
20000         }
20001         if (userId != UserHandle.USER_ALL && pkgUid == -1) {
20002             throw new IllegalArgumentException(
20003                     "Cannot kill dependents of non-existing package " + packageName);
20004         }
20005         try {
20006             synchronized(this) {
20007                 mProcessList.killPackageProcessesLocked(packageName, UserHandle.getAppId(pkgUid),
20008                         userId, ProcessList.FOREGROUND_APP_ADJ,
20009                         ApplicationExitInfo.REASON_DEPENDENCY_DIED,
20010                         ApplicationExitInfo.SUBREASON_UNKNOWN,
20011                         "dep: " + packageName);
20012             }
20013         } finally {
20014             Binder.restoreCallingIdentity(callingId);
20015         }
20016     }
20017 
20018     @Override
restartUserInBackground(final int userId)20019     public int restartUserInBackground(final int userId) {
20020         return mUserController.restartUser(userId, /* foreground */ false);
20021     }
20022 
20023     @Override
scheduleApplicationInfoChanged(List<String> packageNames, int userId)20024     public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) {
20025         enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
20026                 "scheduleApplicationInfoChanged()");
20027 
20028         synchronized (this) {
20029             final long origId = Binder.clearCallingIdentity();
20030             try {
20031                 updateApplicationInfoLocked(packageNames, userId);
20032             } finally {
20033                 Binder.restoreCallingIdentity(origId);
20034             }
20035         }
20036     }
20037 
20038     /**
20039      * Synchronously update the system ActivityThread, bypassing any deferred threading so any
20040      * resources and overlaid values are available immediately.
20041      */
updateSystemUiContext()20042     public void updateSystemUiContext() {
20043         PackageManagerInternal packageManagerInternal;
20044         synchronized (this) {
20045             packageManagerInternal = getPackageManagerInternalLocked();
20046         }
20047 
20048         ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android",
20049                 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM);
20050         ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai);
20051     }
20052 
updateApplicationInfoLocked(@onNull List<String> packagesToUpdate, int userId)20053     void updateApplicationInfoLocked(@NonNull List<String> packagesToUpdate, int userId) {
20054         final boolean updateFrameworkRes = packagesToUpdate.contains("android");
20055         if (updateFrameworkRes) {
20056             PackageParser.readConfigUseRoundIcon(null);
20057         }
20058         mProcessList.updateApplicationInfoLocked(packagesToUpdate, userId, updateFrameworkRes);
20059 
20060         if (updateFrameworkRes) {
20061             // Update system server components that need to know about changed overlays. Because the
20062             // overlay is applied in ActivityThread, we need to serialize through its thread too.
20063             final Executor executor = ActivityThread.currentActivityThread().getExecutor();
20064             final DisplayManagerInternal display =
20065                     LocalServices.getService(DisplayManagerInternal.class);
20066             if (display != null) {
20067                 executor.execute(display::onOverlayChanged);
20068             }
20069             if (mWindowManager != null) {
20070                 executor.execute(mWindowManager::onOverlayChanged);
20071             }
20072         }
20073     }
20074 
20075     /**
20076      * Attach an agent to the specified process (proces name or PID)
20077      */
attachAgent(String process, String path)20078     public void attachAgent(String process, String path) {
20079         try {
20080             synchronized (this) {
20081                 ProcessRecord proc = findProcessLocked(process, UserHandle.USER_SYSTEM,
20082                         "attachAgent");
20083                 if (proc == null || proc.thread == null) {
20084                     throw new IllegalArgumentException("Unknown process: " + process);
20085                 }
20086 
20087                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
20088                 if (!isDebuggable) {
20089                     if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
20090                         throw new SecurityException("Process not debuggable: " + proc);
20091                     }
20092                 }
20093 
20094                 proc.thread.attachAgent(path);
20095             }
20096         } catch (RemoteException e) {
20097             throw new IllegalStateException("Process disappeared");
20098         }
20099     }
20100 
20101     /**
20102      * When power button is very long pressed, call this interface to do some pre-shutdown work
20103      * like persisting database etc.
20104      */
prepareForPossibleShutdown()20105     public void prepareForPossibleShutdown() {
20106         synchronized (this) {
20107             if (mUsageStatsService != null) {
20108                 mUsageStatsService.prepareForPossibleShutdown();
20109             }
20110         }
20111     }
20112 
20113     @VisibleForTesting
20114     public static class Injector {
20115         private NetworkManagementInternal mNmi;
20116         private Context mContext;
20117 
Injector(Context context)20118         public Injector(Context context) {
20119             mContext = context;
20120         }
20121 
getContext()20122         public Context getContext() {
20123             return mContext;
20124         }
20125 
getAppOpsService(File file, Handler handler)20126         public AppOpsService getAppOpsService(File file, Handler handler) {
20127             return new AppOpsService(file, handler, getContext());
20128         }
20129 
getUiHandler(ActivityManagerService service)20130         public Handler getUiHandler(ActivityManagerService service) {
20131             return service.new UiHandler();
20132         }
20133 
isNetworkRestrictedForUid(int uid)20134         public boolean isNetworkRestrictedForUid(int uid) {
20135             if (ensureHasNetworkManagementInternal()) {
20136                 return mNmi.isNetworkRestrictedForUid(uid);
20137             }
20138             return false;
20139         }
20140 
20141         /**
20142          * Return the process list instance
20143          */
getProcessList(ActivityManagerService service)20144         public ProcessList getProcessList(ActivityManagerService service) {
20145             return new ProcessList();
20146         }
20147 
ensureHasNetworkManagementInternal()20148         private boolean ensureHasNetworkManagementInternal() {
20149             if (mNmi == null) {
20150                 mNmi = LocalServices.getService(NetworkManagementInternal.class);
20151             }
20152             return mNmi != null;
20153         }
20154     }
20155 
20156     @Override
startDelegateShellPermissionIdentity(int delegateUid, @Nullable String[] permissions)20157     public void startDelegateShellPermissionIdentity(int delegateUid,
20158             @Nullable String[] permissions) {
20159         if (UserHandle.getCallingAppId() != Process.SHELL_UID
20160                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
20161             throw new SecurityException("Only the shell can delegate its permissions");
20162         }
20163 
20164         // We allow delegation only to one instrumentation started from the shell
20165         synchronized (ActivityManagerService.this) {
20166             // If there is a delegate it should be the same instance for app ops and permissions.
20167             if (mAppOpsService.getAppOpsServiceDelegate()
20168                     != getPermissionManagerInternalLocked().getCheckPermissionDelegate()) {
20169                 throw new IllegalStateException("Bad shell delegate state");
20170             }
20171 
20172             // If the delegate is already set up for the target UID, nothing to do.
20173             if (mAppOpsService.getAppOpsServiceDelegate() != null) {
20174                 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) {
20175                     throw new IllegalStateException("Bad shell delegate state");
20176                 }
20177                 final ShellDelegate delegate = (ShellDelegate) mAppOpsService
20178                         .getAppOpsServiceDelegate();
20179                 if (delegate.getDelegateUid() != delegateUid) {
20180                     throw new SecurityException("Shell can delegate permissions only "
20181                             + "to one instrumentation at a time");
20182                 }
20183                 delegate.setPermissions(permissions);
20184                 return;
20185             }
20186 
20187             final int instrCount = mActiveInstrumentation.size();
20188             for (int i = 0; i < instrCount; i++) {
20189                 final ActiveInstrumentation instr = mActiveInstrumentation.get(i);
20190                 if (instr.mTargetInfo.uid != delegateUid) {
20191                     continue;
20192                 }
20193                 // If instrumentation started from the shell the connection is not null
20194                 if (instr.mUiAutomationConnection == null) {
20195                     throw new SecurityException("Shell can delegate its permissions" +
20196                             " only to an instrumentation started from the shell");
20197                 }
20198 
20199                 // Hook them up...
20200                 final ShellDelegate shellDelegate = new ShellDelegate(
20201                         instr.mTargetInfo.packageName, delegateUid, permissions);
20202                 mAppOpsService.setAppOpsServiceDelegate(shellDelegate);
20203                 getPermissionManagerInternalLocked().setCheckPermissionDelegate(shellDelegate);
20204                 return;
20205             }
20206         }
20207     }
20208 
20209     @Override
stopDelegateShellPermissionIdentity()20210     public void stopDelegateShellPermissionIdentity() {
20211         if (UserHandle.getCallingAppId() != Process.SHELL_UID
20212                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
20213             throw new SecurityException("Only the shell can delegate its permissions");
20214         }
20215         synchronized (ActivityManagerService.this) {
20216             mAppOpsService.setAppOpsServiceDelegate(null);
20217             getPermissionManagerInternalLocked().setCheckPermissionDelegate(null);
20218         }
20219     }
20220 
20221     private class ShellDelegate implements CheckOpsDelegate, CheckPermissionDelegate {
20222         private final String mTargetPackageName;
20223         private final int mTargetUid;
20224         private @Nullable String[] mPermissions;
20225 
ShellDelegate(String targetPackageName, int targetUid, @Nullable String[] permissions)20226         ShellDelegate(String targetPackageName, int targetUid, @Nullable String[] permissions) {
20227             mTargetPackageName = targetPackageName;
20228             mTargetUid = targetUid;
20229             mPermissions = permissions;
20230         }
20231 
getDelegateUid()20232         int getDelegateUid() {
20233             return mTargetUid;
20234         }
20235 
setPermissions(@ullable String[] permissions)20236         void setPermissions(@Nullable String[] permissions) {
20237             mPermissions = permissions;
20238             PackageManager.invalidatePackageInfoCache();
20239         }
20240 
20241         @Override
checkOperation(int code, int uid, String packageName, boolean raw, QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl)20242         public int checkOperation(int code, int uid, String packageName, boolean raw,
20243                 QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl) {
20244             if (uid == mTargetUid && isTargetOp(code)) {
20245                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
20246                         Process.SHELL_UID);
20247                 final long identity = Binder.clearCallingIdentity();
20248                 try {
20249                     return superImpl.apply(code, shellUid, "com.android.shell", raw);
20250                 } finally {
20251                     Binder.restoreCallingIdentity(identity);
20252                 }
20253             }
20254             return superImpl.apply(code, uid, packageName, raw);
20255         }
20256 
20257         @Override
checkAudioOperation(int code, int usage, int uid, String packageName, QuadFunction<Integer, Integer, Integer, String, Integer> superImpl)20258         public int checkAudioOperation(int code, int usage, int uid, String packageName,
20259                 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) {
20260             if (uid == mTargetUid && isTargetOp(code)) {
20261                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
20262                         Process.SHELL_UID);
20263                 final long identity = Binder.clearCallingIdentity();
20264                 try {
20265                     return superImpl.apply(code, usage, shellUid, "com.android.shell");
20266                 } finally {
20267                     Binder.restoreCallingIdentity(identity);
20268                 }
20269             }
20270             return superImpl.apply(code, usage, uid, packageName);
20271         }
20272 
20273         @Override
noteOperation(int code, int uid, @Nullable String packageName, @Nullable String featureId, boolean shouldCollectAsyncNotedOp, @Nullable String message, boolean shouldCollectMessage, @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean, Integer> superImpl)20274         public int noteOperation(int code, int uid, @Nullable String packageName,
20275                 @Nullable String featureId, boolean shouldCollectAsyncNotedOp,
20276                 @Nullable String message, boolean shouldCollectMessage,
20277                 @NonNull HeptFunction<Integer, Integer, String, String, Boolean, String, Boolean,
20278                         Integer> superImpl) {
20279             if (uid == mTargetUid && isTargetOp(code)) {
20280                 final int shellUid = UserHandle.getUid(UserHandle.getUserId(uid),
20281                         Process.SHELL_UID);
20282                 final long identity = Binder.clearCallingIdentity();
20283                 try {
20284                     return superImpl.apply(code, shellUid, "com.android.shell", featureId,
20285                             shouldCollectAsyncNotedOp, message, shouldCollectMessage);
20286                 } finally {
20287                     Binder.restoreCallingIdentity(identity);
20288                 }
20289             }
20290             return superImpl.apply(code, uid, packageName, featureId, shouldCollectAsyncNotedOp,
20291                     message, shouldCollectMessage);
20292         }
20293 
20294         @Override
checkPermission(String permName, String pkgName, int userId, TriFunction<String, String, Integer, Integer> superImpl)20295         public int checkPermission(String permName, String pkgName, int userId,
20296                 TriFunction<String, String, Integer, Integer> superImpl) {
20297             if (mTargetPackageName.equals(pkgName) && isTargetPermission(permName)) {
20298                 final long identity = Binder.clearCallingIdentity();
20299                 try {
20300                     return superImpl.apply(permName, "com.android.shell", userId);
20301                 } finally {
20302                     Binder.restoreCallingIdentity(identity);
20303                 }
20304             }
20305             return superImpl.apply(permName, pkgName, userId);
20306         }
20307 
20308         @Override
checkUidPermission(String permName, int uid, BiFunction<String, Integer, Integer> superImpl)20309         public int checkUidPermission(String permName, int uid,
20310                 BiFunction<String, Integer, Integer> superImpl) {
20311             if (uid == mTargetUid  && isTargetPermission(permName)) {
20312                 final long identity = Binder.clearCallingIdentity();
20313                 try {
20314                     return superImpl.apply(permName, Process.SHELL_UID);
20315                 } finally {
20316                     Binder.restoreCallingIdentity(identity);
20317                 }
20318             }
20319             return superImpl.apply(permName, uid);
20320         }
20321 
isTargetOp(int code)20322         private boolean isTargetOp(int code) {
20323             // null permissions means all ops are targeted
20324             if (mPermissions == null) {
20325                 return true;
20326             }
20327             // no permission for the op means the op is targeted
20328             final String permission = AppOpsManager.opToPermission(code);
20329             if (permission == null) {
20330                 return true;
20331             }
20332             return isTargetPermission(permission);
20333         }
20334 
isTargetPermission(@onNull String permission)20335         private boolean isTargetPermission(@NonNull String permission) {
20336             // null permissions means all permissions are targeted
20337             return (mPermissions == null || ArrayUtils.contains(mPermissions, permission));
20338         }
20339     }
20340 
20341     /**
20342      * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would
20343      * cause a watchdog kill.
20344      */
maybeTriggerWatchdog()20345     void maybeTriggerWatchdog() {
20346         final String key = "debug.trigger.watchdog";
20347         if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) {
20348             Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!");
20349 
20350             // Clear the property; otherwise the system would hang again after a watchdog restart.
20351             SystemProperties.set(key, "");
20352             synchronized (ActivityManagerService.this) {
20353                 try {
20354                     // Arbitrary long sleep for watchdog to catch.
20355                     Thread.sleep(60 * 60 * 1000);
20356                 } catch (InterruptedException e) {
20357                 }
20358             }
20359         }
20360     }
20361 
isOnOffloadQueue(int flags)20362     private boolean isOnOffloadQueue(int flags) {
20363         return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
20364     }
20365 
20366     @Override
getLifeMonitor()20367     public ParcelFileDescriptor getLifeMonitor() {
20368         if (!isCallerShell()) {
20369             throw new SecurityException("Only shell can call it");
20370         }
20371         synchronized (this) {
20372             try {
20373                 if (mLifeMonitorFds == null) {
20374                     mLifeMonitorFds = ParcelFileDescriptor.createPipe();
20375                 }
20376                 // The returned FD will be closed, but we want to keep our reader open,
20377                 // so return a dup instead.
20378                 return mLifeMonitorFds[0].dup();
20379             } catch (IOException e) {
20380                 Slog.w(TAG, "Unable to create pipe", e);
20381                 return null;
20382             }
20383         }
20384     }
20385 
20386     @Override
setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken)20387     public void setActivityLocusContext(ComponentName activity, LocusId locusId, IBinder appToken) {
20388         final int callingUid = Binder.getCallingUid();
20389         final int userId = UserHandle.getCallingUserId();
20390         if (getPackageManagerInternalLocked().getPackageUid(activity.getPackageName(),
20391                 /*flags=*/ 0, userId) != callingUid) {
20392             throw new SecurityException("Calling uid " + callingUid + " cannot set locusId"
20393                     + "for package " + activity.getPackageName());
20394         }
20395 
20396         if (mUsageStatsService != null) {
20397             mUsageStatsService.reportLocusUpdate(activity, userId, locusId, appToken);
20398         }
20399     }
20400 
20401     @Override
isAppFreezerSupported()20402     public boolean isAppFreezerSupported() {
20403         final long token = Binder.clearCallingIdentity();
20404 
20405         try {
20406             return mOomAdjuster.mCachedAppOptimizer.isFreezerSupported();
20407         } finally {
20408             Binder.restoreCallingIdentity(token);
20409         }
20410     }
20411 
20412     @Override
enableAppFreezer(boolean enable)20413     public boolean enableAppFreezer(boolean enable) {
20414         int callerUid = Binder.getCallingUid();
20415 
20416         // Only system can toggle the freezer state
20417         if (callerUid == SYSTEM_UID || Build.IS_DEBUGGABLE) {
20418             return mOomAdjuster.mCachedAppOptimizer.enableFreezer(enable);
20419         } else {
20420             throw new SecurityException("Caller uid " + callerUid + " cannot set freezer state ");
20421         }
20422     }
20423 }
20424