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_TEST_API_CHECKS;
28 import static android.app.ActivityManager.INSTR_FLAG_MOUNT_EXTERNAL_STORAGE_FULL;
29 import static android.app.ActivityManager.PROCESS_STATE_LAST_ACTIVITY;
30 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
31 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
32 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
33 import static android.app.AppOpsManager.OP_NONE;
34 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
35 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
36 import static android.content.pm.PackageManager.GET_PROVIDERS;
37 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES;
38 import static android.content.pm.PackageManager.MATCH_ALL;
39 import static android.content.pm.PackageManager.MATCH_ANY_USER;
40 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
41 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
42 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
43 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
44 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
45 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
46 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
47 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
48 import static android.os.FactoryTest.FACTORY_TEST_OFF;
49 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
50 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
51 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
52 import static android.os.IServiceManager.DUMP_FLAG_PROTO;
53 import static android.os.Process.BLUETOOTH_UID;
54 import static android.os.Process.FIRST_APPLICATION_UID;
55 import static android.os.Process.NETWORK_STACK_UID;
56 import static android.os.Process.NFC_UID;
57 import static android.os.Process.PHONE_UID;
58 import static android.os.Process.PROC_CHAR;
59 import static android.os.Process.PROC_OUT_LONG;
60 import static android.os.Process.PROC_PARENS;
61 import static android.os.Process.PROC_SPACE_TERM;
62 import static android.os.Process.ROOT_UID;
63 import static android.os.Process.SCHED_FIFO;
64 import static android.os.Process.SCHED_RESET_ON_FORK;
65 import static android.os.Process.SE_UID;
66 import static android.os.Process.SHELL_UID;
67 import static android.os.Process.SIGNAL_USR1;
68 import static android.os.Process.SYSTEM_UID;
69 import static android.os.Process.THREAD_PRIORITY_FOREGROUND;
70 import static android.os.Process.ZYGOTE_POLICY_FLAG_BATCH_LAUNCH;
71 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
72 import static android.os.Process.ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE;
73 import static android.os.Process.ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS;
74 import static android.os.Process.ZYGOTE_PROCESS;
75 import static android.os.Process.getTotalMemory;
76 import static android.os.Process.isThreadInProcess;
77 import static android.os.Process.killProcess;
78 import static android.os.Process.killProcessQuiet;
79 import static android.os.Process.myPid;
80 import static android.os.Process.myUid;
81 import static android.os.Process.readProcFile;
82 import static android.os.Process.removeAllProcessGroups;
83 import static android.os.Process.sendSignal;
84 import static android.os.Process.setThreadPriority;
85 import static android.os.Process.setThreadScheduler;
86 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
87 import static android.provider.Settings.Global.DEBUG_APP;
88 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS;
89 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
90 import static android.text.format.DateUtils.DAY_IN_MILLIS;
91 
92 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
93 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
94 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
95 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP;
96 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
97 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND;
98 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
99 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
100 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
101 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESS_OBSERVERS;
106 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROVIDER;
107 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS;
108 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
109 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS;
110 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS;
111 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
112 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
113 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
114 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
115 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
120 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESS_OBSERVERS;
121 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROVIDER;
122 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS;
123 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
124 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
125 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
126 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
127 import static com.android.server.am.MemoryStatUtil.hasMemcg;
128 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
129 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
130 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
131 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
132 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
133 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
134 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
135 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
136 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
137 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
138 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD;
139 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
140 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD;
141 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
142 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD;
143 import static com.android.server.wm.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
144 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
145 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString;
146 
147 import android.Manifest;
148 import android.Manifest.permission;
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.ApplicationThreadConstants;
164 import android.app.BroadcastOptions;
165 import android.app.ContentProviderHolder;
166 import android.app.Dialog;
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.WaitResult;
187 import android.app.WindowConfiguration.ActivityType;
188 import android.app.WindowConfiguration.WindowingMode;
189 import android.app.backup.IBackupManager;
190 import android.app.usage.UsageEvents;
191 import android.app.usage.UsageEvents.Event;
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.pm.ActivityInfo;
208 import android.content.pm.ActivityPresentationInfo;
209 import android.content.pm.ApplicationInfo;
210 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy;
211 import android.content.pm.IPackageDataObserver;
212 import android.content.pm.IPackageManager;
213 import android.content.pm.InstrumentationInfo;
214 import android.content.pm.PackageInfo;
215 import android.content.pm.PackageManager;
216 import android.content.pm.PackageManager.NameNotFoundException;
217 import android.content.pm.PackageManagerInternal;
218 import android.content.pm.PackageManagerInternal.CheckPermissionDelegate;
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.ProviderInfo;
224 import android.content.pm.ResolveInfo;
225 import android.content.pm.SELinuxUtil;
226 import android.content.pm.ServiceInfo;
227 import android.content.pm.UserInfo;
228 import android.content.res.CompatibilityInfo;
229 import android.content.res.Configuration;
230 import android.content.res.Resources;
231 import android.database.ContentObserver;
232 import android.graphics.Rect;
233 import android.hardware.display.DisplayManagerInternal;
234 import android.location.LocationManager;
235 import android.media.audiofx.AudioEffect;
236 import android.net.Proxy;
237 import android.net.Uri;
238 import android.os.AppZygote;
239 import android.os.BatteryStats;
240 import android.os.Binder;
241 import android.os.BinderProxy;
242 import android.os.Build;
243 import android.os.Bundle;
244 import android.os.Debug;
245 import android.os.DropBoxManager;
246 import android.os.FactoryTest;
247 import android.os.FileUtils;
248 import android.os.Handler;
249 import android.os.IBinder;
250 import android.os.IDeviceIdentifiersPolicyService;
251 import android.os.IPermissionController;
252 import android.os.IProcessInfoService;
253 import android.os.IProgressListener;
254 import android.os.Looper;
255 import android.os.Message;
256 import android.os.Parcel;
257 import android.os.ParcelFileDescriptor;
258 import android.os.PowerManager;
259 import android.os.PowerManager.ServiceType;
260 import android.os.PowerManagerInternal;
261 import android.os.Process;
262 import android.os.RemoteCallback;
263 import android.os.RemoteCallbackList;
264 import android.os.RemoteException;
265 import android.os.ResultReceiver;
266 import android.os.ServiceManager;
267 import android.os.ShellCallback;
268 import android.os.StrictMode;
269 import android.os.SystemClock;
270 import android.os.SystemProperties;
271 import android.os.Trace;
272 import android.os.TransactionTooLargeException;
273 import android.os.UserHandle;
274 import android.os.UserManager;
275 import android.os.WorkSource;
276 import android.os.storage.IStorageManager;
277 import android.os.storage.StorageManager;
278 import android.provider.DeviceConfig;
279 import android.provider.DeviceConfig.Properties;
280 import android.provider.Settings;
281 import android.server.ServerProtoEnums;
282 import android.sysprop.InitProperties;
283 import android.sysprop.VoldProperties;
284 import android.text.TextUtils;
285 import android.text.format.DateUtils;
286 import android.text.style.SuggestionSpan;
287 import android.util.ArrayMap;
288 import android.util.ArraySet;
289 import android.util.DebugUtils;
290 import android.util.EventLog;
291 import android.util.Log;
292 import android.util.Pair;
293 import android.util.PrintWriterPrinter;
294 import android.util.Slog;
295 import android.util.SparseArray;
296 import android.util.SparseIntArray;
297 import android.util.StatsLog;
298 import android.util.TimeUtils;
299 import android.util.TimingsTraceLog;
300 import android.util.proto.ProtoOutputStream;
301 import android.util.proto.ProtoUtils;
302 import android.view.Display;
303 import android.view.Gravity;
304 import android.view.IRecentsAnimationRunner;
305 import android.view.LayoutInflater;
306 import android.view.View;
307 import android.view.WindowManager;
308 import android.view.autofill.AutofillManagerInternal;
309 
310 import com.android.internal.R;
311 import com.android.internal.annotations.GuardedBy;
312 import com.android.internal.annotations.VisibleForTesting;
313 import com.android.internal.app.DumpHeapActivity;
314 import com.android.internal.app.IAppOpsCallback;
315 import com.android.internal.app.IAppOpsService;
316 import com.android.internal.app.ProcessMap;
317 import com.android.internal.app.SystemUserHomeActivity;
318 import com.android.internal.app.procstats.ProcessStats;
319 import com.android.internal.content.PackageHelper;
320 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
321 import com.android.internal.notification.SystemNotificationChannels;
322 import com.android.internal.os.BackgroundThread;
323 import com.android.internal.os.BatteryStatsImpl;
324 import com.android.internal.os.BinderInternal;
325 import com.android.internal.os.ByteTransferPipe;
326 import com.android.internal.os.IResultReceiver;
327 import com.android.internal.os.ProcessCpuTracker;
328 import com.android.internal.os.TransferPipe;
329 import com.android.internal.os.Zygote;
330 import com.android.internal.telephony.TelephonyIntents;
331 import com.android.internal.util.ArrayUtils;
332 import com.android.internal.util.DumpUtils;
333 import com.android.internal.util.FastPrintWriter;
334 import com.android.internal.util.MemInfoReader;
335 import com.android.internal.util.Preconditions;
336 import com.android.internal.util.function.QuadFunction;
337 import com.android.internal.util.function.TriFunction;
338 import com.android.server.AlarmManagerInternal;
339 import com.android.server.AttributeCache;
340 import com.android.server.DeviceIdleController;
341 import com.android.server.DisplayThread;
342 import com.android.server.IntentResolver;
343 import com.android.server.IoThread;
344 import com.android.server.LocalServices;
345 import com.android.server.LockGuard;
346 import com.android.server.NetworkManagementInternal;
347 import com.android.server.PackageWatchdog;
348 import com.android.server.RescueParty;
349 import com.android.server.ServiceThread;
350 import com.android.server.SystemConfig;
351 import com.android.server.SystemService;
352 import com.android.server.SystemServiceManager;
353 import com.android.server.ThreadPriorityBooster;
354 import com.android.server.UserspaceRebootLogger;
355 import com.android.server.Watchdog;
356 import com.android.server.am.ActivityManagerServiceDumpProcessesProto.UidObserverRegistrationProto;
357 import com.android.server.appop.AppOpsService;
358 import com.android.server.compat.PlatformCompat;
359 import com.android.server.contentcapture.ContentCaptureManagerInternal;
360 import com.android.server.firewall.IntentFirewall;
361 import com.android.server.job.JobSchedulerInternal;
362 import com.android.server.pm.Installer;
363 import com.android.server.uri.GrantUri;
364 import com.android.server.uri.UriGrantsManagerInternal;
365 import com.android.server.utils.PriorityDump;
366 import com.android.server.vr.VrManagerInternal;
367 import com.android.server.wm.ActivityMetricsLaunchObserver;
368 import com.android.server.wm.ActivityServiceConnectionsHolder;
369 import com.android.server.wm.ActivityTaskManagerInternal;
370 import com.android.server.wm.ActivityTaskManagerService;
371 import com.android.server.wm.WindowManagerService;
372 import com.android.server.wm.WindowProcessController;
373 
374 import dalvik.system.VMRuntime;
375 
376 import libcore.util.EmptyArray;
377 
378 import java.io.File;
379 import java.io.FileDescriptor;
380 import java.io.FileNotFoundException;
381 import java.io.FileOutputStream;
382 import java.io.IOException;
383 import java.io.InputStreamReader;
384 import java.io.PrintWriter;
385 import java.io.StringWriter;
386 import java.io.UnsupportedEncodingException;
387 import java.text.SimpleDateFormat;
388 import java.util.ArrayList;
389 import java.util.Arrays;
390 import java.util.Collections;
391 import java.util.Comparator;
392 import java.util.Date;
393 import java.util.HashMap;
394 import java.util.HashSet;
395 import java.util.Iterator;
396 import java.util.List;
397 import java.util.Locale;
398 import java.util.Map;
399 import java.util.Objects;
400 import java.util.Set;
401 import java.util.concurrent.CountDownLatch;
402 import java.util.concurrent.Executor;
403 import java.util.concurrent.atomic.AtomicBoolean;
404 import java.util.concurrent.atomic.AtomicInteger;
405 import java.util.concurrent.atomic.AtomicLong;
406 import java.util.function.BiFunction;
407 
408 public class ActivityManagerService extends IActivityManager.Stub
409         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
410 
411     /**
412      * Priority we boost main thread and RT of top app to.
413      */
414     public static final int TOP_APP_PRIORITY_BOOST = -10;
415 
416     private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED =
417             "persist.sys.device_provisioned";
418 
419     static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
420     static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
421     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
422     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
423     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
424     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
425     static final String TAG_LRU = TAG + POSTFIX_LRU;
426     private static final String TAG_MU = TAG + POSTFIX_MU;
427     private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
428     static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
429     private static final String TAG_POWER = TAG + POSTFIX_POWER;
430     static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
431     static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
432     private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER;
433     static final String TAG_PSS = TAG + POSTFIX_PSS;
434     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
435     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
436     static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
437 
438     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
439     // here so that while the job scheduler can depend on AMS, the other way around
440     // need not be the case.
441     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
442 
443     /** Control over CPU and battery monitoring */
444     // write battery stats every 30 minutes.
445     static final long BATTERY_STATS_TIME = 30 * 60 * 1000;
446     static final boolean MONITOR_CPU_USAGE = true;
447     // don't sample cpu less than every 5 seconds.
448     static final long MONITOR_CPU_MIN_TIME = 5 * 1000;
449     // wait possibly forever for next cpu sample.
450     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;
451     static final boolean MONITOR_THREAD_CPU_USAGE = false;
452 
453     // The flags that are set for all calls we make to the package manager.
454     public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
455 
456     static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
457 
458     static final String SYSTEM_USER_HOME_NEEDED = "ro.system_user_home_needed";
459 
460     public static final String ANR_TRACE_DIR = "/data/anr";
461 
462     // Maximum number of receivers an app can register.
463     private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000;
464 
465     // How long we wait for a launched process to attach to the activity manager
466     // before we decide it's never going to come up for real.
467     static final int PROC_START_TIMEOUT = 10*1000;
468     // How long we wait for an attached process to publish its content providers
469     // before we decide it must be hung.
470     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
471 
472     // How long we wait to kill an application zygote, after the last process using
473     // it has gone away.
474     static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000;
475     /**
476      * How long we wait for an provider to be published. Should be longer than
477      * {@link #CONTENT_PROVIDER_PUBLISH_TIMEOUT}.
478      */
479     static final int CONTENT_PROVIDER_WAIT_TIMEOUT = 20 * 1000;
480 
481     // How long we wait for a launched process to attach to the activity manager
482     // before we decide it's never going to come up for real, when the process was
483     // started with a wrapper for instrumentation (such as Valgrind) because it
484     // could take much longer than usual.
485     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
486 
487     // How long we allow a receiver to run before giving up on it.
488     static final int BROADCAST_FG_TIMEOUT = 10*1000;
489     static final int BROADCAST_BG_TIMEOUT = 60*1000;
490 
491     public static final int MY_PID = myPid();
492 
493     static final String[] EMPTY_STRING_ARRAY = new String[0];
494 
495     // How many bytes to write into the dropbox log before truncating
496     static final int DROPBOX_MAX_SIZE = 192 * 1024;
497     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
498     // as one line, but close enough for now.
499     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
500 
501     /** If a UID observer takes more than this long, send a WTF. */
502     private static final int SLOW_UID_OBSERVER_THRESHOLD_MS = 20;
503 
504     // Necessary ApplicationInfo flags to mark an app as persistent
505     static final int PERSISTENT_MASK =
506             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
507 
508     // Intent sent when remote bugreport collection has been completed
509     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
510             "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
511 
512     // If set, we will push process association information in to procstats.
513     static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true;
514 
515     /**
516      * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}.
517      */
518     private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec
519 
520     // The minimum memory growth threshold (in KB) for low RAM devices.
521     private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB
522 
523     /**
524      * The number of binder proxies we need to have before we start warning and
525      * dumping debug info.
526      */
527     private static final int BINDER_PROXY_HIGH_WATERMARK = 6000;
528 
529     /**
530      * Low watermark that needs to be met before we consider dumping info again,
531      * after already hitting the high watermark.
532      */
533     private static final int BINDER_PROXY_LOW_WATERMARK = 5500;
534 
535     /**
536      * State indicating that there is no need for any blocking for network.
537      */
538     @VisibleForTesting
539     static final int NETWORK_STATE_NO_CHANGE = 0;
540 
541     /**
542      * State indicating that the main thread needs to be informed about the network wait.
543      */
544     @VisibleForTesting
545     static final int NETWORK_STATE_BLOCK = 1;
546 
547     /**
548      * State indicating that any threads waiting for network state to get updated can be unblocked.
549      */
550     @VisibleForTesting
551     static final int NETWORK_STATE_UNBLOCK = 2;
552 
553     // Max character limit for a notification title. If the notification title is larger than this
554     // the notification will not be legible to the user.
555     private static final int MAX_BUGREPORT_TITLE_SIZE = 50;
556 
557     private static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds;
558     private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes.
559 
560     OomAdjuster mOomAdjuster;
561     final LowMemDetector mLowMemDetector;
562 
563     /** All system services */
564     SystemServiceManager mSystemServiceManager;
565 
566     private Installer mInstaller;
567 
568     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
569 
570     final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
571 
572     public final IntentFirewall mIntentFirewall;
573 
574     public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler();
575 
576     // Whether we should use SCHED_FIFO for UI and RenderThreads.
577     boolean mUseFifoUiScheduling = false;
578 
579     // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
580     // For simplicity, since we statically declare the size of the array of BroadcastQueues,
581     // we still create this new offload queue, but never ever put anything on it.
582     boolean mEnableOffloadQueue;
583 
584     BroadcastQueue mFgBroadcastQueue;
585     BroadcastQueue mBgBroadcastQueue;
586     BroadcastQueue mOffloadBroadcastQueue;
587     // Convenient for easy iteration over the queues. Foreground is first
588     // so that dispatch of foreground broadcasts gets precedence.
589     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[3];
590 
591     BroadcastStats mLastBroadcastStats;
592     BroadcastStats mCurBroadcastStats;
593 
broadcastQueueForIntent(Intent intent)594     BroadcastQueue broadcastQueueForIntent(Intent intent) {
595         if (isOnOffloadQueue(intent.getFlags())) {
596             if (DEBUG_BROADCAST_BACKGROUND) {
597                 Slog.i(TAG_BROADCAST,
598                         "Broadcast intent " + intent + " on offload queue");
599             }
600             return mOffloadBroadcastQueue;
601         }
602 
603         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
604         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
605                 "Broadcast intent " + intent + " on "
606                 + (isFg ? "foreground" : "background") + " queue");
607         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
608     }
609 
610     /**
611      * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
612      */
613     String mDeviceOwnerName;
614 
615     final UserController mUserController;
616     @VisibleForTesting
617     public final PendingIntentController mPendingIntentController;
618 
619     final AppErrors mAppErrors;
620     final PackageWatchdog mPackageWatchdog;
621 
622     /**
623      * Indicates the maximum time spent waiting for the network rules to get updated.
624      */
625     @VisibleForTesting
626     long mWaitForNetworkTimeoutMs;
627 
628     /** Total # of UID change events dispatched, shown in dumpsys. */
629     int mUidChangeDispatchCount;
630 
631     /**
632      * Helper class which strips out priority and proto arguments then calls the dump function with
633      * the appropriate arguments. If priority arguments are omitted, function calls the legacy
634      * dump command.
635      * If priority arguments are omitted all sections are dumped, otherwise sections are dumped
636      * according to their priority.
637      */
638     private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
639         @Override
640         public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
641                 boolean asProto) {
642             if (asProto) return;
643             doDump(fd, pw, new String[]{"activities"}, asProto);
644             doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
645         }
646 
647         @Override
648         public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
649             doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto);
650         }
651 
652         @Override
653         public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
654             doDump(fd, pw, args, asProto);
655         }
656     };
657 
658     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
659             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
660 
boostPriorityForLockedSection()661     static void boostPriorityForLockedSection() {
662         sThreadPriorityBooster.boost();
663     }
664 
resetPriorityAfterLockedSection()665     static void resetPriorityAfterLockedSection() {
666         sThreadPriorityBooster.reset();
667     }
668 
669     /**
670      * Process management.
671      */
672     final ProcessList mProcessList = new ProcessList();
673 
674     /**
675      * Tracking long-term execution of processes to look for abuse and other
676      * bad app behavior.
677      */
678     final ProcessStatsService mProcessStats;
679 
680     /**
681      * Non-persistent appId whitelist for background restrictions
682      */
683     int[] mBackgroundAppIdWhitelist = new int[] {
684             BLUETOOTH_UID
685     };
686 
687     /**
688      * Broadcast actions that will always be deliverable to unlaunched/background apps
689      */
690     ArraySet<String> mBackgroundLaunchBroadcasts;
691 
692     /**
693      * When an app has restrictions on the other apps that can have associations with it,
694      * it appears here with a set of the allowed apps and also track debuggability of the app.
695      */
696     ArrayMap<String, PackageAssociationInfo> mAllowedAssociations;
697 
698     /**
699      * Tracks association information for a particular package along with debuggability.
700      * <p> Associations for a package A are allowed to package B if B is part of the
701      *     allowed associations for A or if A is debuggable.
702      */
703     private final class PackageAssociationInfo {
704         private final String mSourcePackage;
705         private final ArraySet<String> mAllowedPackageAssociations;
706         private boolean mIsDebuggable;
707 
PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)708         PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages,
709                 boolean isDebuggable) {
710             mSourcePackage = sourcePackage;
711             mAllowedPackageAssociations = allowedPackages;
712             mIsDebuggable = isDebuggable;
713         }
714 
715         /**
716          * Returns true if {@code mSourcePackage} is allowed association with
717          * {@code targetPackage}.
718          */
isPackageAssociationAllowed(String targetPackage)719         boolean isPackageAssociationAllowed(String targetPackage) {
720             return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage);
721         }
722 
isDebuggable()723         boolean isDebuggable() {
724             return mIsDebuggable;
725         }
726 
setDebuggable(boolean isDebuggable)727         void setDebuggable(boolean isDebuggable) {
728             mIsDebuggable = isDebuggable;
729         }
730 
getAllowedPackageAssociations()731         ArraySet<String> getAllowedPackageAssociations() {
732             return mAllowedPackageAssociations;
733         }
734     }
735 
736     /**
737      * All of the processes we currently have running organized by pid.
738      * The keys are the pid running the application.
739      *
740      * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock!
741      */
742     final PidMap mPidsSelfLocked = new PidMap();
743     final class PidMap {
744         private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>();
745 
746         /**
747          * Puts the process record in the map.
748          * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
749          * method.
750          */
put(ProcessRecord app)751         void put(ProcessRecord app) {
752             synchronized (this) {
753                 mPidMap.put(app.pid, app);
754             }
755             mAtmInternal.onProcessMapped(app.pid, app.getWindowProcessController());
756         }
757 
758         /**
759          * Removes the process record from the map.
760          * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
761          * method.
762          */
remove(ProcessRecord app)763         void remove(ProcessRecord app) {
764             boolean removed = false;
765             synchronized (this) {
766                 final ProcessRecord existingApp = mPidMap.get(app.pid);
767                 if (existingApp != null && existingApp.startSeq == app.startSeq) {
768                     mPidMap.remove(app.pid);
769                     removed = true;
770                 }
771             }
772             if (removed) {
773                 mAtmInternal.onProcessUnMapped(app.pid);
774             }
775         }
776 
777         /**
778          * Removes the process record from the map if it has a thread.
779          * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
780          * method.
781          */
removeIfNoThread(ProcessRecord app)782         boolean removeIfNoThread(ProcessRecord app) {
783             boolean removed = false;
784             synchronized (this) {
785                 final ProcessRecord existingApp = get(app.pid);
786                 if (existingApp != null && existingApp.startSeq == app.startSeq
787                         && app.thread == null) {
788                     mPidMap.remove(app.pid);
789                     removed = true;
790                 }
791             }
792             if (removed) {
793                 mAtmInternal.onProcessUnMapped(app.pid);
794             }
795             return removed;
796         }
797 
get(int pid)798         ProcessRecord get(int pid) {
799             return mPidMap.get(pid);
800         }
801 
size()802         int size() {
803             return mPidMap.size();
804         }
805 
valueAt(int index)806         ProcessRecord valueAt(int index) {
807             return mPidMap.valueAt(index);
808         }
809 
keyAt(int index)810         int keyAt(int index) {
811             return mPidMap.keyAt(index);
812         }
813 
indexOfKey(int key)814         int indexOfKey(int key) {
815             return mPidMap.indexOfKey(key);
816         }
817     }
818 
819     /**
820      * All of the processes that have been forced to be important.  The key
821      * is the pid of the caller who requested it (we hold a death
822      * link on it).
823      */
824     abstract class ImportanceToken implements IBinder.DeathRecipient {
825         final int pid;
826         final IBinder token;
827         final String reason;
828 
ImportanceToken(int _pid, IBinder _token, String _reason)829         ImportanceToken(int _pid, IBinder _token, String _reason) {
830             pid = _pid;
831             token = _token;
832             reason = _reason;
833         }
834 
835         @Override
toString()836         public String toString() {
837             return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
838                     + " " + reason + " " + pid + " " + token + " }";
839         }
840 
writeToProto(ProtoOutputStream proto, long fieldId)841         void writeToProto(ProtoOutputStream proto, long fieldId) {
842             final long pToken = proto.start(fieldId);
843             proto.write(ImportanceTokenProto.PID, pid);
844             if (token != null) {
845                 proto.write(ImportanceTokenProto.TOKEN, token.toString());
846             }
847             proto.write(ImportanceTokenProto.REASON, reason);
848             proto.end(pToken);
849         }
850     }
851     final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
852 
853     /**
854      * List of records for processes that someone had tried to start before the
855      * system was ready.  We don't start them at that point, but ensure they
856      * are started by the time booting is complete.
857      */
858     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
859 
860     /**
861      * List of persistent applications that are in the process
862      * of being started.
863      */
864     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
865 
866     /**
867      * List of processes that should gc as soon as things are idle.
868      */
869     final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
870 
871     /**
872      * Processes we want to collect PSS data from.
873      */
874     final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
875 
876     /**
877      * Depth of overlapping activity-start PSS deferral notes
878      */
879     private final AtomicInteger mActivityStartingNesting = new AtomicInteger(0);
880 
881     private final ActivityMetricsLaunchObserver mActivityLaunchObserver =
882             new ActivityMetricsLaunchObserver() {
883         @Override
884         public void onActivityLaunched(byte[] activity, int temperature) {
885             // This is safe to force to the head of the queue because it relies only
886             // on refcounting to track begin/end of deferrals, not on actual
887             // message ordering.  We don't care *what* activity is being
888             // launched; only that we're doing so.
889             if (mPssDeferralTime > 0) {
890                 final Message msg = mBgHandler.obtainMessage(DEFER_PSS_MSG);
891                 mBgHandler.sendMessageAtFrontOfQueue(msg);
892             }
893         }
894 
895         // The other observer methods are unused
896         @Override
897         public void onIntentStarted(Intent intent) {
898         }
899 
900         @Override
901         public void onIntentFailed() {
902         }
903 
904         @Override
905         public void onActivityLaunchCancelled(byte[] abortingActivity) {
906         }
907 
908         @Override
909         public void onActivityLaunchFinished(byte[] finalActivity) {
910         }
911     };
912 
913     /**
914      * How long we defer PSS gathering while activities are starting, in milliseconds.
915      * This is adjustable via DeviceConfig.  If it is zero or negative, no PSS deferral
916      * is done.
917      */
918     private volatile long mPssDeferralTime = 0;
919     private static final String ACTIVITY_START_PSS_DEFER_CONFIG = "activity_start_pss_defer";
920 
921     private boolean mBinderTransactionTrackingEnabled = false;
922 
923     /**
924      * Last time we requested PSS data of all processes.
925      */
926     long mLastFullPssTime = SystemClock.uptimeMillis();
927 
928     /**
929      * If set, the next time we collect PSS data we should do a full collection
930      * with data from native processes and the kernel.
931      */
932     boolean mFullPssPending = false;
933 
934     /**
935      * Observe DeviceConfig changes to the PSS calculation interval
936      */
937     private final DeviceConfig.OnPropertiesChangedListener mPssDelayConfigListener =
938             new DeviceConfig.OnPropertiesChangedListener() {
939                 @Override
940                 public void onPropertiesChanged(Properties properties) {
941                     mPssDeferralTime = properties.getLong(ACTIVITY_START_PSS_DEFER_CONFIG, 0);
942                     if (DEBUG_PSS) {
943                         Slog.d(TAG_PSS, "Activity-start PSS delay now "
944                                 + mPssDeferralTime + " ms");
945                     }
946                 }
947             };
948 
949     /**
950      * This is for verifying the UID report flow.
951      */
952     static final boolean VALIDATE_UID_STATES = true;
953     final ActiveUids mValidateUids = new ActiveUids(this, false /* postChangesToAtm */);
954 
955     /**
956      * Fingerprints (hashCode()) of stack traces that we've
957      * already logged DropBox entries for.  Guarded by itself.  If
958      * something (rogue user app) forces this over
959      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
960      */
961     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
962     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
963 
964     /**
965      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
966      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
967      */
968     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
969 
970     /**
971      * Resolver for broadcast intents to registered receivers.
972      * Holds BroadcastFilter (subclass of IntentFilter).
973      */
974     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
975             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
976         @Override
977         protected boolean allowFilterResult(
978                 BroadcastFilter filter, List<BroadcastFilter> dest) {
979             IBinder target = filter.receiverList.receiver.asBinder();
980             for (int i = dest.size() - 1; i >= 0; i--) {
981                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
982                     return false;
983                 }
984             }
985             return true;
986         }
987 
988         @Override
989         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
990             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
991                     || userId == filter.owningUserId) {
992                 return super.newResult(filter, match, userId);
993             }
994             return null;
995         }
996 
997         @Override
998         protected BroadcastFilter[] newArray(int size) {
999             return new BroadcastFilter[size];
1000         }
1001 
1002         @Override
1003         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
1004             return packageName.equals(filter.packageName);
1005         }
1006     };
1007 
1008     /**
1009      * State of all active sticky broadcasts per user.  Keys are the action of the
1010      * sticky Intent, values are an ArrayList of all broadcasted intents with
1011      * that action (which should usually be one).  The SparseArray is keyed
1012      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1013      * for stickies that are sent to all users.
1014      */
1015     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
1016             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
1017 
1018     final ActiveServices mServices;
1019 
1020     final static class Association {
1021         final int mSourceUid;
1022         final String mSourceProcess;
1023         final int mTargetUid;
1024         final ComponentName mTargetComponent;
1025         final String mTargetProcess;
1026 
1027         int mCount;
1028         long mTime;
1029 
1030         int mNesting;
1031         long mStartTime;
1032 
1033         // states of the source process when the bind occurred.
1034         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1035         long mLastStateUptime;
1036         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1037                 - ActivityManager.MIN_PROCESS_STATE+1];
1038 
Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1039         Association(int sourceUid, String sourceProcess, int targetUid,
1040                 ComponentName targetComponent, String targetProcess) {
1041             mSourceUid = sourceUid;
1042             mSourceProcess = sourceProcess;
1043             mTargetUid = targetUid;
1044             mTargetComponent = targetComponent;
1045             mTargetProcess = targetProcess;
1046         }
1047     }
1048 
1049     /**
1050      * When service association tracking is enabled, this is all of the associations we
1051      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
1052      * -> association data.
1053      */
1054     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1055             mAssociations = new SparseArray<>();
1056     boolean mTrackingAssociations;
1057 
1058     /**
1059      * Backup/restore process management
1060      */
1061     @GuardedBy("this")
1062     final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>();
1063 
1064     final ProviderMap mProviderMap;
1065 
1066     /**
1067      * List of content providers who have clients waiting for them.  The
1068      * application is currently being launched and the provider will be
1069      * removed from this list once it is published.
1070      */
1071     final ArrayList<ContentProviderRecord> mLaunchingProviders = new ArrayList<>();
1072 
1073     boolean mSystemProvidersInstalled;
1074 
1075     CoreSettingsObserver mCoreSettingsObserver;
1076 
1077     DevelopmentSettingsObserver mDevelopmentSettingsObserver;
1078 
1079     private final class DevelopmentSettingsObserver extends ContentObserver {
1080         private final Uri mUri = Settings.Global
1081                 .getUriFor(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
1082 
1083         private final ComponentName mBugreportStorageProvider = new ComponentName(
1084                 "com.android.shell", "com.android.shell.BugreportStorageProvider");
1085 
DevelopmentSettingsObserver()1086         public DevelopmentSettingsObserver() {
1087             super(mHandler);
1088             mContext.getContentResolver().registerContentObserver(mUri, false, this,
1089                     UserHandle.USER_ALL);
1090             // Always kick once to ensure that we match current state
1091             onChange();
1092         }
1093 
1094         @Override
onChange(boolean selfChange, Uri uri, @UserIdInt int userId)1095         public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
1096             if (mUri.equals(uri)) {
1097                 onChange();
1098             }
1099         }
1100 
onChange()1101         public void onChange() {
1102             final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(),
1103                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, Build.IS_ENG ? 1 : 0) != 0;
1104             mContext.getPackageManager().setComponentEnabledSetting(mBugreportStorageProvider,
1105                     enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1106                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
1107                     0);
1108         }
1109     }
1110 
1111     /**
1112      * Thread-local storage used to carry caller permissions over through
1113      * indirect content-provider access.
1114      */
1115     private class Identity {
1116         public final IBinder token;
1117         public final int pid;
1118         public final int uid;
1119 
Identity(IBinder _token, int _pid, int _uid)1120         Identity(IBinder _token, int _pid, int _uid) {
1121             token = _token;
1122             pid = _pid;
1123             uid = _uid;
1124         }
1125     }
1126 
1127     private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1128 
1129     /**
1130      * All information we have collected about the runtime performance of
1131      * any user id that can impact battery performance.
1132      */
1133     final BatteryStatsService mBatteryStatsService;
1134 
1135     /**
1136      * Information about component usage
1137      */
1138     UsageStatsManagerInternal mUsageStatsService;
1139 
1140     /**
1141      * Access to DeviceIdleController service.
1142      */
1143     DeviceIdleController.LocalService mLocalDeviceIdleController;
1144 
1145     /**
1146      * Power-save whitelisted app-ids (not including except-idle-whitelisted ones).
1147      */
1148     int[] mDeviceIdleWhitelist = new int[0];
1149 
1150     /**
1151      * Power-save whitelisted app-ids (including except-idle-whitelisted ones).
1152      */
1153     int[] mDeviceIdleExceptIdleWhitelist = new int[0];
1154 
1155     /**
1156      * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1157      */
1158     int[] mDeviceIdleTempWhitelist = new int[0];
1159 
1160     static final class PendingTempWhitelist {
1161         final int targetUid;
1162         final long duration;
1163         final String tag;
1164 
PendingTempWhitelist(int _targetUid, long _duration, String _tag)1165         PendingTempWhitelist(int _targetUid, long _duration, String _tag) {
1166             targetUid = _targetUid;
1167             duration = _duration;
1168             tag = _tag;
1169         }
1170 
writeToProto(ProtoOutputStream proto, long fieldId)1171         void writeToProto(ProtoOutputStream proto, long fieldId) {
1172             final long token = proto.start(fieldId);
1173             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, targetUid);
1174             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, duration);
1175             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag);
1176             proto.end(token);
1177         }
1178     }
1179 
1180     final PendingTempWhitelists mPendingTempWhitelist = new PendingTempWhitelists(this);
1181 
1182     /**
1183      * Information about and control over application operations
1184      */
1185     final AppOpsService mAppOpsService;
1186 
1187     /**
1188      * List of initialization arguments to pass to all processes when binding applications to them.
1189      * For example, references to the commonly used services.
1190      */
1191     ArrayMap<String, IBinder> mAppBindArgs;
1192     ArrayMap<String, IBinder> mIsolatedAppBindArgs;
1193 
1194     /**
1195      * Temporary to avoid allocations.  Protected by main lock.
1196      */
1197     final StringBuilder mStringBuilder = new StringBuilder(256);
1198 
1199     volatile boolean mProcessesReady = false;
1200     volatile boolean mSystemReady = false;
1201     volatile boolean mOnBattery = false;
1202     final int mFactoryTest;
1203     volatile boolean mBooting = false;
1204 
1205     @GuardedBy("this") boolean mCallFinishBooting = false;
1206     @GuardedBy("this") boolean mBootAnimationComplete = false;
1207 
1208     final Context mContext;
1209 
1210     /**
1211      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1212      * change at runtime. Use mContext for non-UI purposes.
1213      */
1214     final Context mUiContext;
1215 
1216     /**
1217      * Last time (in uptime) at which we checked for power usage.
1218      */
1219     long mLastPowerCheckUptime;
1220 
1221     /**
1222      * For some direct access we need to power manager.
1223      */
1224     PowerManagerInternal mLocalPowerManager;
1225 
1226     /**
1227      * State of external calls telling us if the device is awake or asleep.
1228      */
1229     int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
1230 
1231     /**
1232      * Allow the current computed overall memory level of the system to go down?
1233      * This is set to false when we are killing processes for reasons other than
1234      * memory management, so that the now smaller process list will not be taken as
1235      * an indication that memory is tighter.
1236      */
1237     boolean mAllowLowerMemLevel = false;
1238 
1239     /**
1240      * The last computed memory level, for holding when we are in a state that
1241      * processes are going away for other reasons.
1242      */
1243     int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1244 
1245     /**
1246      * The last total number of process we have, to determine if changes actually look
1247      * like a shrinking number of process due to lower RAM.
1248      */
1249     int mLastNumProcesses;
1250 
1251     /**
1252      * The uptime of the last time we performed idle maintenance.
1253      */
1254     long mLastIdleTime = SystemClock.uptimeMillis();
1255 
1256     /**
1257      * Total time spent with RAM that has been added in the past since the last idle time.
1258      */
1259     long mLowRamTimeSinceLastIdle = 0;
1260 
1261     /**
1262      * If RAM is currently low, when that horrible situation started.
1263      */
1264     long mLowRamStartTime = 0;
1265 
1266     /**
1267      * For reporting to battery stats the current top application.
1268      */
1269     private String mCurResumedPackage = null;
1270     private int mCurResumedUid = -1;
1271 
1272     /**
1273      * For reporting to battery stats the apps currently running foreground
1274      * service.  The ProcessMap is package/uid tuples; each of these contain
1275      * an array of the currently foreground processes.
1276      */
1277     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1278             = new ProcessMap<ArrayList<ProcessRecord>>();
1279 
1280     /**
1281      * Set if the systemServer made a call to enterSafeMode.
1282      */
1283     boolean mSafeMode;
1284 
1285     /**
1286      * If true, we are running under a test environment so will sample PSS from processes
1287      * much more rapidly to try to collect better data when the tests are rapidly
1288      * running through apps.
1289      */
1290     boolean mTestPssMode = false;
1291 
1292     String mDebugApp = null;
1293     boolean mWaitForDebugger = false;
1294     boolean mDebugTransient = false;
1295     String mOrigDebugApp = null;
1296     boolean mOrigWaitForDebugger = false;
1297     boolean mAlwaysFinishActivities = false;
1298 
1299     class ProfileData {
1300         private String mProfileApp = null;
1301         private ProcessRecord mProfileProc = null;
1302         private ProfilerInfo mProfilerInfo = null;
1303 
setProfileApp(String profileApp)1304         void setProfileApp(String profileApp) {
1305             mProfileApp = profileApp;
1306             if (mAtmInternal != null) {
1307                 mAtmInternal.setProfileApp(profileApp);
1308             }
1309         }
1310 
getProfileApp()1311         String getProfileApp() {
1312             return mProfileApp;
1313         }
1314 
setProfileProc(ProcessRecord profileProc)1315         void setProfileProc(ProcessRecord profileProc) {
1316             mProfileProc = profileProc;
1317             if (mAtmInternal != null) {
1318                 mAtmInternal.setProfileProc(profileProc == null ? null
1319                         : profileProc.getWindowProcessController());
1320             }
1321         }
1322 
getProfileProc()1323         ProcessRecord getProfileProc() {
1324             return mProfileProc;
1325         }
1326 
setProfilerInfo(ProfilerInfo profilerInfo)1327         void setProfilerInfo(ProfilerInfo profilerInfo) {
1328             mProfilerInfo = profilerInfo;
1329             if (mAtmInternal != null) {
1330                 mAtmInternal.setProfilerInfo(profilerInfo);
1331             }
1332         }
1333 
getProfilerInfo()1334         ProfilerInfo getProfilerInfo() {
1335             return mProfilerInfo;
1336         }
1337     }
1338     final ProfileData mProfileData = new ProfileData();
1339 
1340     /**
1341      * Stores a map of process name -> agent string. When a process is started and mAgentAppMap
1342      * is not null, this map is checked and the mapped agent installed during bind-time. Note:
1343      * A non-null agent in mProfileInfo overrides this.
1344      */
1345     private @Nullable Map<String, String> mAppAgentMap = null;
1346 
1347     int mProfileType = 0;
1348     final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>();
1349     String mMemWatchDumpProcName;
1350     String mMemWatchDumpFile;
1351     int mMemWatchDumpPid;
1352     int mMemWatchDumpUid;
1353     private boolean mMemWatchIsUserInitiated;
1354     String mTrackAllocationApp = null;
1355     String mNativeDebuggingApp = null;
1356 
1357     private final Injector mInjector;
1358 
1359     static final class ProcessChangeItem {
1360         static final int CHANGE_ACTIVITIES = 1<<0;
1361         static final int CHANGE_FOREGROUND_SERVICES = 1<<1;
1362         int changes;
1363         int uid;
1364         int pid;
1365         int processState;
1366         boolean foregroundActivities;
1367         int foregroundServiceTypes;
1368     }
1369 
1370     static final class UidObserverRegistration {
1371         final int uid;
1372         final String pkg;
1373         final int which;
1374         final int cutpoint;
1375 
1376         /**
1377          * Total # of callback calls that took more than {@link #SLOW_UID_OBSERVER_THRESHOLD_MS}.
1378          * We show it in dumpsys.
1379          */
1380         int mSlowDispatchCount;
1381 
1382         /** Max time it took for each dispatch. */
1383         int mMaxDispatchTime;
1384 
1385         final SparseIntArray lastProcStates;
1386 
1387         // Please keep the enum lists in sync
1388         private static int[] ORIG_ENUMS = new int[]{
1389                 ActivityManager.UID_OBSERVER_IDLE,
1390                 ActivityManager.UID_OBSERVER_ACTIVE,
1391                 ActivityManager.UID_OBSERVER_GONE,
1392                 ActivityManager.UID_OBSERVER_PROCSTATE,
1393         };
1394         private static int[] PROTO_ENUMS = new int[]{
1395                 ActivityManagerProto.UID_OBSERVER_FLAG_IDLE,
1396                 ActivityManagerProto.UID_OBSERVER_FLAG_ACTIVE,
1397                 ActivityManagerProto.UID_OBSERVER_FLAG_GONE,
1398                 ActivityManagerProto.UID_OBSERVER_FLAG_PROCSTATE,
1399         };
1400 
UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint)1401         UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) {
1402             uid = _uid;
1403             pkg = _pkg;
1404             which = _which;
1405             cutpoint = _cutpoint;
1406             if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
1407                 lastProcStates = new SparseIntArray();
1408             } else {
1409                 lastProcStates = null;
1410             }
1411         }
1412 
writeToProto(ProtoOutputStream proto, long fieldId)1413         void writeToProto(ProtoOutputStream proto, long fieldId) {
1414             final long token = proto.start(fieldId);
1415             proto.write(UidObserverRegistrationProto.UID, uid);
1416             proto.write(UidObserverRegistrationProto.PACKAGE, pkg);
1417             ProtoUtils.writeBitWiseFlagsToProtoEnum(proto, UidObserverRegistrationProto.FLAGS,
1418                     which, ORIG_ENUMS, PROTO_ENUMS);
1419             proto.write(UidObserverRegistrationProto.CUT_POINT, cutpoint);
1420             if (lastProcStates != null) {
1421                 final int NI = lastProcStates.size();
1422                 for (int i=0; i<NI; i++) {
1423                     final long pToken = proto.start(UidObserverRegistrationProto.LAST_PROC_STATES);
1424                     proto.write(UidObserverRegistrationProto.ProcState.UID, lastProcStates.keyAt(i));
1425                     proto.write(UidObserverRegistrationProto.ProcState.STATE, lastProcStates.valueAt(i));
1426                     proto.end(pToken);
1427                 }
1428             }
1429             proto.end(token);
1430         }
1431     }
1432 
1433     // TODO: Move below 4 members and code to ProcessList
1434     final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>();
1435     ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
1436 
1437     final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>();
1438     final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();
1439 
1440     final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>();
1441     UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];
1442 
1443     final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>();
1444     final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>();
1445 
1446     OomAdjObserver mCurOomAdjObserver;
1447     int mCurOomAdjUid;
1448 
1449     interface OomAdjObserver {
onOomAdjMessage(String msg)1450         void onOomAdjMessage(String msg);
1451     }
1452 
1453     /**
1454      * Runtime CPU use collection thread.  This object's lock is used to
1455      * perform synchronization with the thread (notifying it to run).
1456      */
1457     final Thread mProcessCpuThread;
1458 
1459     /**
1460      * Used to collect per-process CPU use for ANRs, battery stats, etc.
1461      * Must acquire this object's lock when accessing it.
1462      * NOTE: this lock will be held while doing long operations (trawling
1463      * through all processes in /proc), so it should never be acquired by
1464      * any critical paths such as when holding the main activity manager lock.
1465      */
1466     final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1467             MONITOR_THREAD_CPU_USAGE);
1468     final AtomicLong mLastCpuTime = new AtomicLong(0);
1469     final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1470     final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1);
1471 
1472     long mLastWriteTime = 0;
1473 
1474     /** Set to true after the system has finished booting. */
1475     volatile boolean mBooted = false;
1476 
1477     /**
1478      * Current boot phase.
1479      */
1480     int mBootPhase;
1481 
1482     @VisibleForTesting
1483     public WindowManagerService mWindowManager;
1484     @VisibleForTesting
1485     public ActivityTaskManagerService mActivityTaskManager;
1486     @VisibleForTesting
1487     public ActivityTaskManagerInternal mAtmInternal;
1488     @VisibleForTesting
1489     public UriGrantsManagerInternal mUgmInternal;
1490     final ActivityThread mSystemThread;
1491 
1492     private final class AppDeathRecipient implements IBinder.DeathRecipient {
1493         final ProcessRecord mApp;
1494         final int mPid;
1495         final IApplicationThread mAppThread;
1496 
AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1497         AppDeathRecipient(ProcessRecord app, int pid,
1498                 IApplicationThread thread) {
1499             if (DEBUG_ALL) Slog.v(
1500                 TAG, "New death recipient " + this
1501                  + " for thread " + thread.asBinder());
1502             mApp = app;
1503             mPid = pid;
1504             mAppThread = thread;
1505         }
1506 
1507         @Override
binderDied()1508         public void binderDied() {
1509             if (DEBUG_ALL) Slog.v(
1510                 TAG, "Death received in " + this
1511                 + " for thread " + mAppThread.asBinder());
1512             synchronized(ActivityManagerService.this) {
1513                 appDiedLocked(mApp, mPid, mAppThread, true);
1514             }
1515         }
1516     }
1517 
1518     static final int SHOW_ERROR_UI_MSG = 1;
1519     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1520     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1521     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1522     static final int SERVICE_TIMEOUT_MSG = 12;
1523     static final int UPDATE_TIME_ZONE = 13;
1524     static final int PROC_START_TIMEOUT_MSG = 20;
1525     static final int KILL_APPLICATION_MSG = 22;
1526     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1527     static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
1528     static final int CLEAR_DNS_CACHE_MSG = 28;
1529     static final int UPDATE_HTTP_PROXY_MSG = 29;
1530     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1531     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1532     static final int REPORT_MEM_USAGE_MSG = 33;
1533     static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1534     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1535     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1536     static final int DELETE_DUMPHEAP_MSG = 51;
1537     static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53;
1538     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1539     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1540     static final int IDLE_UIDS_MSG = 58;
1541     static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1542     static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1543     static final int PUSH_TEMP_WHITELIST_UI_MSG = 68;
1544     static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1545     static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70;
1546     static final int KILL_APP_ZYGOTE_MSG = 71;
1547 
1548     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1549 
1550     static final String SERVICE_RECORD_KEY = "servicerecord";
1551 
1552     long mLastMemUsageReportTime = 0;
1553 
1554     /**
1555      * Flag whether the current user is a "monkey", i.e. whether
1556      * the UI is driven by a UI automation tool.
1557      */
1558     private boolean mUserIsMonkey;
1559 
1560     @VisibleForTesting
1561     public final ServiceThread mHandlerThread;
1562     final MainHandler mHandler;
1563     final Handler mUiHandler;
1564     final ServiceThread mProcStartHandlerThread;
1565     final Handler mProcStartHandler;
1566 
1567     ActivityManagerConstants mConstants;
1568 
1569     // Encapsulates the global setting "hidden_api_blacklist_exemptions"
1570     final HiddenApiSettings mHiddenApiBlacklist;
1571 
1572     private final PlatformCompat mPlatformCompat;
1573 
1574     PackageManagerInternal mPackageManagerInt;
1575 
1576     /**
1577      * Whether to force background check on all apps (for battery saver) or not.
1578      */
1579     boolean mForceBackgroundCheck;
1580 
1581     private static String sTheRealBuildSerial = Build.UNKNOWN;
1582 
1583     private ParcelFileDescriptor[] mLifeMonitorFds;
1584 
1585     static final HostingRecord sNullHostingRecord = new HostingRecord(null);
1586     /**
1587      * Used to notify activity lifecycle events.
1588      */
1589     @Nullable ContentCaptureManagerInternal mContentCaptureService;
1590 
1591     final class UiHandler extends Handler {
UiHandler()1592         public UiHandler() {
1593             super(com.android.server.UiThread.get().getLooper(), null, true);
1594         }
1595 
1596         @Override
handleMessage(Message msg)1597         public void handleMessage(Message msg) {
1598             switch (msg.what) {
1599             case SHOW_ERROR_UI_MSG: {
1600                 mAppErrors.handleShowAppErrorUi(msg);
1601                 ensureBootCompleted();
1602             } break;
1603             case SHOW_NOT_RESPONDING_UI_MSG: {
1604                 mAppErrors.handleShowAnrUi(msg);
1605                 ensureBootCompleted();
1606             } break;
1607             case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1608                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1609                 synchronized (ActivityManagerService.this) {
1610                     ProcessRecord proc = (ProcessRecord) data.get("app");
1611                     if (proc == null) {
1612                         Slog.e(TAG, "App not found when showing strict mode dialog.");
1613                         break;
1614                     }
1615                     if (proc.crashDialog != null) {
1616                         Slog.e(TAG, "App already has strict mode dialog: " + proc);
1617                         return;
1618                     }
1619                     AppErrorResult res = (AppErrorResult) data.get("result");
1620                     if (mAtmInternal.showStrictModeViolationDialog()) {
1621                         Dialog d = new StrictModeViolationDialog(mUiContext,
1622                                 ActivityManagerService.this, res, proc);
1623                         d.show();
1624                         proc.crashDialog = d;
1625                     } else {
1626                         // The device is asleep, so just pretend that the user
1627                         // saw a crash dialog and hit "force quit".
1628                         res.set(0);
1629                     }
1630                 }
1631                 ensureBootCompleted();
1632             } break;
1633             case WAIT_FOR_DEBUGGER_UI_MSG: {
1634                 synchronized (ActivityManagerService.this) {
1635                     ProcessRecord app = (ProcessRecord)msg.obj;
1636                     if (msg.arg1 != 0) {
1637                         if (!app.waitedForDebugger) {
1638                             Dialog d = new AppWaitingForDebuggerDialog(
1639                                     ActivityManagerService.this,
1640                                     mUiContext, app);
1641                             app.waitDialog = d;
1642                             app.waitedForDebugger = true;
1643                             d.show();
1644                         }
1645                     } else {
1646                         if (app.waitDialog != null) {
1647                             app.waitDialog.dismiss();
1648                             app.waitDialog = null;
1649                         }
1650                     }
1651                 }
1652             } break;
1653             case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1654                 dispatchProcessesChanged();
1655                 break;
1656             }
1657             case DISPATCH_PROCESS_DIED_UI_MSG: {
1658                 final int pid = msg.arg1;
1659                 final int uid = msg.arg2;
1660                 dispatchProcessDied(pid, uid);
1661                 break;
1662             }
1663             case DISPATCH_UIDS_CHANGED_UI_MSG: {
1664                 if (false) { // DO NOT SUBMIT WITH TRUE
1665                     maybeTriggerWatchdog();
1666                 }
1667                 dispatchUidsChanged();
1668             } break;
1669             case DISPATCH_OOM_ADJ_OBSERVER_MSG: {
1670                 dispatchOomAdjObserver((String)msg.obj);
1671             } break;
1672             case PUSH_TEMP_WHITELIST_UI_MSG: {
1673                 pushTempWhitelist();
1674             } break;
1675             }
1676         }
1677     }
1678 
1679     final class MainHandler extends Handler {
MainHandler(Looper looper)1680         public MainHandler(Looper looper) {
1681             super(looper, null, true);
1682         }
1683 
1684         @Override
handleMessage(Message msg)1685         public void handleMessage(Message msg) {
1686             switch (msg.what) {
1687             case GC_BACKGROUND_PROCESSES_MSG: {
1688                 synchronized (ActivityManagerService.this) {
1689                     performAppGcsIfAppropriateLocked();
1690                 }
1691             } break;
1692             case SERVICE_TIMEOUT_MSG: {
1693                 mServices.serviceTimeout((ProcessRecord)msg.obj);
1694             } break;
1695             case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1696                 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj);
1697             } break;
1698             case SERVICE_FOREGROUND_CRASH_MSG: {
1699                 mServices.serviceForegroundCrash(
1700                     (ProcessRecord) msg.obj, msg.getData().getCharSequence(SERVICE_RECORD_KEY));
1701             } break;
1702             case UPDATE_TIME_ZONE: {
1703                 synchronized (ActivityManagerService.this) {
1704                     for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) {
1705                         ProcessRecord r = mProcessList.mLruProcesses.get(i);
1706                         if (r.thread != null) {
1707                             try {
1708                                 r.thread.updateTimeZone();
1709                             } catch (RemoteException ex) {
1710                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
1711                             }
1712                         }
1713                     }
1714                 }
1715             } break;
1716             case CLEAR_DNS_CACHE_MSG: {
1717                 synchronized (ActivityManagerService.this) {
1718                     mProcessList.clearAllDnsCacheLocked();
1719                 }
1720             } break;
1721             case UPDATE_HTTP_PROXY_MSG: {
1722                 mProcessList.setAllHttpProxy();
1723             } break;
1724             case PROC_START_TIMEOUT_MSG: {
1725                 ProcessRecord app = (ProcessRecord)msg.obj;
1726                 synchronized (ActivityManagerService.this) {
1727                     processStartTimedOutLocked(app);
1728                 }
1729             } break;
1730             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1731                 ProcessRecord app = (ProcessRecord)msg.obj;
1732                 synchronized (ActivityManagerService.this) {
1733                     processContentProviderPublishTimedOutLocked(app);
1734                 }
1735             } break;
1736             case KILL_APPLICATION_MSG: {
1737                 synchronized (ActivityManagerService.this) {
1738                     final int appId = msg.arg1;
1739                     final int userId = msg.arg2;
1740                     Bundle bundle = (Bundle)msg.obj;
1741                     String pkg = bundle.getString("pkg");
1742                     String reason = bundle.getString("reason");
1743                     forceStopPackageLocked(pkg, appId, false, false, true, false,
1744                             false, userId, reason);
1745                 }
1746             } break;
1747                 case KILL_APP_ZYGOTE_MSG: {
1748                     synchronized (ActivityManagerService.this) {
1749                         final AppZygote appZygote = (AppZygote) msg.obj;
1750                         mProcessList.killAppZygoteIfNeededLocked(appZygote);
1751                     }
1752                 } break;
1753             case CHECK_EXCESSIVE_POWER_USE_MSG: {
1754                 synchronized (ActivityManagerService.this) {
1755                     checkExcessivePowerUsageLocked();
1756                     removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
1757                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
1758                     sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
1759                 }
1760             } break;
1761             case REPORT_MEM_USAGE_MSG: {
1762                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
1763                 Thread thread = new Thread() {
1764                     @Override public void run() {
1765                         reportMemUsage(memInfos);
1766                     }
1767                 };
1768                 thread.start();
1769                 break;
1770             }
1771             case UPDATE_TIME_PREFERENCE_MSG: {
1772                 // The user's time format preference might have changed.
1773                 // For convenience we re-use the Intent extra values.
1774                 synchronized (ActivityManagerService.this) {
1775                     mProcessList.updateAllTimePrefsLocked(msg.arg1);
1776                 }
1777                 break;
1778             }
1779             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1780                 final int uid = msg.arg1;
1781                 final byte[] firstPacket = (byte[]) msg.obj;
1782 
1783                 synchronized (mPidsSelfLocked) {
1784                     for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1785                         final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1786                         if (p.uid == uid && p.thread != null) {
1787                             try {
1788                                 p.thread.notifyCleartextNetwork(firstPacket);
1789                             } catch (RemoteException ignored) {
1790                             }
1791                         }
1792                     }
1793                 }
1794                 break;
1795             }
1796             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1797                 final String procName;
1798                 final int uid;
1799                 final long memLimit;
1800                 final String reportPackage;
1801                 final boolean isUserInitiated;
1802                 synchronized (ActivityManagerService.this) {
1803                     uid = mMemWatchDumpUid;
1804                     if (uid == SYSTEM_UID) {
1805                         procName = mContext.getString(R.string.android_system_label);
1806                     } else {
1807                         procName = mMemWatchDumpProcName;
1808                     }
1809                     Pair<Long, String> val = mMemWatchProcesses.get(procName, uid);
1810                     if (val == null) {
1811                         val = mMemWatchProcesses.get(procName, 0);
1812                     }
1813                     if (val != null) {
1814                         memLimit = val.first;
1815                         reportPackage = val.second;
1816                     } else {
1817                         memLimit = 0;
1818                         reportPackage = null;
1819                     }
1820                     isUserInitiated = mMemWatchIsUserInitiated;
1821                 }
1822                 if (procName == null) {
1823                     return;
1824                 }
1825 
1826                 if (DEBUG_PSS) Slog.d(TAG_PSS,
1827                         "Showing dump heap notification from " + procName + "/" + uid);
1828 
1829                 INotificationManager inm = NotificationManager.getService();
1830                 if (inm == null) {
1831                     return;
1832                 }
1833 
1834                 final int titleId = isUserInitiated
1835                         ? R.string.dump_heap_ready_notification : R.string.dump_heap_notification;
1836                 String text = mContext.getString(titleId, procName);
1837 
1838                 Intent deleteIntent = new Intent();
1839                 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
1840                 Intent intent = new Intent();
1841                 intent.setClassName("android", DumpHeapActivity.class.getName());
1842                 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName);
1843                 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit);
1844                 intent.putExtra(DumpHeapActivity.KEY_IS_USER_INITIATED, isUserInitiated);
1845                 intent.putExtra(DumpHeapActivity.KEY_IS_SYSTEM_PROCESS, uid == SYSTEM_UID);
1846                 if (reportPackage != null) {
1847                     intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage);
1848                 }
1849                 int userId = UserHandle.getUserId(uid);
1850                 Notification notification =
1851                         new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
1852                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
1853                         .setAutoCancel(true)
1854                         .setTicker(text)
1855                         .setColor(mContext.getColor(
1856                                 com.android.internal.R.color.system_notification_accent_color))
1857                         .setContentTitle(text)
1858                         .setContentText(
1859                                 mContext.getText(R.string.dump_heap_notification_detail))
1860                         .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
1861                                 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
1862                                 new UserHandle(userId)))
1863                         .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0,
1864                                 deleteIntent, 0, UserHandle.SYSTEM))
1865                         .build();
1866 
1867                 try {
1868                     inm.enqueueNotificationWithTag("android", "android", null,
1869                             SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION,
1870                             notification, userId);
1871                 } catch (RuntimeException e) {
1872                     Slog.w(ActivityManagerService.TAG,
1873                             "Error showing notification for dump heap", e);
1874                 } catch (RemoteException e) {
1875                 }
1876             } break;
1877             case DELETE_DUMPHEAP_MSG: {
1878                 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(),
1879                         null, DumpHeapActivity.JAVA_URI,
1880                         Intent.FLAG_GRANT_READ_URI_PERMISSION
1881                                 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
1882                         UserHandle.myUserId());
1883                 synchronized (ActivityManagerService.this) {
1884                     mMemWatchDumpFile = null;
1885                     mMemWatchDumpProcName = null;
1886                     mMemWatchDumpPid = -1;
1887                     mMemWatchDumpUid = -1;
1888                 }
1889             } break;
1890             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
1891                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
1892                 try {
1893                     connection.shutdown();
1894                 } catch (RemoteException e) {
1895                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
1896                 }
1897                 // Only a UiAutomation can set this flag and now that
1898                 // it is finished we make sure it is reset to its default.
1899                 mUserIsMonkey = false;
1900             } break;
1901             case IDLE_UIDS_MSG: {
1902                 idleUids();
1903             } break;
1904             case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
1905                 synchronized (ActivityManagerService.this) {
1906                     mProcessList.handleAllTrustStorageUpdateLocked();
1907                 }
1908             } break;
1909             }
1910         }
1911     }
1912 
1913     static final int COLLECT_PSS_BG_MSG = 1;
1914     static final int DEFER_PSS_MSG = 2;
1915     static final int STOP_DEFERRING_PSS_MSG = 3;
1916 
1917     final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
1918         @Override
1919         public void handleMessage(Message msg) {
1920             switch (msg.what) {
1921             case COLLECT_PSS_BG_MSG: {
1922                 long start = SystemClock.uptimeMillis();
1923                 MemInfoReader memInfo = null;
1924                 synchronized (ActivityManagerService.this) {
1925                     if (mFullPssPending) {
1926                         mFullPssPending = false;
1927                         memInfo = new MemInfoReader();
1928                     }
1929                 }
1930                 if (memInfo != null) {
1931                     updateCpuStatsNow();
1932                     long nativeTotalPss = 0;
1933                     final List<ProcessCpuTracker.Stats> stats;
1934                     synchronized (mProcessCpuTracker) {
1935                         stats = mProcessCpuTracker.getStats( (st)-> {
1936                             return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID;
1937                         });
1938                     }
1939                     final int N = stats.size();
1940                     for (int j = 0; j < N; j++) {
1941                         synchronized (mPidsSelfLocked) {
1942                             if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) {
1943                                 // This is one of our own processes; skip it.
1944                                 continue;
1945                             }
1946                         }
1947                         nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null);
1948                     }
1949                     memInfo.readMemInfo();
1950                     synchronized (ActivityManagerService.this) {
1951                         if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in "
1952                                 + (SystemClock.uptimeMillis()-start) + "ms");
1953                         final long cachedKb = memInfo.getCachedSizeKb();
1954                         final long freeKb = memInfo.getFreeSizeKb();
1955                         final long zramKb = memInfo.getZramTotalSizeKb();
1956                         final long kernelKb = memInfo.getKernelUsedSizeKb();
1957                         EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
1958                                 kernelKb*1024, nativeTotalPss*1024);
1959                         mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
1960                                 nativeTotalPss);
1961                     }
1962                 }
1963 
1964                 int num = 0;
1965                 long[] tmp = new long[3];
1966                 do {
1967                     ProcessRecord proc;
1968                     int procState;
1969                     int statType;
1970                     int pid = -1;
1971                     long lastPssTime;
1972                     synchronized (ActivityManagerService.this) {
1973                         if (mPendingPssProcesses.size() <= 0) {
1974                             if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS,
1975                                     "Collected pss of " + num + " processes in "
1976                                     + (SystemClock.uptimeMillis() - start) + "ms");
1977                             mPendingPssProcesses.clear();
1978                             return;
1979                         }
1980                         proc = mPendingPssProcesses.remove(0);
1981                         procState = proc.pssProcState;
1982                         statType = proc.pssStatType;
1983                         lastPssTime = proc.lastPssTime;
1984                         long now = SystemClock.uptimeMillis();
1985                         if (proc.thread != null && procState == proc.setProcState
1986                                 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
1987                                         < now) {
1988                             pid = proc.pid;
1989                         } else {
1990                             ProcessList.abortNextPssTime(proc.procStateMemTracker);
1991                             if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid +
1992                                     ": still need " +
1993                                     (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE-now) +
1994                                     "ms until safe");
1995                             proc = null;
1996                             pid = 0;
1997                         }
1998                     }
1999                     if (proc != null) {
2000                         long startTime = SystemClock.currentThreadTimeMillis();
2001                         long pss = Debug.getPss(pid, tmp, null);
2002                         long endTime = SystemClock.currentThreadTimeMillis();
2003                         synchronized (ActivityManagerService.this) {
2004                             if (pss != 0 && proc.thread != null && proc.setProcState == procState
2005                                     && proc.pid == pid && proc.lastPssTime == lastPssTime) {
2006                                 num++;
2007                                 ProcessList.commitNextPssTime(proc.procStateMemTracker);
2008                                 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1], tmp[2],
2009                                         statType, endTime-startTime, SystemClock.uptimeMillis());
2010                             } else {
2011                                 ProcessList.abortNextPssTime(proc.procStateMemTracker);
2012                                 if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid +
2013                                         ": " + (proc.thread == null ? "NO_THREAD " : "") +
2014                                         (proc.pid != pid ? "PID_CHANGED " : "") +
2015                                         " initState=" + procState + " curState=" +
2016                                         proc.setProcState + " " +
2017                                         (proc.lastPssTime != lastPssTime ? "TIME_CHANGED" : ""));
2018                             }
2019                         }
2020                     }
2021                 } while (true);
2022             }
2023 
2024             case DEFER_PSS_MSG: {
2025                 deferPssForActivityStart();
2026             } break;
2027 
2028             case STOP_DEFERRING_PSS_MSG: {
2029                 final int nesting = mActivityStartingNesting.decrementAndGet();
2030                 if (nesting <= 0) {
2031                     if (DEBUG_PSS) {
2032                         Slog.d(TAG_PSS, "PSS activity start deferral interval ended; now "
2033                                 + nesting);
2034                     }
2035                     if (nesting < 0) {
2036                         Slog.wtf(TAG, "Activity start nesting undercount!");
2037                         mActivityStartingNesting.incrementAndGet();
2038                     }
2039                 } else {
2040                     if (DEBUG_PSS) {
2041                         Slog.d(TAG_PSS, "Still deferring PSS, nesting=" + nesting);
2042                     }
2043                 }
2044             }
2045             break;
2046 
2047             }
2048         }
2049     };
2050 
setSystemProcess()2051     public void setSystemProcess() {
2052         try {
2053             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2054                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2055             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2056             ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2057                     DUMP_FLAG_PRIORITY_HIGH);
2058             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2059             ServiceManager.addService("dbinfo", new DbBinder(this));
2060             if (MONITOR_CPU_USAGE) {
2061                 ServiceManager.addService("cpuinfo", new CpuBinder(this),
2062                         /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2063             }
2064             ServiceManager.addService("permission", new PermissionController(this));
2065             ServiceManager.addService("processinfo", new ProcessInfoService(this));
2066 
2067             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2068                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2069             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2070 
2071             synchronized (this) {
2072                 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
2073                         false,
2074                         0,
2075                         new HostingRecord("system"));
2076                 app.setPersistent(true);
2077                 app.pid = MY_PID;
2078                 app.getWindowProcessController().setPid(MY_PID);
2079                 app.maxAdj = ProcessList.SYSTEM_ADJ;
2080                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2081                 mPidsSelfLocked.put(app);
2082                 mProcessList.updateLruProcessLocked(app, false, null);
2083                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2084             }
2085         } catch (PackageManager.NameNotFoundException e) {
2086             throw new RuntimeException(
2087                     "Unable to find android system package", e);
2088         }
2089 
2090         // Start watching app ops after we and the package manager are up and running.
2091         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2092                 new IAppOpsCallback.Stub() {
2093                     @Override public void opChanged(int op, int uid, String packageName) {
2094                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2095                             if (mAppOpsService.checkOperation(op, uid, packageName)
2096                                     != AppOpsManager.MODE_ALLOWED) {
2097                                 runInBackgroundDisabled(uid);
2098                             }
2099                         }
2100                     }
2101                 });
2102     }
2103 
setWindowManager(WindowManagerService wm)2104     public void setWindowManager(WindowManagerService wm) {
2105         synchronized (this) {
2106             mWindowManager = wm;
2107             mActivityTaskManager.setWindowManager(wm);
2108         }
2109     }
2110 
setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)2111     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2112         mUsageStatsService = usageStatsManager;
2113         mActivityTaskManager.setUsageStatsManager(usageStatsManager);
2114     }
2115 
2116     /**
2117      * Sets the internal content capture manager service.
2118      *
2119      * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock.
2120      */
setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2121     public void setContentCaptureManager(
2122             @Nullable ContentCaptureManagerInternal contentCaptureManager) {
2123         mContentCaptureService = contentCaptureManager;
2124     }
2125 
startObservingNativeCrashes()2126     public void startObservingNativeCrashes() {
2127         final NativeCrashListener ncl = new NativeCrashListener(this);
2128         ncl.start();
2129     }
2130 
getAppOpsService()2131     public IAppOpsService getAppOpsService() {
2132         return mAppOpsService;
2133     }
2134 
2135     static class MemBinder extends Binder {
2136         ActivityManagerService mActivityManagerService;
2137         private final PriorityDump.PriorityDumper mPriorityDumper =
2138                 new PriorityDump.PriorityDumper() {
2139             @Override
2140             public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args,
2141                     boolean asProto) {
2142                 dump(fd, pw, new String[] {"-a"}, asProto);
2143             }
2144 
2145             @Override
2146             public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
2147                 mActivityManagerService.dumpApplicationMemoryUsage(
2148                         fd, pw, "  ", args, false, null, asProto);
2149             }
2150         };
2151 
MemBinder(ActivityManagerService activityManagerService)2152         MemBinder(ActivityManagerService activityManagerService) {
2153             mActivityManagerService = activityManagerService;
2154         }
2155 
2156         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2157         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2158             if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2159                     "meminfo", pw)) return;
2160             PriorityDump.dump(mPriorityDumper, fd, pw, args);
2161         }
2162     }
2163 
2164     static class GraphicsBinder extends Binder {
2165         ActivityManagerService mActivityManagerService;
GraphicsBinder(ActivityManagerService activityManagerService)2166         GraphicsBinder(ActivityManagerService activityManagerService) {
2167             mActivityManagerService = activityManagerService;
2168         }
2169 
2170         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2171         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2172             if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2173                     "gfxinfo", pw)) return;
2174             mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2175         }
2176     }
2177 
2178     static class DbBinder extends Binder {
2179         ActivityManagerService mActivityManagerService;
DbBinder(ActivityManagerService activityManagerService)2180         DbBinder(ActivityManagerService activityManagerService) {
2181             mActivityManagerService = activityManagerService;
2182         }
2183 
2184         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2185         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2186             if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2187                     "dbinfo", pw)) return;
2188             mActivityManagerService.dumpDbInfo(fd, pw, args);
2189         }
2190     }
2191 
2192     static class CpuBinder extends Binder {
2193         ActivityManagerService mActivityManagerService;
2194         private final PriorityDump.PriorityDumper mPriorityDumper =
2195                 new PriorityDump.PriorityDumper() {
2196             @Override
2197             public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
2198                     boolean asProto) {
2199                 if (asProto) return;
2200                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2201                         "cpuinfo", pw)) return;
2202                 synchronized (mActivityManagerService.mProcessCpuTracker) {
2203                     pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2204                     pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2205                             SystemClock.uptimeMillis()));
2206                 }
2207             }
2208         };
2209 
CpuBinder(ActivityManagerService activityManagerService)2210         CpuBinder(ActivityManagerService activityManagerService) {
2211             mActivityManagerService = activityManagerService;
2212         }
2213 
2214         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2215         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2216             PriorityDump.dump(mPriorityDumper, fd, pw, args);
2217         }
2218     }
2219 
2220     public static final class Lifecycle extends SystemService {
2221         private final ActivityManagerService mService;
2222         private static ActivityTaskManagerService sAtm;
2223 
Lifecycle(Context context)2224         public Lifecycle(Context context) {
2225             super(context);
2226             mService = new ActivityManagerService(context, sAtm);
2227         }
2228 
startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2229         public static ActivityManagerService startService(
2230                 SystemServiceManager ssm, ActivityTaskManagerService atm) {
2231             sAtm = atm;
2232             return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2233         }
2234 
2235         @Override
onStart()2236         public void onStart() {
2237             mService.start();
2238         }
2239 
2240         @Override
onBootPhase(int phase)2241         public void onBootPhase(int phase) {
2242             mService.mBootPhase = phase;
2243             if (phase == PHASE_SYSTEM_SERVICES_READY) {
2244                 mService.mBatteryStatsService.systemServicesReady();
2245                 mService.mServices.systemServicesReady();
2246             } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
2247                 mService.startBroadcastObservers();
2248             } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2249                 mService.mPackageWatchdog.onPackagesReady();
2250             }
2251         }
2252 
2253         @Override
onCleanupUser(int userId)2254         public void onCleanupUser(int userId) {
2255             mService.mBatteryStatsService.onCleanupUser(userId);
2256         }
2257 
getService()2258         public ActivityManagerService getService() {
2259             return mService;
2260         }
2261     }
2262 
maybeLogUserspaceRebootEvent()2263     private void maybeLogUserspaceRebootEvent() {
2264         if (!UserspaceRebootLogger.shouldLogUserspaceRebootEvent()) {
2265             return;
2266         }
2267         final int userId = mUserController.getCurrentUserId();
2268         if (userId != UserHandle.USER_SYSTEM) {
2269             // Only log for user0.
2270             return;
2271         }
2272         // TODO(b/148767783): should we check all profiles under user0?
2273         UserspaceRebootLogger.logEventAsync(StorageManager.isUserKeyUnlocked(userId),
2274                 BackgroundThread.getExecutor());
2275     }
2276 
2277     /**
2278      * Encapsulates global settings related to hidden API enforcement behaviour, including tracking
2279      * the latest value via a content observer.
2280      */
2281     static class HiddenApiSettings extends ContentObserver
2282             implements DeviceConfig.OnPropertiesChangedListener {
2283 
2284         private final Context mContext;
2285         private boolean mBlacklistDisabled;
2286         private String mExemptionsStr;
2287         private List<String> mExemptions = Collections.emptyList();
2288         private int mLogSampleRate = -1;
2289         private int mStatslogSampleRate = -1;
2290         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
2291 
2292         /**
2293          * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
2294          * the range 0 to 0x10000 inclusive.
2295          *
2296          * @hide
2297          */
2298         public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE =
2299                 "hidden_api_access_log_sampling_rate";
2300 
2301         /**
2302          * Sampling rate for hidden API access event logging with statslog, as an integer in the
2303          * range 0 to 0x10000 inclusive.
2304          *
2305          * @hide
2306          */
2307         public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
2308                 "hidden_api_access_statslog_sampling_rate";
2309 
onPropertiesChanged(DeviceConfig.Properties properties)2310         public void onPropertiesChanged(DeviceConfig.Properties properties) {
2311             int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE,
2312                     mLogSampleRate);
2313             int statslogSampleRate = properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE,
2314                     mStatslogSampleRate);
2315             setSampleRates(logSampleRate, statslogSampleRate);
2316         }
2317 
setSampleRates(int logSampleRate, int statslogSampleRate)2318         private void setSampleRates(int logSampleRate, int statslogSampleRate) {
2319             if (logSampleRate >= 0 && logSampleRate <= 0x10000
2320                     && logSampleRate != mLogSampleRate) {
2321                 mLogSampleRate = logSampleRate;
2322                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
2323             }
2324 
2325             if (statslogSampleRate >= 0 && statslogSampleRate <= 0x10000
2326                     && statslogSampleRate != mStatslogSampleRate) {
2327                 mStatslogSampleRate = statslogSampleRate;
2328                 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
2329             }
2330 
2331         }
2332 
2333         /**
2334          * Set initial sampling rates from DeviceConfig. This is required after each restart,
2335          * if they never get updated.
2336          */
initializeSampleRates()2337         private void initializeSampleRates() {
2338             int logSampleRate = DeviceConfig.getInt(DeviceConfig.NAMESPACE_APP_COMPAT,
2339                     HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0);
2340             int statslogSampleRate = DeviceConfig.getInt(DeviceConfig.NAMESPACE_APP_COMPAT,
2341                     HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
2342             setSampleRates(logSampleRate, statslogSampleRate);
2343         }
2344 
HiddenApiSettings(Handler handler, Context context)2345         public HiddenApiSettings(Handler handler, Context context) {
2346             super(handler);
2347             mContext = context;
2348         }
2349 
registerObserver()2350         public void registerObserver() {
2351             mContext.getContentResolver().registerContentObserver(
2352                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
2353                     false,
2354                     this);
2355             mContext.getContentResolver().registerContentObserver(
2356                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
2357                     false,
2358                     this);
2359             initializeSampleRates();
2360             DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT,
2361                     mContext.getMainExecutor(), this);
2362             update();
2363         }
2364 
update()2365         private void update() {
2366             String exemptions = Settings.Global.getString(mContext.getContentResolver(),
2367                     Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS);
2368             if (!TextUtils.equals(exemptions, mExemptionsStr)) {
2369                 mExemptionsStr = exemptions;
2370                 if ("*".equals(exemptions)) {
2371                     mBlacklistDisabled = true;
2372                     mExemptions = Collections.emptyList();
2373                 } else {
2374                     mBlacklistDisabled = false;
2375                     mExemptions = TextUtils.isEmpty(exemptions)
2376                             ? Collections.emptyList()
2377                             : Arrays.asList(exemptions.split(","));
2378                 }
2379                 if (!ZYGOTE_PROCESS.setApiBlacklistExemptions(mExemptions)) {
2380                   Slog.e(TAG, "Failed to set API blacklist exemptions!");
2381                   // leave mExemptionsStr as is, so we don't try to send the same list again.
2382                   mExemptions = Collections.emptyList();
2383                 }
2384             }
2385             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
2386         }
2387 
getValidEnforcementPolicy(String settingsKey)2388         private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) {
2389             int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey,
2390                     ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT);
2391             if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) {
2392                 return policy;
2393             } else {
2394                 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
2395             }
2396         }
2397 
isDisabled()2398         boolean isDisabled() {
2399             return mBlacklistDisabled;
2400         }
2401 
getPolicy()2402         @HiddenApiEnforcementPolicy int getPolicy() {
2403             return mPolicy;
2404         }
2405 
onChange(boolean selfChange)2406         public void onChange(boolean selfChange) {
2407             update();
2408         }
2409     }
2410 
2411     @VisibleForTesting
ActivityManagerService(Injector injector)2412     public ActivityManagerService(Injector injector) {
2413         this(injector, null /* handlerThread */);
2414     }
2415 
2416     /**
2417      * Provides the basic functionality for activity task related tests when a handler thread is
2418      * given to initialize the dependency members.
2419      */
2420     @VisibleForTesting
ActivityManagerService(Injector injector, ServiceThread handlerThread)2421     public ActivityManagerService(Injector injector, ServiceThread handlerThread) {
2422         final boolean hasHandlerThread = handlerThread != null;
2423         mInjector = injector;
2424         mContext = mInjector.getContext();
2425         mUiContext = null;
2426         mAppErrors = null;
2427         mPackageWatchdog = null;
2428         mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */);
2429         mBatteryStatsService = null;
2430         mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null;
2431         mHandlerThread = handlerThread;
2432         mConstants = hasHandlerThread
2433                 ? new ActivityManagerConstants(mContext, this, mHandler) : null;
2434         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
2435         mPlatformCompat = null;
2436         mProcessList.init(this, activeUids, mPlatformCompat);
2437         mLowMemDetector = null;
2438         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2439 
2440         mIntentFirewall = hasHandlerThread
2441                 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null;
2442         mProcessCpuThread = null;
2443         mProcessStats = null;
2444         mProviderMap = null;
2445         // For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from
2446         // {@link ActivityStackSupervisor#cleanUpRemovedTaskLocked}.
2447         mServices = hasHandlerThread ? new ActiveServices(this) : null;
2448         mSystemThread = null;
2449         mUiHandler = injector.getUiHandler(null /* service */);
2450         mUserController = hasHandlerThread ? new UserController(this) : null;
2451         mPendingIntentController = hasHandlerThread
2452                 ? new PendingIntentController(handlerThread.getLooper(), mUserController) : null;
2453         mProcStartHandlerThread = null;
2454         mProcStartHandler = null;
2455         mHiddenApiBlacklist = null;
2456         mFactoryTest = FACTORY_TEST_OFF;
2457     }
2458 
2459     // Note: This method is invoked on the main thread but may need to attach various
2460     // handlers to other threads.  So take care to be explicit about the looper.
ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2461     public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
2462         LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2463         mInjector = new Injector();
2464         mContext = systemContext;
2465 
2466         mFactoryTest = FactoryTest.getMode();
2467         mSystemThread = ActivityThread.currentActivityThread();
2468         mUiContext = mSystemThread.getSystemUiContext();
2469 
2470         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2471 
2472         mHandlerThread = new ServiceThread(TAG,
2473                 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2474         mHandlerThread.start();
2475         mHandler = new MainHandler(mHandlerThread.getLooper());
2476         mUiHandler = mInjector.getUiHandler(this);
2477 
2478         mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2479                 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2480         mProcStartHandlerThread.start();
2481         mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
2482 
2483         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2484         final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2485         mPlatformCompat = (PlatformCompat) ServiceManager.getService(
2486                 Context.PLATFORM_COMPAT_SERVICE);
2487         mProcessList.init(this, activeUids, mPlatformCompat);
2488         mLowMemDetector = new LowMemDetector(this);
2489         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2490 
2491         // Broadcast policy parameters
2492         final BroadcastConstants foreConstants = new BroadcastConstants(
2493                 Settings.Global.BROADCAST_FG_CONSTANTS);
2494         foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2495 
2496         final BroadcastConstants backConstants = new BroadcastConstants(
2497                 Settings.Global.BROADCAST_BG_CONSTANTS);
2498         backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2499 
2500         final BroadcastConstants offloadConstants = new BroadcastConstants(
2501                 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2502         offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2503         // by default, no "slow" policy in this queue
2504         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2505 
2506         mEnableOffloadQueue = SystemProperties.getBoolean(
2507                 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
2508 
2509         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2510                 "foreground", foreConstants, false);
2511         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2512                 "background", backConstants, true);
2513         mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
2514                 "offload", offloadConstants, true);
2515         mBroadcastQueues[0] = mFgBroadcastQueue;
2516         mBroadcastQueues[1] = mBgBroadcastQueue;
2517         mBroadcastQueues[2] = mOffloadBroadcastQueue;
2518 
2519         mServices = new ActiveServices(this);
2520         mProviderMap = new ProviderMap(this);
2521         mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2522         mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2523 
2524         final File systemDir = SystemServiceManager.ensureSystemDir();
2525 
2526         // TODO: Move creation of battery stats service outside of activity manager service.
2527         mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
2528                 BackgroundThread.get().getHandler());
2529         mBatteryStatsService.getActiveStatistics().readLocked();
2530         mBatteryStatsService.scheduleWriteToDisk();
2531         mOnBattery = DEBUG_POWER ? true
2532                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2533         mBatteryStatsService.getActiveStatistics().setCallback(this);
2534         mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2535 
2536         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2537 
2538         mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2539 
2540         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2541 
2542         mUserController = new UserController(this);
2543 
2544         mPendingIntentController = new PendingIntentController(
2545                 mHandlerThread.getLooper(), mUserController);
2546 
2547         if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
2548             mUseFifoUiScheduling = true;
2549         }
2550 
2551         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2552         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2553 
2554         mActivityTaskManager = atm;
2555         mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2556                 DisplayThread.get().getLooper());
2557         mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2558 
2559         mProcessCpuThread = new Thread("CpuTracker") {
2560             @Override
2561             public void run() {
2562                 synchronized (mProcessCpuTracker) {
2563                     mProcessCpuInitLatch.countDown();
2564                     mProcessCpuTracker.init();
2565                 }
2566                 while (true) {
2567                     try {
2568                         try {
2569                             synchronized(this) {
2570                                 final long now = SystemClock.uptimeMillis();
2571                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2572                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2573                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2574                                 //        + ", write delay=" + nextWriteDelay);
2575                                 if (nextWriteDelay < nextCpuDelay) {
2576                                     nextCpuDelay = nextWriteDelay;
2577                                 }
2578                                 if (nextCpuDelay > 0) {
2579                                     mProcessCpuMutexFree.set(true);
2580                                     this.wait(nextCpuDelay);
2581                                 }
2582                             }
2583                         } catch (InterruptedException e) {
2584                         }
2585                         updateCpuStatsNow();
2586                     } catch (Exception e) {
2587                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
2588                     }
2589                 }
2590             }
2591         };
2592 
2593         mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2594 
2595         Watchdog.getInstance().addMonitor(this);
2596         Watchdog.getInstance().addThread(mHandler);
2597 
2598         // bind background threads to little cores
2599         // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2600         // make sure we've already adjusted system_server's internal view of itself first
2601         updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2602         try {
2603             Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2604                     Process.THREAD_GROUP_SYSTEM);
2605             Process.setThreadGroupAndCpuset(
2606                     mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
2607                     Process.THREAD_GROUP_SYSTEM);
2608         } catch (Exception e) {
2609             Slog.w(TAG, "Setting background thread cpuset failed");
2610         }
2611 
2612     }
2613 
setSystemServiceManager(SystemServiceManager mgr)2614     public void setSystemServiceManager(SystemServiceManager mgr) {
2615         mSystemServiceManager = mgr;
2616     }
2617 
setInstaller(Installer installer)2618     public void setInstaller(Installer installer) {
2619         mInstaller = installer;
2620     }
2621 
start()2622     private void start() {
2623         removeAllProcessGroups();
2624         mProcessCpuThread.start();
2625 
2626         mBatteryStatsService.publish();
2627         mAppOpsService.publish(mContext);
2628         Slog.d("AppOps", "AppOpsService published");
2629         LocalServices.addService(ActivityManagerInternal.class, new LocalService());
2630         mActivityTaskManager.onActivityManagerInternalAdded();
2631         mUgmInternal.onActivityManagerInternalAdded();
2632         mPendingIntentController.onActivityManagerInternalAdded();
2633         // Wait for the synchronized block started in mProcessCpuThread,
2634         // so that any other access to mProcessCpuTracker from main thread
2635         // will be blocked during mProcessCpuTracker initialization.
2636         try {
2637             mProcessCpuInitLatch.await();
2638         } catch (InterruptedException e) {
2639             Slog.wtf(TAG, "Interrupted wait during start", e);
2640             Thread.currentThread().interrupt();
2641             throw new IllegalStateException("Interrupted wait during start");
2642         }
2643     }
2644 
initPowerManagement()2645     public void initPowerManagement() {
2646         mActivityTaskManager.onInitPowerManagement();
2647         mBatteryStatsService.initPowerManagement();
2648         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2649     }
2650 
getBackgroundLaunchBroadcasts()2651     private ArraySet<String> getBackgroundLaunchBroadcasts() {
2652         if (mBackgroundLaunchBroadcasts == null) {
2653             mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2654         }
2655         return mBackgroundLaunchBroadcasts;
2656     }
2657 
2658     /**
2659      * Ensures that the given package name has an explicit set of allowed associations.
2660      * If it does not, give it an empty set.
2661      */
requireAllowedAssociationsLocked(String packageName)2662     void requireAllowedAssociationsLocked(String packageName) {
2663         ensureAllowedAssociations();
2664         if (mAllowedAssociations.get(packageName) == null) {
2665             mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName,
2666                     new ArraySet<>(), /* isDebuggable = */ false));
2667         }
2668     }
2669 
2670     /**
2671      * Returns true if the package {@code pkg1} running under user handle {@code uid1} is
2672      * allowed association with the package {@code pkg2} running under user handle {@code uid2}.
2673      * <p> If either of the packages are running as  part of the core system, then the
2674      * association is implicitly allowed.
2675      */
validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2676     boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) {
2677         ensureAllowedAssociations();
2678         // Interactions with the system uid are always allowed, since that is the core system
2679         // that everyone needs to be able to interact with. Also allow reflexive associations
2680         // within the same uid.
2681         if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID
2682                 || UserHandle.getAppId(uid2) == SYSTEM_UID) {
2683             return true;
2684         }
2685 
2686         // Check for association on both source and target packages.
2687         PackageAssociationInfo pai = mAllowedAssociations.get(pkg1);
2688         if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) {
2689             return false;
2690         }
2691         pai = mAllowedAssociations.get(pkg2);
2692         if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) {
2693             return false;
2694         }
2695         // If no explicit associations are provided in the manifest, then assume the app is
2696         // allowed associations with any package.
2697         return true;
2698     }
2699 
2700     /** Sets up allowed associations for system prebuilt packages from system config (if needed). */
ensureAllowedAssociations()2701     private void ensureAllowedAssociations() {
2702         if (mAllowedAssociations == null) {
2703             ArrayMap<String, ArraySet<String>> allowedAssociations =
2704                     SystemConfig.getInstance().getAllowedAssociations();
2705             mAllowedAssociations = new ArrayMap<>(allowedAssociations.size());
2706             PackageManagerInternal pm = getPackageManagerInternalLocked();
2707             for (int i = 0; i < allowedAssociations.size(); i++) {
2708                 final String pkg = allowedAssociations.keyAt(i);
2709                 final ArraySet<String> asc = allowedAssociations.valueAt(i);
2710 
2711                 // Query latest debuggable flag from package-manager.
2712                 boolean isDebuggable = false;
2713                 try {
2714                     ApplicationInfo ai = AppGlobals.getPackageManager()
2715                             .getApplicationInfo(pkg, MATCH_ALL, 0);
2716                     if (ai != null) {
2717                         isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2718                     }
2719                 } catch (RemoteException e) {
2720                     /* ignore */
2721                 }
2722                 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable));
2723             }
2724         }
2725     }
2726 
2727     /** Updates allowed associations for app info (specifically, based on debuggability).  */
updateAssociationForApp(ApplicationInfo appInfo)2728     private void updateAssociationForApp(ApplicationInfo appInfo) {
2729         ensureAllowedAssociations();
2730         PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName);
2731         if (pai != null) {
2732             pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
2733         }
2734     }
2735 
2736     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)2737     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2738             throws RemoteException {
2739         if (code == SYSPROPS_TRANSACTION) {
2740             // We need to tell all apps about the system property change.
2741             ArrayList<IBinder> procs = new ArrayList<IBinder>();
2742             synchronized (this) {
2743                 final int NP = mProcessList.mProcessNames.getMap().size();
2744                 for (int ip = 0; ip < NP; ip++) {
2745                     SparseArray<ProcessRecord> apps =
2746                             mProcessList.mProcessNames.getMap().valueAt(ip);
2747                     final int NA = apps.size();
2748                     for (int ia = 0; ia < NA; ia++) {
2749                         ProcessRecord app = apps.valueAt(ia);
2750                         if (app.thread != null) {
2751                             procs.add(app.thread.asBinder());
2752                         }
2753                     }
2754                 }
2755             }
2756 
2757             int N = procs.size();
2758             for (int i=0; i<N; i++) {
2759                 Parcel data2 = Parcel.obtain();
2760                 try {
2761                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2762                             Binder.FLAG_ONEWAY);
2763                 } catch (RemoteException e) {
2764                 }
2765                 data2.recycle();
2766             }
2767         }
2768         try {
2769             return super.onTransact(code, data, reply, flags);
2770         } catch (RuntimeException e) {
2771             // The activity manager only throws certain exceptions intentionally, so let's
2772             // log all others.
2773             if (!(e instanceof SecurityException
2774                     || e instanceof IllegalArgumentException
2775                     || e instanceof IllegalStateException)) {
2776                 Slog.wtf(TAG, "Activity Manager Crash."
2777                         + " UID:" + Binder.getCallingUid()
2778                         + " PID:" + Binder.getCallingPid()
2779                         + " TRANS:" + code, e);
2780             }
2781             throw e;
2782         }
2783     }
2784 
updateCpuStats()2785     void updateCpuStats() {
2786         final long now = SystemClock.uptimeMillis();
2787         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2788             return;
2789         }
2790         if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2791             synchronized (mProcessCpuThread) {
2792                 mProcessCpuThread.notify();
2793             }
2794         }
2795     }
2796 
updateCpuStatsNow()2797     void updateCpuStatsNow() {
2798         synchronized (mProcessCpuTracker) {
2799             mProcessCpuMutexFree.set(false);
2800             final long now = SystemClock.uptimeMillis();
2801             boolean haveNewCpuStats = false;
2802 
2803             if (MONITOR_CPU_USAGE &&
2804                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2805                 mLastCpuTime.set(now);
2806                 mProcessCpuTracker.update();
2807                 if (mProcessCpuTracker.hasGoodLastStats()) {
2808                     haveNewCpuStats = true;
2809                     //Slog.i(TAG, mProcessCpu.printCurrentState());
2810                     //Slog.i(TAG, "Total CPU usage: "
2811                     //        + mProcessCpu.getTotalCpuPercent() + "%");
2812 
2813                     // Slog the cpu usage if the property is set.
2814                     if ("true".equals(SystemProperties.get("events.cpu"))) {
2815                         int user = mProcessCpuTracker.getLastUserTime();
2816                         int system = mProcessCpuTracker.getLastSystemTime();
2817                         int iowait = mProcessCpuTracker.getLastIoWaitTime();
2818                         int irq = mProcessCpuTracker.getLastIrqTime();
2819                         int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2820                         int idle = mProcessCpuTracker.getLastIdleTime();
2821 
2822                         int total = user + system + iowait + irq + softIrq + idle;
2823                         if (total == 0) total = 1;
2824 
2825                         EventLog.writeEvent(EventLogTags.CPU,
2826                                 ((user+system+iowait+irq+softIrq) * 100) / total,
2827                                 (user * 100) / total,
2828                                 (system * 100) / total,
2829                                 (iowait * 100) / total,
2830                                 (irq * 100) / total,
2831                                 (softIrq * 100) / total);
2832                     }
2833                 }
2834             }
2835 
2836             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
2837             synchronized(bstats) {
2838                 synchronized(mPidsSelfLocked) {
2839                     if (haveNewCpuStats) {
2840                         if (bstats.startAddingCpuLocked()) {
2841                             int totalUTime = 0;
2842                             int totalSTime = 0;
2843                             final int N = mProcessCpuTracker.countStats();
2844                             for (int i=0; i<N; i++) {
2845                                 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
2846                                 if (!st.working) {
2847                                     continue;
2848                                 }
2849                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
2850                                 totalUTime += st.rel_utime;
2851                                 totalSTime += st.rel_stime;
2852                                 if (pr != null) {
2853                                     BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
2854                                     if (ps == null || !ps.isActive()) {
2855                                         pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
2856                                                 pr.info.uid, pr.processName);
2857                                     }
2858                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2859                                     pr.curCpuTime += st.rel_utime + st.rel_stime;
2860                                     if (pr.lastCpuTime == 0) {
2861                                         pr.lastCpuTime = pr.curCpuTime;
2862                                     }
2863                                 } else {
2864                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
2865                                     if (ps == null || !ps.isActive()) {
2866                                         st.batteryStats = ps = bstats.getProcessStatsLocked(
2867                                                 bstats.mapUid(st.uid), st.name);
2868                                     }
2869                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2870                                 }
2871                             }
2872                             final int userTime = mProcessCpuTracker.getLastUserTime();
2873                             final int systemTime = mProcessCpuTracker.getLastSystemTime();
2874                             final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime();
2875                             final int irqTime = mProcessCpuTracker.getLastIrqTime();
2876                             final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime();
2877                             final int idleTime = mProcessCpuTracker.getLastIdleTime();
2878                             bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime,
2879                                     systemTime, iowaitTime, irqTime, softIrqTime, idleTime);
2880                         }
2881                     }
2882                 }
2883 
2884                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2885                     mLastWriteTime = now;
2886                     mBatteryStatsService.scheduleWriteToDisk();
2887                 }
2888             }
2889         }
2890     }
2891 
2892     @Override
batteryNeedsCpuUpdate()2893     public void batteryNeedsCpuUpdate() {
2894         updateCpuStatsNow();
2895     }
2896 
2897     @Override
batteryPowerChanged(boolean onBattery)2898     public void batteryPowerChanged(boolean onBattery) {
2899         // When plugging in, update the CPU stats first before changing
2900         // the plug state.
2901         updateCpuStatsNow();
2902         synchronized (this) {
2903             synchronized(mPidsSelfLocked) {
2904                 mOnBattery = DEBUG_POWER ? true : onBattery;
2905             }
2906             mOomAdjProfiler.batteryPowerChanged(onBattery);
2907         }
2908     }
2909 
2910     @Override
batteryStatsReset()2911     public void batteryStatsReset() {
2912         mOomAdjProfiler.reset();
2913     }
2914 
2915     @Override
batterySendBroadcast(Intent intent)2916     public void batterySendBroadcast(Intent intent) {
2917         synchronized (this) {
2918             broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
2919                     OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
2920                     Binder.getCallingPid(), UserHandle.USER_ALL);
2921         }
2922     }
2923 
2924     /**
2925      * Initialize the application bind args. These are passed to each
2926      * process when the bindApplication() IPC is sent to the process. They're
2927      * lazily setup to make sure the services are running when they're asked for.
2928      */
getCommonServicesLocked(boolean isolated)2929     private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
2930         // Isolated processes won't get this optimization, so that we don't
2931         // violate the rules about which services they have access to.
2932         if (isolated) {
2933             if (mIsolatedAppBindArgs == null) {
2934                 mIsolatedAppBindArgs = new ArrayMap<>(1);
2935                 addServiceToMap(mIsolatedAppBindArgs, "package");
2936             }
2937             return mIsolatedAppBindArgs;
2938         }
2939 
2940         if (mAppBindArgs == null) {
2941             mAppBindArgs = new ArrayMap<>();
2942 
2943             // Add common services.
2944             // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too.
2945             // Enable the check in ApplicationThread.bindApplication() to make sure.
2946             addServiceToMap(mAppBindArgs, "package");
2947             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
2948             addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE);
2949             addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE);
2950             addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE);
2951             addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE);
2952             addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE);
2953             addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
2954             addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
2955             addServiceToMap(mAppBindArgs, "graphicsstats");
2956             addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
2957             addServiceToMap(mAppBindArgs, "content");
2958             addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
2959             addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
2960             addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
2961             addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
2962             addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
2963             addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
2964             addServiceToMap(mAppBindArgs, "mount");
2965         }
2966         return mAppBindArgs;
2967     }
2968 
addServiceToMap(ArrayMap<String, IBinder> map, String name)2969     private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) {
2970         final IBinder service = ServiceManager.getService(name);
2971         if (service != null) {
2972             map.put(name, service);
2973             if (false) {
2974                 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache.");
2975             }
2976         }
2977     }
2978 
2979     @Override
setFocusedStack(int stackId)2980     public void setFocusedStack(int stackId) {
2981         mActivityTaskManager.setFocusedStack(stackId);
2982     }
2983 
2984     /** Sets the task stack listener that gets callbacks when a task stack changes. */
2985     @Override
registerTaskStackListener(ITaskStackListener listener)2986     public void registerTaskStackListener(ITaskStackListener listener) {
2987         mActivityTaskManager.registerTaskStackListener(listener);
2988     }
2989 
2990     /**
2991      * Unregister a task stack listener so that it stops receiving callbacks.
2992      */
2993     @Override
unregisterTaskStackListener(ITaskStackListener listener)2994     public void unregisterTaskStackListener(ITaskStackListener listener) {
2995         mActivityTaskManager.unregisterTaskStackListener(listener);
2996     }
2997 
updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2998     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2999             ProcessRecord client) {
3000         mProcessList.updateLruProcessLocked(app, activityChange, client);
3001     }
3002 
removeLruProcessLocked(ProcessRecord app)3003     final void removeLruProcessLocked(ProcessRecord app) {
3004         mProcessList.removeLruProcessLocked(app);
3005     }
3006 
getProcessRecordLocked(String processName, int uid, boolean keepIfLarge)3007     final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
3008         return mProcessList.getProcessRecordLocked(processName, uid, keepIfLarge);
3009     }
3010 
getProcessNames()3011     final ProcessMap<ProcessRecord> getProcessNames() {
3012         return mProcessList.mProcessNames;
3013     }
3014 
notifyPackageUse(String packageName, int reason)3015     void notifyPackageUse(String packageName, int reason) {
3016         synchronized(this) {
3017             getPackageManagerInternalLocked().notifyPackageUse(packageName, reason);
3018         }
3019     }
3020 
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)3021     boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
3022             String processName, String abiOverride, int uid, Runnable crashHandler) {
3023         synchronized(this) {
3024             ApplicationInfo info = new ApplicationInfo();
3025             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
3026             // For isolated processes, the former contains the parent's uid and the latter the
3027             // actual uid of the isolated process.
3028             // In the special case introduced by this method (which is, starting an isolated
3029             // process directly from the SystemServer without an actual parent app process) the
3030             // closest thing to a parent's uid is SYSTEM_UID.
3031             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
3032             // the |isolated| logic in the ProcessRecord constructor.
3033             info.uid = SYSTEM_UID;
3034             info.processName = processName;
3035             info.className = entryPoint;
3036             info.packageName = "android";
3037             info.seInfoUser = SELinuxUtil.COMPLETE_STR;
3038             info.targetSdkVersion = Build.VERSION.SDK_INT;
3039             ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */,
3040                     false /* knownToBeDead */, 0 /* intentFlags */,
3041                     sNullHostingRecord  /* hostingRecord */, ZYGOTE_POLICY_FLAG_EMPTY,
3042                     true /* allowWhileBooting */, true /* isolated */,
3043                     uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
3044                     crashHandler);
3045             return proc != null;
3046         }
3047     }
3048 
3049     @GuardedBy("this")
startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge)3050     final ProcessRecord startProcessLocked(String processName,
3051             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3052             HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
3053             boolean isolated, boolean keepIfLarge) {
3054         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
3055                 hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
3056                 keepIfLarge, null /* ABI override */, null /* entryPoint */,
3057                 null /* entryPointArgs */, null /* crashHandler */);
3058     }
3059 
isAllowedWhileBooting(ApplicationInfo ai)3060     boolean isAllowedWhileBooting(ApplicationInfo ai) {
3061         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
3062     }
3063 
3064     /**
3065      * Update battery stats on the activity' usage.
3066      * @param activity
3067      * @param uid
3068      * @param userId
3069      * @param resumed
3070      */
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)3071     void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) {
3072         if (DEBUG_SWITCH) {
3073             Slog.d(TAG_SWITCH,
3074                     "updateBatteryStats: comp=" + activity + "res=" + resumed);
3075         }
3076         final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3077         StatsLog.write(StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED,
3078                 uid, activity.getPackageName(), activity.getShortClassName(),
3079                 resumed ? StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__FOREGROUND :
3080                         StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__BACKGROUND);
3081         synchronized (stats) {
3082             if (resumed) {
3083                 stats.noteActivityResumedLocked(uid);
3084             } else {
3085                 stats.noteActivityPausedLocked(uid);
3086             }
3087         }
3088     }
3089 
3090     /**
3091      * Update UsageStas on the activity's usage.
3092      * @param activity
3093      * @param userId
3094      * @param event
3095      * @param appToken ActivityRecord's appToken.
3096      * @param taskRoot TaskRecord's root
3097      */
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)3098     public void updateActivityUsageStats(ComponentName activity, int userId, int event,
3099             IBinder appToken, ComponentName taskRoot) {
3100         if (DEBUG_SWITCH) {
3101             Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp="
3102                     + activity + " hash=" + appToken.hashCode() + " event=" + event);
3103         }
3104         synchronized (this) {
3105             if (mUsageStatsService != null) {
3106                 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(),
3107                         taskRoot);
3108             }
3109         }
3110         if (mContentCaptureService != null && (event == Event.ACTIVITY_PAUSED
3111                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED
3112                 || event == Event.ACTIVITY_DESTROYED)) {
3113             mContentCaptureService.notifyActivityEvent(userId, activity, event);
3114         }
3115     }
3116 
3117     /**
3118      * Update UsageStats on this package's usage.
3119      * @param packageName
3120      * @param userId
3121      * @param event
3122      */
updateActivityUsageStats(String packageName, int userId, int event)3123     public void updateActivityUsageStats(String packageName, int userId, int event) {
3124         if (DEBUG_SWITCH) {
3125             Slog.d(TAG_SWITCH, "updateActivityUsageStats: package="
3126                     + packageName + " event=" + event);
3127         }
3128         synchronized (this) {
3129             if (mUsageStatsService != null) {
3130                 mUsageStatsService.reportEvent(packageName, userId, event);
3131             }
3132         }
3133     }
3134 
3135     /**
3136      * Update Usages on this foreground service's usage.
3137      * @param service
3138      * @param userId
3139      * @param started
3140      */
updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3141     void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) {
3142         if (DEBUG_SWITCH) {
3143             Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp="
3144                     + service + " started=" + started);
3145         }
3146         synchronized (this) {
3147             if (mUsageStatsService != null) {
3148                 mUsageStatsService.reportEvent(service, userId,
3149                         started ? UsageEvents.Event.FOREGROUND_SERVICE_START
3150                                 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null);
3151             }
3152         }
3153     }
3154 
compatibilityInfoForPackage(ApplicationInfo ai)3155     CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
3156         return mAtmInternal.compatibilityInfoForPackage(ai);
3157     }
3158 
enforceNotIsolatedCaller(String caller)3159     private void enforceNotIsolatedCaller(String caller) {
3160         if (UserHandle.isIsolated(Binder.getCallingUid())) {
3161             throw new SecurityException("Isolated process not allowed to call " + caller);
3162         }
3163     }
3164 
3165     @Override
setPackageScreenCompatMode(String packageName, int mode)3166     public void setPackageScreenCompatMode(String packageName, int mode) {
3167         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
3168     }
3169 
hasUsageStatsPermission(String callingPackage)3170     private boolean hasUsageStatsPermission(String callingPackage) {
3171         final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS,
3172                 Binder.getCallingUid(), callingPackage);
3173         if (mode == AppOpsManager.MODE_DEFAULT) {
3174             return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3175                     == PackageManager.PERMISSION_GRANTED;
3176         }
3177         return mode == AppOpsManager.MODE_ALLOWED;
3178     }
3179 
3180     @Override
getPackageProcessState(String packageName, String callingPackage)3181     public int getPackageProcessState(String packageName, String callingPackage) {
3182         if (!hasUsageStatsPermission(callingPackage)) {
3183             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
3184                     "getPackageProcessState");
3185         }
3186 
3187         int procState = PROCESS_STATE_NONEXISTENT;
3188         synchronized (this) {
3189             for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) {
3190                 final ProcessRecord proc = mProcessList.mLruProcesses.get(i);
3191                 if (procState > proc.setProcState) {
3192                     if (proc.pkgList.containsKey(packageName) ||
3193                             (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) {
3194                         procState = proc.setProcState;
3195                     }
3196                 }
3197             }
3198         }
3199         return procState;
3200     }
3201 
3202     @Override
setProcessMemoryTrimLevel(String process, int userId, int level)3203     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
3204             throws RemoteException {
3205         synchronized (this) {
3206             final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
3207             if (app == null) {
3208                 throw new IllegalArgumentException("Unknown process: " + process);
3209             }
3210             if (app.thread == null) {
3211                 throw new IllegalArgumentException("Process has no app thread");
3212             }
3213             if (app.trimMemoryLevel >= level) {
3214                 throw new IllegalArgumentException(
3215                         "Unable to set a higher trim level than current level");
3216             }
3217             if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
3218                     app.getCurProcState() > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) {
3219                 throw new IllegalArgumentException("Unable to set a background trim level "
3220                     + "on a foreground process");
3221             }
3222             app.thread.scheduleTrimMemory(level);
3223             app.trimMemoryLevel = level;
3224             return true;
3225         }
3226     }
3227 
dispatchProcessesChanged()3228     private void dispatchProcessesChanged() {
3229         int N;
3230         synchronized (this) {
3231             N = mPendingProcessChanges.size();
3232             if (mActiveProcessChanges.length < N) {
3233                 mActiveProcessChanges = new ProcessChangeItem[N];
3234             }
3235             mPendingProcessChanges.toArray(mActiveProcessChanges);
3236             mPendingProcessChanges.clear();
3237             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3238                     "*** Delivering " + N + " process changes");
3239         }
3240 
3241         int i = mProcessObservers.beginBroadcast();
3242         while (i > 0) {
3243             i--;
3244             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3245             if (observer != null) {
3246                 try {
3247                     for (int j=0; j<N; j++) {
3248                         ProcessChangeItem item = mActiveProcessChanges[j];
3249                         if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
3250                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3251                                     "ACTIVITIES CHANGED pid=" + item.pid + " uid="
3252                                     + item.uid + ": " + item.foregroundActivities);
3253                             observer.onForegroundActivitiesChanged(item.pid, item.uid,
3254                                     item.foregroundActivities);
3255                         }
3256                         if ((item.changes & ProcessChangeItem.CHANGE_FOREGROUND_SERVICES) != 0) {
3257                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3258                                     "FOREGROUND SERVICES CHANGED pid=" + item.pid + " uid="
3259                                             + item.uid + ": " + item.foregroundServiceTypes);
3260                             observer.onForegroundServicesChanged(item.pid, item.uid,
3261                                     item.foregroundServiceTypes);
3262                         }
3263                     }
3264                 } catch (RemoteException e) {
3265                 }
3266             }
3267         }
3268         mProcessObservers.finishBroadcast();
3269 
3270         synchronized (this) {
3271             for (int j=0; j<N; j++) {
3272                 mAvailProcessChanges.add(mActiveProcessChanges[j]);
3273             }
3274         }
3275     }
3276 
3277     @GuardedBy("this")
enqueueProcessChangeItemLocked(int pid, int uid)3278     ProcessChangeItem enqueueProcessChangeItemLocked(int pid, int uid) {
3279         int i = mPendingProcessChanges.size()-1;
3280         ActivityManagerService.ProcessChangeItem item = null;
3281         while (i >= 0) {
3282             item = mPendingProcessChanges.get(i);
3283             if (item.pid == pid) {
3284                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3285                         "Re-using existing item: " + item);
3286                 break;
3287             }
3288             i--;
3289         }
3290 
3291         if (i < 0) {
3292             // No existing item in pending changes; need a new one.
3293             final int NA = mAvailProcessChanges.size();
3294             if (NA > 0) {
3295                 item = mAvailProcessChanges.remove(NA-1);
3296                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3297                         "Retrieving available item: " + item);
3298             } else {
3299                 item = new ActivityManagerService.ProcessChangeItem();
3300                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3301                         "Allocating new item: " + item);
3302             }
3303             item.changes = 0;
3304             item.pid = pid;
3305             item.uid = uid;
3306             if (mPendingProcessChanges.size() == 0) {
3307                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3308                         "*** Enqueueing dispatch processes changed!");
3309                 mUiHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED_UI_MSG)
3310                         .sendToTarget();
3311             }
3312             mPendingProcessChanges.add(item);
3313         }
3314 
3315         return item;
3316     }
3317 
dispatchProcessDied(int pid, int uid)3318     private void dispatchProcessDied(int pid, int uid) {
3319         int i = mProcessObservers.beginBroadcast();
3320         while (i > 0) {
3321             i--;
3322             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3323             if (observer != null) {
3324                 try {
3325                     observer.onProcessDied(pid, uid);
3326                 } catch (RemoteException e) {
3327                 }
3328             }
3329         }
3330         mProcessObservers.finishBroadcast();
3331     }
3332 
3333     @VisibleForTesting
dispatchUidsChanged()3334     void dispatchUidsChanged() {
3335         int N;
3336         synchronized (this) {
3337             N = mPendingUidChanges.size();
3338             if (mActiveUidChanges.length < N) {
3339                 mActiveUidChanges = new UidRecord.ChangeItem[N];
3340             }
3341             for (int i=0; i<N; i++) {
3342                 final UidRecord.ChangeItem change = mPendingUidChanges.get(i);
3343                 mActiveUidChanges[i] = change;
3344                 if (change.uidRecord != null) {
3345                     change.uidRecord.pendingChange = null;
3346                     change.uidRecord = null;
3347                 }
3348             }
3349             mPendingUidChanges.clear();
3350             if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3351                     "*** Delivering " + N + " uid changes");
3352         }
3353 
3354         mUidChangeDispatchCount += N;
3355         int i = mUidObservers.beginBroadcast();
3356         while (i > 0) {
3357             i--;
3358             dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i),
3359                     (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N);
3360         }
3361         mUidObservers.finishBroadcast();
3362 
3363         if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) {
3364             for (int j = 0; j < N; ++j) {
3365                 final UidRecord.ChangeItem item = mActiveUidChanges[j];
3366                 if ((item.change & UidRecord.CHANGE_GONE) != 0) {
3367                     mValidateUids.remove(item.uid);
3368                 } else {
3369                     UidRecord validateUid = mValidateUids.get(item.uid);
3370                     if (validateUid == null) {
3371                         validateUid = new UidRecord(item.uid);
3372                         mValidateUids.put(item.uid, validateUid);
3373                     }
3374                     if ((item.change & UidRecord.CHANGE_IDLE) != 0) {
3375                         validateUid.idle = true;
3376                     } else if ((item.change & UidRecord.CHANGE_ACTIVE) != 0) {
3377                         validateUid.idle = false;
3378                     }
3379                     validateUid.setCurProcState(validateUid.setProcState = item.processState);
3380                     validateUid.lastDispatchedProcStateSeq = item.procStateSeq;
3381                 }
3382             }
3383         }
3384 
3385         synchronized (this) {
3386             for (int j = 0; j < N; j++) {
3387                 mAvailUidChanges.add(mActiveUidChanges[j]);
3388             }
3389         }
3390     }
3391 
dispatchUidsChangedForObserver(IUidObserver observer, UidObserverRegistration reg, int changesSize)3392     private void dispatchUidsChangedForObserver(IUidObserver observer,
3393             UidObserverRegistration reg, int changesSize) {
3394         if (observer == null) {
3395             return;
3396         }
3397         try {
3398             for (int j = 0; j < changesSize; j++) {
3399                 UidRecord.ChangeItem item = mActiveUidChanges[j];
3400                 final int change = item.change;
3401                 if (change == UidRecord.CHANGE_PROCSTATE &&
3402                         (reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) == 0) {
3403                     // No-op common case: no significant change, the observer is not
3404                     // interested in all proc state changes.
3405                     continue;
3406                 }
3407                 final long start = SystemClock.uptimeMillis();
3408                 if ((change & UidRecord.CHANGE_IDLE) != 0) {
3409                     if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) {
3410                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3411                                 "UID idle uid=" + item.uid);
3412                         observer.onUidIdle(item.uid, item.ephemeral);
3413                     }
3414                 } else if ((change & UidRecord.CHANGE_ACTIVE) != 0) {
3415                     if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
3416                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3417                                 "UID active uid=" + item.uid);
3418                         observer.onUidActive(item.uid);
3419                     }
3420                 }
3421                 if ((reg.which & ActivityManager.UID_OBSERVER_CACHED) != 0) {
3422                     if ((change & UidRecord.CHANGE_CACHED) != 0) {
3423                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3424                                 "UID cached uid=" + item.uid);
3425                         observer.onUidCachedChanged(item.uid, true);
3426                     } else if ((change & UidRecord.CHANGE_UNCACHED) != 0) {
3427                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3428                                 "UID active uid=" + item.uid);
3429                         observer.onUidCachedChanged(item.uid, false);
3430                     }
3431                 }
3432                 if ((change & UidRecord.CHANGE_GONE) != 0) {
3433                     if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) {
3434                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3435                                 "UID gone uid=" + item.uid);
3436                         observer.onUidGone(item.uid, item.ephemeral);
3437                     }
3438                     if (reg.lastProcStates != null) {
3439                         reg.lastProcStates.delete(item.uid);
3440                     }
3441                 } else {
3442                     if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
3443                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3444                                 "UID CHANGED uid=" + item.uid
3445                                         + ": " + item.processState);
3446                         boolean doReport = true;
3447                         if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
3448                             final int lastState = reg.lastProcStates.get(item.uid,
3449                                     ActivityManager.PROCESS_STATE_UNKNOWN);
3450                             if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) {
3451                                 final boolean lastAboveCut = lastState <= reg.cutpoint;
3452                                 final boolean newAboveCut = item.processState <= reg.cutpoint;
3453                                 doReport = lastAboveCut != newAboveCut;
3454                             } else {
3455                                 doReport = item.processState != PROCESS_STATE_NONEXISTENT;
3456                             }
3457                         }
3458                         if (doReport) {
3459                             if (reg.lastProcStates != null) {
3460                                 reg.lastProcStates.put(item.uid, item.processState);
3461                             }
3462                             observer.onUidStateChanged(item.uid, item.processState,
3463                                     item.procStateSeq);
3464                         }
3465                     }
3466                 }
3467                 final int duration = (int) (SystemClock.uptimeMillis() - start);
3468                 if (reg.mMaxDispatchTime < duration) {
3469                     reg.mMaxDispatchTime = duration;
3470                 }
3471                 if (duration >= SLOW_UID_OBSERVER_THRESHOLD_MS) {
3472                     reg.mSlowDispatchCount++;
3473                 }
3474             }
3475         } catch (RemoteException e) {
3476         }
3477     }
3478 
dispatchOomAdjObserver(String msg)3479     void dispatchOomAdjObserver(String msg) {
3480         OomAdjObserver observer;
3481         synchronized (this) {
3482             observer = mCurOomAdjObserver;
3483         }
3484 
3485         if (observer != null) {
3486             observer.onOomAdjMessage(msg);
3487         }
3488     }
3489 
setOomAdjObserver(int uid, OomAdjObserver observer)3490     void setOomAdjObserver(int uid, OomAdjObserver observer) {
3491         synchronized (this) {
3492             mCurOomAdjUid = uid;
3493             mCurOomAdjObserver = observer;
3494         }
3495     }
3496 
clearOomAdjObserver()3497     void clearOomAdjObserver() {
3498         synchronized (this) {
3499             mCurOomAdjUid = -1;
3500             mCurOomAdjObserver = null;
3501         }
3502     }
3503 
reportOomAdjMessageLocked(String tag, String msg)3504     void reportOomAdjMessageLocked(String tag, String msg) {
3505         Slog.d(tag, msg);
3506         if (mCurOomAdjObserver != null) {
3507             mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3508         }
3509     }
3510 
reportUidInfoMessageLocked(String tag, String msg, int uid)3511     void reportUidInfoMessageLocked(String tag, String msg, int uid) {
3512         Slog.i(TAG, msg);
3513         if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) {
3514             mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3515         }
3516 
3517     }
3518 
3519     @Override
startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3520     public int startActivity(IApplicationThread caller, String callingPackage,
3521             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3522             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
3523         return mActivityTaskManager.startActivity(caller, callingPackage, intent, resolvedType,
3524                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3525     }
3526 
3527     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3528     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3529             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3530             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3531 
3532             return mActivityTaskManager.startActivityAsUser(caller, callingPackage, intent,
3533                     resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo,
3534                     bOptions, userId);
3535     }
3536 
startActivityAndWait(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3537     WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3538             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3539             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3540             return mActivityTaskManager.startActivityAndWait(caller, callingPackage, intent,
3541                     resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo,
3542                     bOptions, userId);
3543     }
3544 
3545     @Override
startActivityFromRecents(int taskId, Bundle bOptions)3546     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
3547         return mActivityTaskManager.startActivityFromRecents(taskId, bOptions);
3548     }
3549 
3550     @Override
startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver, IRecentsAnimationRunner recentsAnimationRunner)3551     public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
3552             IRecentsAnimationRunner recentsAnimationRunner) {
3553         mActivityTaskManager.startRecentsActivity(
3554                 intent, assistDataReceiver, recentsAnimationRunner);
3555     }
3556 
3557     @Override
cancelRecentsAnimation(boolean restoreHomeStackPosition)3558     public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
3559         mActivityTaskManager.cancelRecentsAnimation(restoreHomeStackPosition);
3560     }
3561 
3562     /**
3563      * This is the internal entry point for handling Activity.finish().
3564      *
3565      * @param token The Binder token referencing the Activity we want to finish.
3566      * @param resultCode Result code, if any, from this Activity.
3567      * @param resultData Result data (Intent), if any, from this Activity.
3568      * @param finishTask Whether to finish the task associated with this Activity.
3569      *
3570      * @return Returns true if the activity successfully finished, or false if it is still running.
3571      */
3572     @Override
finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3573     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
3574             int finishTask) {
3575         return mActivityTaskManager.finishActivity(token, resultCode, resultData, finishTask);
3576     }
3577 
3578     @Override
setRequestedOrientation(IBinder token, int requestedOrientation)3579     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
3580         mActivityTaskManager.setRequestedOrientation(token, requestedOrientation);
3581     }
3582 
3583     @Override
finishHeavyWeightApp()3584     public final void finishHeavyWeightApp() {
3585         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3586                 != PackageManager.PERMISSION_GRANTED) {
3587             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3588                     + Binder.getCallingPid()
3589                     + ", uid=" + Binder.getCallingUid()
3590                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3591             Slog.w(TAG, msg);
3592             throw new SecurityException(msg);
3593         }
3594         mAtmInternal.finishHeavyWeightApp();
3595     }
3596 
3597     @Override
crashApplication(int uid, int initialPid, String packageName, int userId, String message, boolean force)3598     public void crashApplication(int uid, int initialPid, String packageName, int userId,
3599             String message, boolean force) {
3600         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3601                 != PackageManager.PERMISSION_GRANTED) {
3602             String msg = "Permission Denial: crashApplication() from pid="
3603                     + Binder.getCallingPid()
3604                     + ", uid=" + Binder.getCallingUid()
3605                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3606             Slog.w(TAG, msg);
3607             throw new SecurityException(msg);
3608         }
3609 
3610         synchronized(this) {
3611             mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId,
3612                     message, force);
3613         }
3614     }
3615 
3616     /**
3617      * Main function for removing an existing process from the activity manager
3618      * as a result of that process going away.  Clears out all connections
3619      * to the process.
3620      */
3621     @GuardedBy("this")
handleAppDiedLocked(ProcessRecord app, boolean restarting, boolean allowRestart)3622     final void handleAppDiedLocked(ProcessRecord app,
3623             boolean restarting, boolean allowRestart) {
3624         int pid = app.pid;
3625         boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
3626                 false /*replacingPid*/);
3627         if (!kept && !restarting) {
3628             removeLruProcessLocked(app);
3629             if (pid > 0) {
3630                 ProcessList.remove(pid);
3631             }
3632         }
3633 
3634         if (mProfileData.getProfileProc() == app) {
3635             clearProfilerLocked();
3636         }
3637 
3638         mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
3639             Slog.w(TAG, "Crash of app " + app.processName
3640                     + " running instrumentation " + app.getActiveInstrumentation().mClass);
3641             Bundle info = new Bundle();
3642             info.putString("shortMsg", "Process crashed.");
3643             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3644         });
3645     }
3646 
getRecordForAppLocked(IApplicationThread thread)3647     ProcessRecord getRecordForAppLocked(IApplicationThread thread) {
3648         if (thread == null) {
3649             return null;
3650         }
3651 
3652         ProcessRecord record = mProcessList.getLRURecordForAppLocked(thread);
3653         if (record != null) return record;
3654 
3655         // Validation: if it isn't in the LRU list, it shouldn't exist, but let's
3656         // double-check that.
3657         final IBinder threadBinder = thread.asBinder();
3658         final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
3659                 mProcessList.mProcessNames.getMap();
3660         for (int i = pmap.size()-1; i >= 0; i--) {
3661             final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
3662             for (int j = procs.size()-1; j >= 0; j--) {
3663                 final ProcessRecord proc = procs.valueAt(j);
3664                 if (proc.thread != null && proc.thread.asBinder() == threadBinder) {
3665                     Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
3666                             + proc);
3667                     return proc;
3668                 }
3669             }
3670         }
3671 
3672         return null;
3673     }
3674 
doLowMemReportIfNeededLocked(ProcessRecord dyingProc)3675     final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
3676         // If there are no longer any background processes running,
3677         // and the app that died was not running instrumentation,
3678         // then tell everyone we are now low on memory.
3679         if (!mProcessList.haveBackgroundProcessLocked()) {
3680             boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
3681             if (doReport) {
3682                 long now = SystemClock.uptimeMillis();
3683                 if (now < (mLastMemUsageReportTime+5*60*1000)) {
3684                     doReport = false;
3685                 } else {
3686                     mLastMemUsageReportTime = now;
3687                 }
3688             }
3689             final ArrayList<ProcessMemInfo> memInfos
3690                     = doReport ? new ArrayList<ProcessMemInfo>(mProcessList.getLruSizeLocked())
3691                     : null;
3692             EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mProcessList.getLruSizeLocked());
3693             long now = SystemClock.uptimeMillis();
3694             for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) {
3695                 ProcessRecord rec = mProcessList.mLruProcesses.get(i);
3696                 if (rec == dyingProc || rec.thread == null) {
3697                     continue;
3698                 }
3699                 if (doReport) {
3700                     memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
3701                             rec.setProcState, rec.adjType, rec.makeAdjReason()));
3702                 }
3703                 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) {
3704                     // The low memory report is overriding any current
3705                     // state for a GC request.  Make sure to do
3706                     // heavy/important/visible/foreground processes first.
3707                     if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
3708                         rec.lastRequestedGc = 0;
3709                     } else {
3710                         rec.lastRequestedGc = rec.lastLowMemory;
3711                     }
3712                     rec.reportLowMemory = true;
3713                     rec.lastLowMemory = now;
3714                     mProcessesToGc.remove(rec);
3715                     addProcessToGcListLocked(rec);
3716                 }
3717             }
3718             if (doReport) {
3719                 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
3720                 mHandler.sendMessage(msg);
3721             }
3722             scheduleAppGcsLocked();
3723         }
3724     }
3725 
3726     @GuardedBy("this")
appDiedLocked(ProcessRecord app)3727     final void appDiedLocked(ProcessRecord app) {
3728        appDiedLocked(app, app.pid, app.thread, false);
3729     }
3730 
3731     @GuardedBy("this")
appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied)3732     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
3733             boolean fromBinderDied) {
3734         // First check if this ProcessRecord is actually active for the pid.
3735         synchronized (mPidsSelfLocked) {
3736             ProcessRecord curProc = mPidsSelfLocked.get(pid);
3737             if (curProc != app) {
3738                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
3739                 return;
3740             }
3741         }
3742 
3743         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3744         synchronized (stats) {
3745             stats.noteProcessDiedLocked(app.info.uid, pid);
3746         }
3747 
3748         if (!app.killed) {
3749             if (!fromBinderDied) {
3750                 killProcessQuiet(pid);
3751             }
3752             ProcessList.killProcessGroup(app.uid, pid);
3753             app.killed = true;
3754         }
3755 
3756         // Clean up already done if the process has been re-started.
3757         if (app.pid == pid && app.thread != null &&
3758                 app.thread.asBinder() == thread.asBinder()) {
3759             boolean doLowMem = app.getActiveInstrumentation() == null;
3760             boolean doOomAdj = doLowMem;
3761             if (!app.killedByAm) {
3762                 reportUidInfoMessageLocked(TAG,
3763                         "Process " + app.processName + " (pid " + pid + ") has died: "
3764                                 + ProcessList.makeOomAdjString(app.setAdj, true) + " "
3765                                 + ProcessList.makeProcStateString(app.setProcState), app.info.uid);
3766                 mAllowLowerMemLevel = true;
3767             } else {
3768                 // Note that we always want to do oom adj to update our state with the
3769                 // new number of procs.
3770                 mAllowLowerMemLevel = false;
3771                 doLowMem = false;
3772             }
3773             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName,
3774                     app.setAdj, app.setProcState);
3775             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3776                 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
3777             handleAppDiedLocked(app, false, true);
3778 
3779             if (doOomAdj) {
3780                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
3781             }
3782             if (doLowMem) {
3783                 doLowMemReportIfNeededLocked(app);
3784             }
3785         } else if (app.pid != pid) {
3786             // A new process has already been started.
3787             reportUidInfoMessageLocked(TAG,
3788                     "Process " + app.processName + " (pid " + pid
3789                             + ") has died and restarted (pid " + app.pid + ").", app.info.uid);
3790             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
3791         } else if (DEBUG_PROCESSES) {
3792             Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
3793                     + thread.asBinder());
3794         }
3795 
3796         // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal
3797         // for pulling memory stats of other running processes when this process died.
3798         if (!hasMemcg()) {
3799             StatsLog.write(StatsLog.APP_DIED, SystemClock.elapsedRealtime());
3800         }
3801     }
3802 
3803     /**
3804      * If a stack trace dump file is configured, dump process stack traces.
3805      * @param firstPids of dalvik VM processes to dump stack traces for first
3806      * @param lastPids of dalvik VM processes to dump stack traces for last
3807      * @param nativePids optional list of native pids to dump stack crawls
3808      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids)3809     public static File dumpStackTraces(ArrayList<Integer> firstPids,
3810             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3811             ArrayList<Integer> nativePids) {
3812         ArrayList<Integer> extraPids = null;
3813 
3814         Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids);
3815 
3816         // Measure CPU usage as soon as we're called in order to get a realistic sampling
3817         // of the top users at the time of the request.
3818         if (processCpuTracker != null) {
3819             processCpuTracker.init();
3820             try {
3821                 Thread.sleep(200);
3822             } catch (InterruptedException ignored) {
3823             }
3824 
3825             processCpuTracker.update();
3826 
3827             // We'll take the stack crawls of just the top apps using CPU.
3828             final int N = processCpuTracker.countWorkingStats();
3829             extraPids = new ArrayList<>();
3830             for (int i = 0; i < N && extraPids.size() < 5; i++) {
3831                 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
3832                 if (lastPids.indexOfKey(stats.pid) >= 0) {
3833                     if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid);
3834 
3835                     extraPids.add(stats.pid);
3836                 } else {
3837                     Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: "
3838                             + stats.pid);
3839                 }
3840             }
3841         }
3842 
3843         final File tracesDir = new File(ANR_TRACE_DIR);
3844         // Each set of ANR traces is written to a separate file and dumpstate will process
3845         // all such files and add them to a captured bug report if they're recent enough.
3846         maybePruneOldTraces(tracesDir);
3847 
3848         // NOTE: We should consider creating the file in native code atomically once we've
3849         // gotten rid of the old scheme of dumping and lot of the code that deals with paths
3850         // can be removed.
3851         File tracesFile = createAnrDumpFile(tracesDir);
3852         if (tracesFile == null) {
3853             return null;
3854         }
3855 
3856         dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids);
3857         return tracesFile;
3858     }
3859 
3860     @GuardedBy("ActivityManagerService.class")
3861     private static SimpleDateFormat sAnrFileDateFormat;
3862 
createAnrDumpFile(File tracesDir)3863     private static synchronized File createAnrDumpFile(File tracesDir) {
3864         if (sAnrFileDateFormat == null) {
3865             sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
3866         }
3867 
3868         final String formattedDate = sAnrFileDateFormat.format(new Date());
3869         final File anrFile = new File(tracesDir, "anr_" + formattedDate);
3870 
3871         try {
3872             if (anrFile.createNewFile()) {
3873                 FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw-------
3874                 return anrFile;
3875             } else {
3876                 Slog.w(TAG, "Unable to create ANR dump file: createNewFile failed");
3877             }
3878         } catch (IOException ioe) {
3879             Slog.w(TAG, "Exception creating ANR dump file:", ioe);
3880         }
3881 
3882         return null;
3883     }
3884 
3885     /**
3886      * Prune all trace files that are more than a day old.
3887      *
3888      * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a
3889      * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now
3890      * since it's the system_server that creates trace files for most ANRs.
3891      */
maybePruneOldTraces(File tracesDir)3892     private static void maybePruneOldTraces(File tracesDir) {
3893         final File[] files = tracesDir.listFiles();
3894         if (files == null) return;
3895 
3896         final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64);
3897         final long now = System.currentTimeMillis();
3898         Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
3899         for (int i = 0; i < files.length; ++i) {
3900             if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) {
3901                 if (!files[i].delete()) {
3902                     Slog.w(TAG, "Unable to prune stale trace file: " + files[i]);
3903                 }
3904             }
3905         }
3906     }
3907 
3908     /**
3909      * Dump java traces for process {@code pid} to the specified file. If java trace dumping
3910      * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies
3911      * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent
3912      * attempting to obtain native traces in the case of a failure. Returns the total time spent
3913      * capturing traces.
3914      */
dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)3915     private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) {
3916         final long timeStart = SystemClock.elapsedRealtime();
3917         boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName,
3918                 (int) (timeoutMs / 1000));
3919         if (javaSuccess) {
3920             // Check that something is in the file, actually. Try-catch should not be necessary,
3921             // but better safe than sorry.
3922             try {
3923                 long size = new File(fileName).length();
3924                 if (size < JAVA_DUMP_MINIMUM_SIZE) {
3925                     Slog.w(TAG, "Successfully created Java ANR file is empty!");
3926                     javaSuccess = false;
3927                 }
3928             } catch (Exception e) {
3929                 Slog.w(TAG, "Unable to get ANR file size", e);
3930                 javaSuccess = false;
3931             }
3932         }
3933         if (!javaSuccess) {
3934             Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump.");
3935             if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName,
3936                     (NATIVE_DUMP_TIMEOUT_MS / 1000))) {
3937                 Slog.w(TAG, "Native stack dump failed!");
3938             }
3939         }
3940 
3941         return SystemClock.elapsedRealtime() - timeStart;
3942     }
3943 
dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)3944     public static void dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids,
3945             ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) {
3946 
3947         Slog.i(TAG, "Dumping to " + tracesFile);
3948 
3949         // We don't need any sort of inotify based monitoring when we're dumping traces via
3950         // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full
3951         // control of all writes to the file in question.
3952 
3953         // We must complete all stack dumps within 20 seconds.
3954         long remainingTime = 20 * 1000;
3955 
3956         // First collect all of the stacks of the most important pids.
3957         if (firstPids != null) {
3958             int num = firstPids.size();
3959             for (int i = 0; i < num; i++) {
3960                 Slog.i(TAG, "Collecting stacks for pid " + firstPids.get(i));
3961                 final long timeTaken = dumpJavaTracesTombstoned(firstPids.get(i), tracesFile,
3962                                                                 remainingTime);
3963 
3964                 remainingTime -= timeTaken;
3965                 if (remainingTime <= 0) {
3966                     Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) +
3967                            "); deadline exceeded.");
3968                     return;
3969                 }
3970 
3971                 if (DEBUG_ANR) {
3972                     Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms");
3973                 }
3974             }
3975         }
3976 
3977         // Next collect the stacks of the native pids
3978         if (nativePids != null) {
3979             for (int pid : nativePids) {
3980                 Slog.i(TAG, "Collecting stacks for native pid " + pid);
3981                 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime);
3982 
3983                 final long start = SystemClock.elapsedRealtime();
3984                 Debug.dumpNativeBacktraceToFileTimeout(
3985                         pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000));
3986                 final long timeTaken = SystemClock.elapsedRealtime() - start;
3987 
3988                 remainingTime -= timeTaken;
3989                 if (remainingTime <= 0) {
3990                     Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid +
3991                         "); deadline exceeded.");
3992                     return;
3993                 }
3994 
3995                 if (DEBUG_ANR) {
3996                     Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms");
3997                 }
3998             }
3999         }
4000 
4001         // Lastly, dump stacks for all extra PIDs from the CPU tracker.
4002         if (extraPids != null) {
4003             for (int pid : extraPids) {
4004                 Slog.i(TAG, "Collecting stacks for extra pid " + pid);
4005 
4006                 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime);
4007 
4008                 remainingTime -= timeTaken;
4009                 if (remainingTime <= 0) {
4010                     Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid +
4011                             "); deadline exceeded.");
4012                     return;
4013                 }
4014 
4015                 if (DEBUG_ANR) {
4016                     Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms");
4017                 }
4018             }
4019         }
4020         Slog.i(TAG, "Done dumping");
4021     }
4022 
4023     @Override
clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)4024     public boolean clearApplicationUserData(final String packageName, boolean keepState,
4025             final IPackageDataObserver observer, int userId) {
4026         enforceNotIsolatedCaller("clearApplicationUserData");
4027         int uid = Binder.getCallingUid();
4028         int pid = Binder.getCallingPid();
4029         final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false,
4030                 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
4031 
4032         final ApplicationInfo appInfo;
4033         final boolean isInstantApp;
4034 
4035         long callingId = Binder.clearCallingIdentity();
4036         try {
4037             IPackageManager pm = AppGlobals.getPackageManager();
4038             synchronized(this) {
4039                 // Instant packages are not protected
4040                 if (getPackageManagerInternalLocked().isPackageDataProtected(
4041                         resolvedUserId, packageName)) {
4042                     throw new SecurityException(
4043                             "Cannot clear data for a protected package: " + packageName);
4044                 }
4045 
4046                 ApplicationInfo applicationInfo = null;
4047                 try {
4048                     applicationInfo = pm.getApplicationInfo(packageName,
4049                             MATCH_UNINSTALLED_PACKAGES, resolvedUserId);
4050                 } catch (RemoteException e) {
4051                     /* ignore */
4052                 }
4053                 appInfo = applicationInfo;
4054 
4055                 final boolean clearingOwnUidData = appInfo != null && appInfo.uid == uid;
4056 
4057                 if (!clearingOwnUidData && checkComponentPermission(permission.CLEAR_APP_USER_DATA,
4058                         pid, uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
4059                     throw new SecurityException("PID " + pid + " does not have permission "
4060                             + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
4061                             + " of package " + packageName);
4062                 }
4063 
4064                 final boolean hasInstantMetadata = getPackageManagerInternalLocked()
4065                         .hasInstantApplicationMetadata(packageName, resolvedUserId);
4066                 final boolean isUninstalledAppWithoutInstantMetadata =
4067                         (appInfo == null && !hasInstantMetadata);
4068                 isInstantApp = (appInfo != null && appInfo.isInstantApp())
4069                         || hasInstantMetadata;
4070                 final boolean canAccessInstantApps = checkComponentPermission(
4071                         permission.ACCESS_INSTANT_APPS, pid, uid, -1, true)
4072                         == PackageManager.PERMISSION_GRANTED;
4073 
4074                 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp
4075                         && !canAccessInstantApps)) {
4076                     Slog.w(TAG, "Invalid packageName: " + packageName);
4077                     if (observer != null) {
4078                         try {
4079                             observer.onRemoveCompleted(packageName, false);
4080                         } catch (RemoteException e) {
4081                             Slog.i(TAG, "Observer no longer exists.");
4082                         }
4083                     }
4084                     return false;
4085                 }
4086 
4087                 if (appInfo != null) {
4088                     forceStopPackageLocked(packageName, appInfo.uid, "clear data");
4089                     mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId);
4090                 }
4091             }
4092 
4093             final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
4094                 @Override
4095                 public void onRemoveCompleted(String packageName, boolean succeeded)
4096                         throws RemoteException {
4097                     if (appInfo != null) {
4098                         synchronized (ActivityManagerService.this) {
4099                             finishForceStopPackageLocked(packageName, appInfo.uid);
4100                         }
4101                     }
4102                     final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4103                             Uri.fromParts("package", packageName, null));
4104                     intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4105                     intent.putExtra(Intent.EXTRA_UID, (appInfo != null) ? appInfo.uid : -1);
4106                     intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId);
4107                     if (isInstantApp) {
4108                         intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
4109                         broadcastIntentInPackage("android", SYSTEM_UID, uid, pid, intent, null,
4110                                 null, 0, null, null, permission.ACCESS_INSTANT_APPS, null, false,
4111                                 false, resolvedUserId, false);
4112                     } else {
4113                         broadcastIntentInPackage("android", SYSTEM_UID, uid, pid, intent, null,
4114                                 null, 0, null, null, null, null, false, false, resolvedUserId,
4115                                 false);
4116                     }
4117 
4118                     if (observer != null) {
4119                         observer.onRemoveCompleted(packageName, succeeded);
4120                     }
4121                 }
4122             };
4123 
4124             try {
4125                 // Clear application user data
4126                 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId);
4127 
4128                 if (appInfo != null) {
4129                     // Restore already established notification state and permission grants,
4130                     // so it told us to keep those intact -- it's about to emplace app data
4131                     // that is appropriate for those bits of system state.
4132                     if (!keepState) {
4133                         // Remove all permissions granted from/to this package
4134                         mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId,
4135                                 true, false);
4136 
4137                         // Reset notification state
4138                         INotificationManager inm = NotificationManager.getService();
4139                         inm.clearData(packageName, appInfo.uid, uid == appInfo.uid);
4140                     }
4141 
4142                     // Clear its scheduled jobs
4143                     JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
4144                     js.cancelJobsForUid(appInfo.uid, "clear data");
4145 
4146                     // Clear its pending alarms
4147                     AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class);
4148                     ami.removeAlarmsForUid(appInfo.uid);
4149                 }
4150             } catch (RemoteException e) {
4151             }
4152         } finally {
4153             Binder.restoreCallingIdentity(callingId);
4154         }
4155         return true;
4156     }
4157 
4158     @Override
killBackgroundProcesses(final String packageName, int userId)4159     public void killBackgroundProcesses(final String packageName, int userId) {
4160         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4161                 != PackageManager.PERMISSION_GRANTED &&
4162                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4163                         != PackageManager.PERMISSION_GRANTED) {
4164             String msg = "Permission Denial: killBackgroundProcesses() from pid="
4165                     + Binder.getCallingPid()
4166                     + ", uid=" + Binder.getCallingUid()
4167                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4168             Slog.w(TAG, msg);
4169             throw new SecurityException(msg);
4170         }
4171 
4172         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4173                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
4174         final int[] userIds = mUserController.expandUserId(userId);
4175 
4176         long callingId = Binder.clearCallingIdentity();
4177         try {
4178             IPackageManager pm = AppGlobals.getPackageManager();
4179             for (int targetUserId : userIds) {
4180                 int appId = -1;
4181                 try {
4182                     appId = UserHandle.getAppId(
4183                             pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
4184                                     targetUserId));
4185                 } catch (RemoteException e) {
4186                 }
4187                 if (appId == -1) {
4188                     Slog.w(TAG, "Invalid packageName: " + packageName);
4189                     return;
4190                 }
4191                 synchronized (this) {
4192                     mProcessList.killPackageProcessesLocked(packageName, appId, targetUserId,
4193                             ProcessList.SERVICE_ADJ, "kill background");
4194                 }
4195             }
4196         } finally {
4197             Binder.restoreCallingIdentity(callingId);
4198         }
4199     }
4200 
4201     @Override
killAllBackgroundProcesses()4202     public void killAllBackgroundProcesses() {
4203         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4204                 != PackageManager.PERMISSION_GRANTED) {
4205             final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4206                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4207                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4208             Slog.w(TAG, msg);
4209             throw new SecurityException(msg);
4210         }
4211 
4212         final long callingId = Binder.clearCallingIdentity();
4213         try {
4214             synchronized (this) {
4215                 // Allow memory level to go down (the flag needs to be set before updating oom adj)
4216                 // because this method is also used to simulate low memory.
4217                 mAllowLowerMemLevel = true;
4218                 mProcessList.killPackageProcessesLocked(null /* packageName */, -1 /* appId */,
4219                         UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, "kill all background");
4220 
4221                 doLowMemReportIfNeededLocked(null);
4222             }
4223         } finally {
4224             Binder.restoreCallingIdentity(callingId);
4225         }
4226     }
4227 
4228     /**
4229      * Kills all background processes, except those matching any of the
4230      * specified properties.
4231      *
4232      * @param minTargetSdk the target SDK version at or above which to preserve
4233      *                     processes, or {@code -1} to ignore the target SDK
4234      * @param maxProcState the process state at or below which to preserve
4235      *                     processes, or {@code -1} to ignore the process state
4236      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)4237     void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
4238         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4239                 != PackageManager.PERMISSION_GRANTED) {
4240             final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
4241                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4242                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4243             Slog.w(TAG, msg);
4244             throw new SecurityException(msg);
4245         }
4246 
4247         final long callingId = Binder.clearCallingIdentity();
4248         try {
4249             synchronized (this) {
4250                 mProcessList.killAllBackgroundProcessesExceptLocked(minTargetSdk, maxProcState);
4251             }
4252         } finally {
4253             Binder.restoreCallingIdentity(callingId);
4254         }
4255     }
4256 
4257     @Override
forceStopPackage(final String packageName, int userId)4258     public void forceStopPackage(final String packageName, int userId) {
4259         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4260                 != PackageManager.PERMISSION_GRANTED) {
4261             String msg = "Permission Denial: forceStopPackage() from pid="
4262                     + Binder.getCallingPid()
4263                     + ", uid=" + Binder.getCallingUid()
4264                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4265             Slog.w(TAG, msg);
4266             throw new SecurityException(msg);
4267         }
4268         final int callingPid = Binder.getCallingPid();
4269         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
4270                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
4271         long callingId = Binder.clearCallingIdentity();
4272         try {
4273             IPackageManager pm = AppGlobals.getPackageManager();
4274             synchronized(this) {
4275                 int[] users = userId == UserHandle.USER_ALL
4276                         ? mUserController.getUsers() : new int[] { userId };
4277                 for (int user : users) {
4278                     if (getPackageManagerInternalLocked().isPackageStateProtected(
4279                             packageName, user)) {
4280                         Slog.w(TAG, "Ignoring request to force stop protected package "
4281                                 + packageName + " u" + user);
4282                         return;
4283                     }
4284 
4285                     int pkgUid = -1;
4286                     try {
4287                         pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
4288                                 user);
4289                     } catch (RemoteException e) {
4290                     }
4291                     if (pkgUid == -1) {
4292                         Slog.w(TAG, "Invalid packageName: " + packageName);
4293                         continue;
4294                     }
4295                     try {
4296                         pm.setPackageStoppedState(packageName, true, user);
4297                     } catch (RemoteException e) {
4298                     } catch (IllegalArgumentException e) {
4299                         Slog.w(TAG, "Failed trying to unstop package "
4300                                 + packageName + ": " + e);
4301                     }
4302                     if (mUserController.isUserRunning(user, 0)) {
4303                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
4304                         finishForceStopPackageLocked(packageName, pkgUid);
4305                     }
4306                 }
4307             }
4308         } finally {
4309             Binder.restoreCallingIdentity(callingId);
4310         }
4311     }
4312 
4313     @Override
addPackageDependency(String packageName)4314     public void addPackageDependency(String packageName) {
4315         synchronized (this) {
4316             int callingPid = Binder.getCallingPid();
4317             if (callingPid == myPid()) {
4318                 //  Yeah, um, no.
4319                 return;
4320             }
4321             ProcessRecord proc;
4322             synchronized (mPidsSelfLocked) {
4323                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
4324             }
4325             if (proc != null) {
4326                 if (proc.pkgDeps == null) {
4327                     proc.pkgDeps = new ArraySet<String>(1);
4328                 }
4329                 proc.pkgDeps.add(packageName);
4330             }
4331         }
4332     }
4333 
4334     /*
4335      * The pkg name and app id have to be specified.
4336      */
4337     @Override
killApplication(String pkg, int appId, int userId, String reason)4338     public void killApplication(String pkg, int appId, int userId, String reason) {
4339         if (pkg == null) {
4340             return;
4341         }
4342         // Make sure the uid is valid.
4343         if (appId < 0) {
4344             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
4345             return;
4346         }
4347         int callerUid = Binder.getCallingUid();
4348         // Only the system server can kill an application
4349         if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
4350             // Post an aysnc message to kill the application
4351             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4352             msg.arg1 = appId;
4353             msg.arg2 = userId;
4354             Bundle bundle = new Bundle();
4355             bundle.putString("pkg", pkg);
4356             bundle.putString("reason", reason);
4357             msg.obj = bundle;
4358             mHandler.sendMessage(msg);
4359         } else {
4360             throw new SecurityException(callerUid + " cannot kill pkg: " +
4361                     pkg);
4362         }
4363     }
4364 
4365     @Override
closeSystemDialogs(String reason)4366     public void closeSystemDialogs(String reason) {
4367         mAtmInternal.closeSystemDialogs(reason);
4368     }
4369 
4370     @Override
getProcessMemoryInfo(int[] pids)4371     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
4372         enforceNotIsolatedCaller("getProcessMemoryInfo");
4373 
4374         final long now = SystemClock.uptimeMillis();
4375         final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME;
4376 
4377         final int callingPid = Binder.getCallingPid();
4378         final int callingUid = Binder.getCallingUid();
4379         final int callingUserId = UserHandle.getUserId(callingUid);
4380         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4381                 callingUid) == PackageManager.PERMISSION_GRANTED;
4382         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4383         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4384                 "getProcessMemoryInfo", callingPid, callingUid);
4385 
4386         Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4387         for (int i=pids.length-1; i>=0; i--) {
4388             infos[i] = new Debug.MemoryInfo();
4389             final ProcessRecord proc;
4390             final int oomAdj;
4391             synchronized (this) {
4392                 synchronized (mPidsSelfLocked) {
4393                     proc = mPidsSelfLocked.get(pids[i]);
4394                     oomAdj = proc != null ? proc.setAdj : 0;
4395                 }
4396             }
4397             final int targetUid = (proc != null) ? proc.uid : -1;
4398             final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1;
4399 
4400             if (callingUid != targetUid) {
4401                 if (!allUids) {
4402                     continue; // Not allowed to see other UIDs.
4403                 }
4404 
4405                 if (!allUsers && (targetUserId != callingUserId)) {
4406                     continue; // Not allowed to see other users.
4407                 }
4408             }
4409             if (proc != null && proc.lastMemInfoTime >= lastNow && proc.lastMemInfo != null) {
4410                 // It hasn't been long enough that we want to take another sample; return
4411                 // the last one.
4412                 infos[i].set(proc.lastMemInfo);
4413                 continue;
4414             }
4415             final long startTime = SystemClock.currentThreadTimeMillis();
4416             final Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
4417             Debug.getMemoryInfo(pids[i], memInfo);
4418             final long endTime = SystemClock.currentThreadTimeMillis();
4419             infos[i].set(memInfo);
4420             if (proc != null) {
4421                 synchronized (this) {
4422                     proc.lastMemInfo = memInfo;
4423                     proc.lastMemInfoTime = SystemClock.uptimeMillis();
4424                     if (proc.thread != null && proc.setAdj == oomAdj) {
4425                         // Record this for posterity if the process has been stable.
4426                         proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
4427                                 infos[i].getTotalUss(), infos[i].getTotalRss(), false,
4428                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, endTime - startTime,
4429                                 proc.pkgList.mPkgList);
4430                         for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) {
4431                             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
4432                             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
4433                                     proc.info.uid,
4434                                     holder.state.getName(),
4435                                     holder.state.getPackage(),
4436                                     infos[i].getTotalPss(),
4437                                     infos[i].getTotalUss(),
4438                                     infos[i].getTotalRss(),
4439                                     ProcessStats.ADD_PSS_EXTERNAL_SLOW,
4440                                     endTime-startTime,
4441                                     holder.appVersion);
4442                         }
4443                     }
4444                 }
4445             }
4446         }
4447         return infos;
4448     }
4449 
4450     @Override
getProcessPss(int[] pids)4451     public long[] getProcessPss(int[] pids) {
4452         enforceNotIsolatedCaller("getProcessPss");
4453 
4454         final int callingPid = Binder.getCallingPid();
4455         final int callingUid = Binder.getCallingUid();
4456         final int userId = UserHandle.getUserId(callingUid);
4457         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4458                 callingUid) == PackageManager.PERMISSION_GRANTED;
4459         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4460         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4461                 "getProcessPss", callingPid, callingUid);
4462 
4463         long[] pss = new long[pids.length];
4464         for (int i=pids.length-1; i>=0; i--) {
4465             ProcessRecord proc;
4466             int oomAdj;
4467             synchronized (this) {
4468                 synchronized (mPidsSelfLocked) {
4469                     proc = mPidsSelfLocked.get(pids[i]);
4470                     oomAdj = proc != null ? proc.setAdj : 0;
4471                 }
4472             }
4473             if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) {
4474                 // The caller is not allow to get information about this other process...
4475                 // just leave it empty.
4476                 continue;
4477             }
4478             long[] tmpUss = new long[3];
4479             long startTime = SystemClock.currentThreadTimeMillis();
4480             pss[i] = Debug.getPss(pids[i], tmpUss, null);
4481             long endTime = SystemClock.currentThreadTimeMillis();
4482             if (proc != null) {
4483                 synchronized (this) {
4484                     if (proc.thread != null && proc.setAdj == oomAdj) {
4485                         // Record this for posterity if the process has been stable.
4486                         proc.baseProcessTracker.addPss(pss[i], tmpUss[0], tmpUss[2], false,
4487                                 ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime, proc.pkgList.mPkgList);
4488                         for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) {
4489                             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
4490                             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
4491                                     proc.info.uid,
4492                                     holder.state.getName(),
4493                                     holder.state.getPackage(),
4494                                     pss[i], tmpUss[0], tmpUss[2],
4495                                     ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime,
4496                                     holder.appVersion);
4497                         }
4498                     }
4499                 }
4500             }
4501         }
4502         return pss;
4503     }
4504 
4505     @Override
killApplicationProcess(String processName, int uid)4506     public void killApplicationProcess(String processName, int uid) {
4507         if (processName == null) {
4508             return;
4509         }
4510 
4511         int callerUid = Binder.getCallingUid();
4512         // Only the system server can kill an application
4513         if (callerUid == SYSTEM_UID) {
4514             synchronized (this) {
4515                 ProcessRecord app = getProcessRecordLocked(processName, uid, true);
4516                 if (app != null && app.thread != null) {
4517                     try {
4518                         app.thread.scheduleSuicide();
4519                     } catch (RemoteException e) {
4520                         // If the other end already died, then our work here is done.
4521                     }
4522                 } else {
4523                     Slog.w(TAG, "Process/uid not found attempting kill of "
4524                             + processName + " / " + uid);
4525                 }
4526             }
4527         } else {
4528             throw new SecurityException(callerUid + " cannot kill app process: " +
4529                     processName);
4530         }
4531     }
4532 
4533     @GuardedBy("this")
forceStopPackageLocked(final String packageName, int uid, String reason)4534     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
4535         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
4536                 false, true, false, false, UserHandle.getUserId(uid), reason);
4537     }
4538 
4539     @GuardedBy("this")
finishForceStopPackageLocked(final String packageName, int uid)4540     private void finishForceStopPackageLocked(final String packageName, int uid) {
4541         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4542                 Uri.fromParts("package", packageName, null));
4543         if (!mProcessesReady) {
4544             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4545                     | Intent.FLAG_RECEIVER_FOREGROUND);
4546         }
4547         intent.putExtra(Intent.EXTRA_UID, uid);
4548         intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
4549         broadcastIntentLocked(null, null, intent,
4550                 null, null, 0, null, null, null, OP_NONE,
4551                 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
4552                 Binder.getCallingPid(), UserHandle.getUserId(uid));
4553     }
4554 
cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4555     private void cleanupDisabledPackageComponentsLocked(
4556             String packageName, int userId, String[] changedClasses) {
4557 
4558         Set<String> disabledClasses = null;
4559         boolean packageDisabled = false;
4560         IPackageManager pm = AppGlobals.getPackageManager();
4561 
4562         if (changedClasses == null) {
4563             // Nothing changed...
4564             return;
4565         }
4566 
4567         // Determine enable/disable state of the package and its components.
4568         int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4569         for (int i = changedClasses.length - 1; i >= 0; i--) {
4570             final String changedClass = changedClasses[i];
4571 
4572             if (changedClass.equals(packageName)) {
4573                 try {
4574                     // Entire package setting changed
4575                     enabled = pm.getApplicationEnabledSetting(packageName,
4576                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4577                 } catch (Exception e) {
4578                     // No such package/component; probably racing with uninstall.  In any
4579                     // event it means we have nothing further to do here.
4580                     return;
4581                 }
4582                 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4583                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4584                 if (packageDisabled) {
4585                     // Entire package is disabled.
4586                     // No need to continue to check component states.
4587                     disabledClasses = null;
4588                     break;
4589                 }
4590             } else {
4591                 try {
4592                     enabled = pm.getComponentEnabledSetting(
4593                             new ComponentName(packageName, changedClass),
4594                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4595                 } catch (Exception e) {
4596                     // As above, probably racing with uninstall.
4597                     return;
4598                 }
4599                 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4600                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
4601                     if (disabledClasses == null) {
4602                         disabledClasses = new ArraySet<>(changedClasses.length);
4603                     }
4604                     disabledClasses.add(changedClass);
4605                 }
4606             }
4607         }
4608 
4609         if (!packageDisabled && disabledClasses == null) {
4610             // Nothing to do here...
4611             return;
4612         }
4613 
4614         mAtmInternal.cleanupDisabledPackageComponents(
4615                 packageName, disabledClasses, userId, mBooted);
4616 
4617         // Clean-up disabled services.
4618         mServices.bringDownDisabledPackageServicesLocked(
4619                 packageName, disabledClasses, userId, false /* evenPersistent */, true /* doIt */);
4620 
4621         // Clean-up disabled providers.
4622         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4623         mProviderMap.collectPackageProvidersLocked(
4624                 packageName, disabledClasses, true, false, userId, providers);
4625         for (int i = providers.size() - 1; i >= 0; i--) {
4626             removeDyingProviderLocked(null, providers.get(i), true);
4627         }
4628 
4629         // Clean-up disabled broadcast receivers.
4630         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4631             mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4632                     packageName, disabledClasses, userId, true);
4633         }
4634 
4635     }
4636 
clearBroadcastQueueForUserLocked(int userId)4637     final boolean clearBroadcastQueueForUserLocked(int userId) {
4638         boolean didSomething = false;
4639         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4640             didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4641                     null, null, userId, true);
4642         }
4643         return didSomething;
4644     }
4645 
4646     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4647     final boolean forceStopPackageLocked(String packageName, int appId,
4648             boolean callerWillRestart, boolean purgeCache, boolean doit,
4649             boolean evenPersistent, boolean uninstalling, int userId, String reason) {
4650         int i;
4651 
4652         if (userId == UserHandle.USER_ALL && packageName == null) {
4653             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
4654         }
4655 
4656         if (appId < 0 && packageName != null) {
4657             try {
4658                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
4659                         .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
4660             } catch (RemoteException e) {
4661             }
4662         }
4663 
4664         if (doit) {
4665             if (packageName != null) {
4666                 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
4667                         + " user=" + userId + ": " + reason);
4668             } else {
4669                 Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
4670             }
4671 
4672             mAppErrors.resetProcessCrashTimeLocked(packageName == null, appId, userId);
4673         }
4674 
4675         boolean didSomething = mProcessList.killPackageProcessesLocked(packageName, appId, userId,
4676                 ProcessList.INVALID_ADJ, callerWillRestart, true /* allowRestart */, doit,
4677                 evenPersistent, true /* setRemoved */,
4678                 packageName == null ? ("stop user " + userId) : ("stop " + packageName));
4679 
4680         didSomething |=
4681                 mAtmInternal.onForceStopPackage(packageName, doit, evenPersistent, userId);
4682 
4683         if (mServices.bringDownDisabledPackageServicesLocked(
4684                 packageName, null /* filterByClasses */, userId, evenPersistent, doit)) {
4685             if (!doit) {
4686                 return true;
4687             }
4688             didSomething = true;
4689         }
4690 
4691         if (packageName == null) {
4692             // Remove all sticky broadcasts from this user.
4693             mStickyBroadcasts.remove(userId);
4694         }
4695 
4696         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4697         if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent,
4698                 userId, providers)) {
4699             if (!doit) {
4700                 return true;
4701             }
4702             didSomething = true;
4703         }
4704         for (i = providers.size() - 1; i >= 0; i--) {
4705             removeDyingProviderLocked(null, providers.get(i), true);
4706         }
4707 
4708         // Remove transient permissions granted from/to this package/user
4709         mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false);
4710 
4711         if (doit) {
4712             for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
4713                 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4714                         packageName, null, userId, doit);
4715             }
4716         }
4717 
4718         if (packageName == null || uninstalling) {
4719             didSomething |= mPendingIntentController.removePendingIntentsForPackage(
4720                     packageName, userId, appId, doit);
4721         }
4722 
4723         if (doit) {
4724             if (purgeCache && packageName != null) {
4725                 AttributeCache ac = AttributeCache.instance();
4726                 if (ac != null) {
4727                     ac.removePackage(packageName);
4728                 }
4729             }
4730             if (mBooted) {
4731                 mAtmInternal.resumeTopActivities(true /* scheduleIdle */);
4732             }
4733         }
4734 
4735         return didSomething;
4736     }
4737 
4738     @GuardedBy("this")
processContentProviderPublishTimedOutLocked(ProcessRecord app)4739     private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) {
4740         cleanupAppInLaunchingProvidersLocked(app, true);
4741         mProcessList.removeProcessLocked(app, false, true, "timeout publishing content providers");
4742     }
4743 
4744     @GuardedBy("this")
processStartTimedOutLocked(ProcessRecord app)4745     private final void processStartTimedOutLocked(ProcessRecord app) {
4746         final int pid = app.pid;
4747         boolean gone = mPidsSelfLocked.removeIfNoThread(app);
4748 
4749         if (gone) {
4750             Slog.w(TAG, "Process " + app + " failed to attach");
4751             EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4752                     pid, app.uid, app.processName);
4753             mProcessList.removeProcessNameLocked(app.processName, app.uid);
4754             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
4755             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
4756             // Take care of any launching providers waiting for this process.
4757             cleanupAppInLaunchingProvidersLocked(app, true);
4758             // Take care of any services that are waiting for the process.
4759             mServices.processStartTimedOutLocked(app);
4760             app.kill("start timeout", true);
4761             if (app.isolated) {
4762                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
4763             }
4764             removeLruProcessLocked(app);
4765             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4766             if (backupTarget != null && backupTarget.app.pid == pid) {
4767                 Slog.w(TAG, "Unattached app died before backup, skipping");
4768                 mHandler.post(new Runnable() {
4769                 @Override
4770                     public void run(){
4771                         try {
4772                             IBackupManager bm = IBackupManager.Stub.asInterface(
4773                                     ServiceManager.getService(Context.BACKUP_SERVICE));
4774                             bm.agentDisconnectedForUser(app.userId, app.info.packageName);
4775                         } catch (RemoteException e) {
4776                             // Can't happen; the backup manager is local
4777                         }
4778                     }
4779                 });
4780             }
4781             if (isPendingBroadcastProcessLocked(pid)) {
4782                 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
4783                 skipPendingBroadcastLocked(pid);
4784             }
4785         } else {
4786             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
4787         }
4788     }
4789 
4790     @GuardedBy("this")
attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4791     private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
4792             int pid, int callingUid, long startSeq) {
4793 
4794         // Find the application record that is being attached...  either via
4795         // the pid if we are running in multiple processes, or just pull the
4796         // next app record if we are emulating process with anonymous threads.
4797         ProcessRecord app;
4798         long startTime = SystemClock.uptimeMillis();
4799         long bindApplicationTimeMillis;
4800         if (pid != MY_PID && pid >= 0) {
4801             synchronized (mPidsSelfLocked) {
4802                 app = mPidsSelfLocked.get(pid);
4803             }
4804             if (app != null && (app.startUid != callingUid || app.startSeq != startSeq)) {
4805                 String processName = null;
4806                 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4807                 if (pending != null) {
4808                     processName = pending.processName;
4809                 }
4810                 final String msg = "attachApplicationLocked process:" + processName
4811                         + " startSeq:" + startSeq
4812                         + " pid:" + pid
4813                         + " belongs to another existing app:" + app.processName
4814                         + " startSeq:" + app.startSeq;
4815                 Slog.wtf(TAG, msg);
4816                 // SafetyNet logging for b/131105245.
4817                 EventLog.writeEvent(0x534e4554, "131105245", app.startUid, msg);
4818                 // If there is already an app occupying that pid that hasn't been cleaned up
4819                 cleanUpApplicationRecordLocked(app, false, false, -1,
4820                             true /*replacingPid*/);
4821                 mPidsSelfLocked.remove(app);
4822                 app = null;
4823             }
4824         } else {
4825             app = null;
4826         }
4827 
4828         // It's possible that process called attachApplication before we got a chance to
4829         // update the internal state.
4830         if (app == null && startSeq > 0) {
4831             final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4832             if (pending != null && pending.startUid == callingUid && pending.startSeq == startSeq
4833                     && mProcessList.handleProcessStartedLocked(pending, pid, pending
4834                             .isUsingWrapper(),
4835                             startSeq, true)) {
4836                 app = pending;
4837             }
4838         }
4839 
4840         if (app == null) {
4841             Slog.w(TAG, "No pending application record for pid " + pid
4842                     + " (IApplicationThread " + thread + "); dropping process");
4843             EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
4844             if (pid > 0 && pid != MY_PID) {
4845                 killProcessQuiet(pid);
4846                 //TODO: killProcessGroup(app.info.uid, pid);
4847             } else {
4848                 try {
4849                     thread.scheduleExit();
4850                 } catch (Exception e) {
4851                     // Ignore exceptions.
4852                 }
4853             }
4854             return false;
4855         }
4856 
4857         // If this application record is still attached to a previous
4858         // process, clean it up now.
4859         if (app.thread != null) {
4860             handleAppDiedLocked(app, true, true);
4861         }
4862 
4863         // Tell the process all about itself.
4864 
4865         if (DEBUG_ALL) Slog.v(
4866                 TAG, "Binding process pid " + pid + " to record " + app);
4867 
4868         final String processName = app.processName;
4869         try {
4870             AppDeathRecipient adr = new AppDeathRecipient(
4871                     app, pid, thread);
4872             thread.asBinder().linkToDeath(adr, 0);
4873             app.deathRecipient = adr;
4874         } catch (RemoteException e) {
4875             app.resetPackageList(mProcessStats);
4876             mProcessList.startProcessLocked(app,
4877                     new HostingRecord("link fail", processName),
4878                     ZYGOTE_POLICY_FLAG_EMPTY);
4879             return false;
4880         }
4881 
4882         EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
4883 
4884         app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;
4885         mOomAdjuster.setAttachingSchedGroupLocked(app);
4886         app.forcingToImportant = null;
4887         updateProcessForegroundLocked(app, false, 0, false);
4888         app.hasShownUi = false;
4889         app.setDebugging(false);
4890         app.cached = false;
4891         app.killedByAm = false;
4892         app.killed = false;
4893 
4894 
4895         // We carefully use the same state that PackageManager uses for
4896         // filtering, since we use this flag to decide if we need to install
4897         // providers when user is unlocked later
4898         app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);
4899 
4900         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4901 
4902         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4903         List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
4904 
4905         if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
4906             Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
4907             msg.obj = app;
4908             mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT);
4909         }
4910 
4911         checkTime(startTime, "attachApplicationLocked: before bindApplication");
4912 
4913         if (!normalMode) {
4914             Slog.i(TAG, "Launching preboot mode app: " + app);
4915         }
4916 
4917         if (DEBUG_ALL) Slog.v(
4918             TAG, "New app record " + app
4919             + " thread=" + thread.asBinder() + " pid=" + pid);
4920         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4921         try {
4922             int testMode = ApplicationThreadConstants.DEBUG_OFF;
4923             if (mDebugApp != null && mDebugApp.equals(processName)) {
4924                 testMode = mWaitForDebugger
4925                     ? ApplicationThreadConstants.DEBUG_WAIT
4926                     : ApplicationThreadConstants.DEBUG_ON;
4927                 app.setDebugging(true);
4928                 if (mDebugTransient) {
4929                     mDebugApp = mOrigDebugApp;
4930                     mWaitForDebugger = mOrigWaitForDebugger;
4931                 }
4932             }
4933 
4934             boolean enableTrackAllocation = false;
4935             if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
4936                 enableTrackAllocation = true;
4937                 mTrackAllocationApp = null;
4938             }
4939 
4940             // If the app is being launched for restore or full backup, set it up specially
4941             boolean isRestrictedBackupMode = false;
4942             if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) {
4943                 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID
4944                         && ((backupTarget.backupMode == BackupRecord.RESTORE)
4945                                 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL)
4946                                 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL));
4947             }
4948 
4949             final ActiveInstrumentation instr = app.getActiveInstrumentation();
4950 
4951             if (instr != null) {
4952                 notifyPackageUse(instr.mClass.getPackageName(),
4953                                  PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
4954             }
4955             if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc "
4956                     + processName + " with config "
4957                     + app.getWindowProcessController().getConfiguration());
4958             ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info;
4959             app.compat = compatibilityInfoForPackage(appInfo);
4960 
4961             ProfilerInfo profilerInfo = null;
4962             String preBindAgent = null;
4963             if (mProfileData.getProfileApp() != null
4964                     && mProfileData.getProfileApp().equals(processName)) {
4965                 mProfileData.setProfileProc(app);
4966                 if (mProfileData.getProfilerInfo() != null) {
4967                     // Send a profiler info object to the app if either a file is given, or
4968                     // an agent should be loaded at bind-time.
4969                     boolean needsInfo = mProfileData.getProfilerInfo().profileFile != null
4970                             || mProfileData.getProfilerInfo().attachAgentDuringBind;
4971                     profilerInfo = needsInfo
4972                             ? new ProfilerInfo(mProfileData.getProfilerInfo()) : null;
4973                     if (mProfileData.getProfilerInfo().agent != null) {
4974                         preBindAgent = mProfileData.getProfilerInfo().agent;
4975                     }
4976                 }
4977             } else if (instr != null && instr.mProfileFile != null) {
4978                 profilerInfo = new ProfilerInfo(instr.mProfileFile, null, 0, false, false,
4979                         null, false);
4980             }
4981             if (mAppAgentMap != null && mAppAgentMap.containsKey(processName)) {
4982                 // We need to do a debuggable check here. See setAgentApp for why the check is
4983                 // postponed to here.
4984                 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
4985                     String agent = mAppAgentMap.get(processName);
4986                     // Do not overwrite already requested agent.
4987                     if (profilerInfo == null) {
4988                         profilerInfo = new ProfilerInfo(null, null, 0, false, false,
4989                                 mAppAgentMap.get(processName), true);
4990                     } else if (profilerInfo.agent == null) {
4991                         profilerInfo = profilerInfo.setAgent(mAppAgentMap.get(processName), true);
4992                     }
4993                 }
4994             }
4995 
4996             if (profilerInfo != null && profilerInfo.profileFd != null) {
4997                 profilerInfo.profileFd = profilerInfo.profileFd.dup();
4998                 if (TextUtils.equals(mProfileData.getProfileApp(), processName)
4999                         && mProfileData.getProfilerInfo() != null) {
5000                     clearProfilerLocked();
5001                 }
5002             }
5003 
5004             // We deprecated Build.SERIAL and it is not accessible to
5005             // Instant Apps and target APIs higher than O MR1. Since access to the serial
5006             // is now behind a permission we push down the value.
5007             final String buildSerial = (!appInfo.isInstantApp()
5008                     && appInfo.targetSdkVersion < Build.VERSION_CODES.P)
5009                             ? sTheRealBuildSerial : Build.UNKNOWN;
5010 
5011             // Check if this is a secondary process that should be incorporated into some
5012             // currently active instrumentation.  (Note we do this AFTER all of the profiling
5013             // stuff above because profiling can currently happen only in the primary
5014             // instrumentation process.)
5015             if (mActiveInstrumentation.size() > 0 && instr == null) {
5016                 for (int i = mActiveInstrumentation.size() - 1;
5017                         i >= 0 && app.getActiveInstrumentation() == null; i--) {
5018                     ActiveInstrumentation aInstr = mActiveInstrumentation.get(i);
5019                     if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) {
5020                         if (aInstr.mTargetProcesses.length == 0) {
5021                             // This is the wildcard mode, where every process brought up for
5022                             // the target instrumentation should be included.
5023                             if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) {
5024                                 app.setActiveInstrumentation(aInstr);
5025                                 aInstr.mRunningProcesses.add(app);
5026                             }
5027                         } else {
5028                             for (String proc : aInstr.mTargetProcesses) {
5029                                 if (proc.equals(app.processName)) {
5030                                     app.setActiveInstrumentation(aInstr);
5031                                     aInstr.mRunningProcesses.add(app);
5032                                     break;
5033                                 }
5034                             }
5035                         }
5036                     }
5037                 }
5038             }
5039 
5040             // If we were asked to attach an agent on startup, do so now, before we're binding
5041             // application code.
5042             if (preBindAgent != null) {
5043                 thread.attachAgent(preBindAgent);
5044             }
5045             if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
5046                 thread.attachStartupAgents(app.info.dataDir);
5047             }
5048 
5049             // Figure out whether the app needs to run in autofill compat mode.
5050             AutofillOptions autofillOptions = null;
5051             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
5052                 final AutofillManagerInternal afm = LocalServices.getService(
5053                         AutofillManagerInternal.class);
5054                 if (afm != null) {
5055                     autofillOptions = afm.getAutofillOptions(
5056                             app.info.packageName, app.info.longVersionCode, app.userId);
5057                 }
5058             }
5059             ContentCaptureOptions contentCaptureOptions = null;
5060             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
5061                 final ContentCaptureManagerInternal ccm =
5062                         LocalServices.getService(ContentCaptureManagerInternal.class);
5063                 if (ccm != null) {
5064                     contentCaptureOptions = ccm.getOptionsForPackage(app.userId,
5065                             app.info.packageName);
5066                 }
5067             }
5068 
5069             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
5070             bindApplicationTimeMillis = SystemClock.elapsedRealtime();
5071             mAtmInternal.preBindApplication(app.getWindowProcessController());
5072             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
5073             if (mPlatformCompat != null) {
5074                 mPlatformCompat.resetReporting(app.info);
5075             }
5076             if (app.isolatedEntryPoint != null) {
5077                 // This is an isolated process which should just call an entry point instead of
5078                 // being bound to an application.
5079                 thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
5080             } else if (instr2 != null) {
5081                 thread.bindApplication(processName, appInfo, providers,
5082                         instr2.mClass,
5083                         profilerInfo, instr2.mArguments,
5084                         instr2.mWatcher,
5085                         instr2.mUiAutomationConnection, testMode,
5086                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
5087                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
5088                         new Configuration(app.getWindowProcessController().getConfiguration()),
5089                         app.compat, getCommonServicesLocked(app.isolated),
5090                         mCoreSettingsObserver.getCoreSettingsLocked(),
5091                         buildSerial, autofillOptions, contentCaptureOptions,
5092                         app.mDisabledCompatChanges);
5093             } else {
5094                 thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
5095                         null, null, null, testMode,
5096                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
5097                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
5098                         new Configuration(app.getWindowProcessController().getConfiguration()),
5099                         app.compat, getCommonServicesLocked(app.isolated),
5100                         mCoreSettingsObserver.getCoreSettingsLocked(),
5101                         buildSerial, autofillOptions, contentCaptureOptions,
5102                         app.mDisabledCompatChanges);
5103             }
5104             if (profilerInfo != null) {
5105                 profilerInfo.closeFd();
5106                 profilerInfo = null;
5107             }
5108 
5109             // Make app active after binding application or client may be running requests (e.g
5110             // starting activities) before it is ready.
5111             app.makeActive(thread, mProcessStats);
5112             checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
5113             mProcessList.updateLruProcessLocked(app, false, null);
5114             checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
5115             app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
5116         } catch (Exception e) {
5117             // todo: Yikes!  What should we do?  For now we will try to
5118             // start another process, but that could easily get us in
5119             // an infinite loop of restarting processes...
5120             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
5121 
5122             app.resetPackageList(mProcessStats);
5123             app.unlinkDeathRecipient();
5124             mProcessList.startProcessLocked(app, new HostingRecord("bind-fail", processName),
5125                     ZYGOTE_POLICY_FLAG_EMPTY);
5126             return false;
5127         }
5128 
5129         // Remove this record from the list of starting applications.
5130         mPersistentStartingProcesses.remove(app);
5131         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
5132                 "Attach application locked removing on hold: " + app);
5133         mProcessesOnHold.remove(app);
5134 
5135         boolean badApp = false;
5136         boolean didSomething = false;
5137 
5138         // See if the top visible activity is waiting to run in this process...
5139         if (normalMode) {
5140             try {
5141                 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
5142             } catch (Exception e) {
5143                 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
5144                 badApp = true;
5145             }
5146         }
5147 
5148         // Find any services that should be running in this process...
5149         if (!badApp) {
5150             try {
5151                 didSomething |= mServices.attachApplicationLocked(app, processName);
5152                 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
5153             } catch (Exception e) {
5154                 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
5155                 badApp = true;
5156             }
5157         }
5158 
5159         // Check if a next-broadcast receiver is in this process...
5160         if (!badApp && isPendingBroadcastProcessLocked(pid)) {
5161             try {
5162                 didSomething |= sendPendingBroadcastsLocked(app);
5163                 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
5164             } catch (Exception e) {
5165                 // If the app died trying to launch the receiver we declare it 'bad'
5166                 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
5167                 badApp = true;
5168             }
5169         }
5170 
5171         // Check whether the next backup agent is in this process...
5172         if (!badApp && backupTarget != null && backupTarget.app == app) {
5173             if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
5174                     "New app is backup target, launching agent for " + app);
5175             notifyPackageUse(backupTarget.appInfo.packageName,
5176                              PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
5177             try {
5178                 thread.scheduleCreateBackupAgent(backupTarget.appInfo,
5179                         compatibilityInfoForPackage(backupTarget.appInfo),
5180                         backupTarget.backupMode, backupTarget.userId);
5181             } catch (Exception e) {
5182                 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
5183                 badApp = true;
5184             }
5185         }
5186 
5187         if (badApp) {
5188             app.kill("error during init", true);
5189             handleAppDiedLocked(app, false, true);
5190             return false;
5191         }
5192 
5193         if (!didSomething) {
5194             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
5195             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
5196         }
5197 
5198         StatsLog.write(
5199                 StatsLog.PROCESS_START_TIME,
5200                 app.info.uid,
5201                 app.pid,
5202                 app.info.packageName,
5203                 StatsLog.PROCESS_START_TIME__TYPE__COLD,
5204                 app.startTime,
5205                 (int) (bindApplicationTimeMillis - app.startTime),
5206                 (int) (SystemClock.elapsedRealtime() - app.startTime),
5207                 app.hostingRecord.getType(),
5208                 (app.hostingRecord.getName() != null ? app.hostingRecord.getName() : ""));
5209         return true;
5210     }
5211 
5212     @Override
attachApplication(IApplicationThread thread, long startSeq)5213     public final void attachApplication(IApplicationThread thread, long startSeq) {
5214         if (thread == null) {
5215             throw new SecurityException("Invalid application interface");
5216         }
5217         synchronized (this) {
5218             int callingPid = Binder.getCallingPid();
5219             final int callingUid = Binder.getCallingUid();
5220             final long origId = Binder.clearCallingIdentity();
5221             attachApplicationLocked(thread, callingPid, callingUid, startSeq);
5222             Binder.restoreCallingIdentity(origId);
5223         }
5224     }
5225 
5226     @Override
showBootMessage(final CharSequence msg, final boolean always)5227     public void showBootMessage(final CharSequence msg, final boolean always) {
5228         if (Binder.getCallingUid() != myUid()) {
5229             throw new SecurityException();
5230         }
5231         mWindowManager.showBootMessage(msg, always);
5232     }
5233 
finishBooting()5234     final void finishBooting() {
5235         Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting");
5236 
5237         synchronized (this) {
5238             if (!mBootAnimationComplete) {
5239                 mCallFinishBooting = true;
5240                 return;
5241             }
5242             mCallFinishBooting = false;
5243         }
5244 
5245         // Let the ART runtime in zygote and system_server know that the boot completed.
5246         ZYGOTE_PROCESS.bootCompleted();
5247         VMRuntime.bootCompleted();
5248 
5249         IntentFilter pkgFilter = new IntentFilter();
5250         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
5251         pkgFilter.addDataScheme("package");
5252         mContext.registerReceiver(new BroadcastReceiver() {
5253             @Override
5254             public void onReceive(Context context, Intent intent) {
5255                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
5256                 if (pkgs != null) {
5257                     for (String pkg : pkgs) {
5258                         synchronized (ActivityManagerService.this) {
5259                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
5260                                     0, "query restart")) {
5261                                 setResultCode(Activity.RESULT_OK);
5262                                 return;
5263                             }
5264                         }
5265                     }
5266                 }
5267             }
5268         }, pkgFilter);
5269 
5270         IntentFilter dumpheapFilter = new IntentFilter();
5271         dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
5272         mContext.registerReceiver(new BroadcastReceiver() {
5273             @Override
5274             public void onReceive(Context context, Intent intent) {
5275                 final long delay = intent.getBooleanExtra(
5276                         DumpHeapActivity.EXTRA_DELAY_DELETE, false) ? 5 * 60 * 1000 : 0;
5277                 mHandler.sendEmptyMessageDelayed(DELETE_DUMPHEAP_MSG, delay);
5278             }
5279         }, dumpheapFilter);
5280 
5281         // Inform checkpointing systems of success
5282         try {
5283             // This line is needed to CTS test for the correct exception handling
5284             // See b/138952436#comment36 for context
5285             Slog.i(TAG, "About to commit checkpoint");
5286             IStorageManager storageManager = PackageHelper.getStorageManager();
5287             storageManager.commitChanges();
5288         } catch (Exception e) {
5289             PowerManager pm = (PowerManager)
5290                      mContext.getSystemService(Context.POWER_SERVICE);
5291             pm.reboot("Checkpoint commit failed");
5292         }
5293 
5294         // Let system services know.
5295         mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
5296 
5297         synchronized (this) {
5298             // Ensure that any processes we had put on hold are now started
5299             // up.
5300             final int NP = mProcessesOnHold.size();
5301             if (NP > 0) {
5302                 ArrayList<ProcessRecord> procs =
5303                     new ArrayList<ProcessRecord>(mProcessesOnHold);
5304                 for (int ip=0; ip<NP; ip++) {
5305                     if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: "
5306                             + procs.get(ip));
5307                     mProcessList.startProcessLocked(procs.get(ip),
5308                             new HostingRecord("on-hold"),
5309                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
5310                 }
5311             }
5312             if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5313                 return;
5314             }
5315             // Start looking for apps that are abusing wake locks.
5316             Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
5317             mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
5318             // Check if we are performing userspace reboot before setting sys.boot_completed to
5319             // avoid race with init reseting sys.init.userspace_reboot.in_progress once sys
5320             // .boot_completed is 1.
5321             if (InitProperties.userspace_reboot_in_progress().orElse(false)) {
5322                 UserspaceRebootLogger.noteUserspaceRebootSuccess();
5323             }
5324             // Tell anyone interested that we are done booting!
5325             SystemProperties.set("sys.boot_completed", "1");
5326 
5327             // And trigger dev.bootcomplete if we are not showing encryption progress
5328             if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse(""))
5329                     || "".equals(VoldProperties.encrypt_progress().orElse(""))) {
5330                 SystemProperties.set("dev.bootcomplete", "1");
5331             }
5332             mUserController.sendBootCompleted(
5333                     new IIntentReceiver.Stub() {
5334                         @Override
5335                         public void performReceive(Intent intent, int resultCode,
5336                                 String data, Bundle extras, boolean ordered,
5337                                 boolean sticky, int sendingUser) {
5338                             synchronized (ActivityManagerService.this) {
5339                                 mOomAdjuster.mAppCompact.compactAllSystem();
5340                                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
5341                             }
5342                         }
5343                     });
5344             maybeLogUserspaceRebootEvent();
5345             mUserController.scheduleStartProfiles();
5346         }
5347 
5348         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5349     }
5350 
5351     @Override
bootAnimationComplete()5352     public void bootAnimationComplete() {
5353         final boolean callFinishBooting;
5354         synchronized (this) {
5355             callFinishBooting = mCallFinishBooting;
5356             mBootAnimationComplete = true;
5357         }
5358         if (callFinishBooting) {
5359             finishBooting();
5360         }
5361     }
5362 
ensureBootCompleted()5363     final void ensureBootCompleted() {
5364         boolean booting;
5365         boolean enableScreen;
5366         synchronized (this) {
5367             booting = mBooting;
5368             mBooting = false;
5369             enableScreen = !mBooted;
5370             mBooted = true;
5371         }
5372 
5373         if (booting) {
5374             finishBooting();
5375         }
5376 
5377         if (enableScreen) {
5378             mAtmInternal.enableScreenAfterBoot(mBooted);
5379         }
5380     }
5381 
5382     @Override
getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5383     public IIntentSender getIntentSender(int type,
5384             String packageName, IBinder token, String resultWho,
5385             int requestCode, Intent[] intents, String[] resolvedTypes,
5386             int flags, Bundle bOptions, int userId) {
5387 
5388         // NOTE: The service lock isn't held in this method because nothing in the method requires
5389         // the service lock to be held.
5390 
5391         enforceNotIsolatedCaller("getIntentSender");
5392         // Refuse possible leaked file descriptors
5393         if (intents != null) {
5394             if (intents.length < 1) {
5395                 throw new IllegalArgumentException("Intents array length must be >= 1");
5396             }
5397             for (int i=0; i<intents.length; i++) {
5398                 Intent intent = intents[i];
5399                 if (intent != null) {
5400                     if (intent.hasFileDescriptors()) {
5401                         throw new IllegalArgumentException("File descriptors passed in Intent");
5402                     }
5403                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
5404                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5405                         throw new IllegalArgumentException(
5406                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5407                     }
5408                     intents[i] = new Intent(intent);
5409                 }
5410             }
5411             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
5412                 throw new IllegalArgumentException(
5413                         "Intent array length does not match resolvedTypes length");
5414             }
5415         }
5416         if (bOptions != null) {
5417             if (bOptions.hasFileDescriptors()) {
5418                 throw new IllegalArgumentException("File descriptors passed in options");
5419             }
5420         }
5421 
5422         int callingUid = Binder.getCallingUid();
5423         int origUserId = userId;
5424         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
5425                 type == ActivityManager.INTENT_SENDER_BROADCAST,
5426                 ALLOW_NON_FULL, "getIntentSender", null);
5427         if (origUserId == UserHandle.USER_CURRENT) {
5428             // We don't want to evaluate this until the pending intent is
5429             // actually executed.  However, we do want to always do the
5430             // security checking for it above.
5431             userId = UserHandle.USER_CURRENT;
5432         }
5433         try {
5434             if (callingUid != 0 && callingUid != SYSTEM_UID) {
5435                 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
5436                         MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callingUid));
5437                 if (!UserHandle.isSameApp(callingUid, uid)) {
5438                     String msg = "Permission Denial: getIntentSender() from pid="
5439                         + Binder.getCallingPid()
5440                         + ", uid=" + Binder.getCallingUid()
5441                         + ", (need uid=" + uid + ")"
5442                         + " is not allowed to send as package " + packageName;
5443                     Slog.w(TAG, msg);
5444                     throw new SecurityException(msg);
5445                 }
5446             }
5447 
5448             if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5449                 return mAtmInternal.getIntentSender(type, packageName, callingUid, userId,
5450                         token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
5451             }
5452             return mPendingIntentController.getIntentSender(type, packageName, callingUid,
5453                     userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5454                     bOptions);
5455         } catch (RemoteException e) {
5456             throw new SecurityException(e);
5457         }
5458     }
5459 
5460     @Override
sendIntentSender(IIntentSender target, IBinder whitelistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5461     public int sendIntentSender(IIntentSender target, IBinder whitelistToken, int code,
5462             Intent intent, String resolvedType,
5463             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
5464         if (target instanceof PendingIntentRecord) {
5465             return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType,
5466                     whitelistToken, finishedReceiver, requiredPermission, options);
5467         } else {
5468             if (intent == null) {
5469                 // Weird case: someone has given us their own custom IIntentSender, and now
5470                 // they have someone else trying to send to it but of course this isn't
5471                 // really a PendingIntent, so there is no base Intent, and the caller isn't
5472                 // supplying an Intent... but we never want to dispatch a null Intent to
5473                 // a receiver, so um...  let's make something up.
5474                 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
5475                 intent = new Intent(Intent.ACTION_MAIN);
5476             }
5477             try {
5478                 target.send(code, intent, resolvedType, whitelistToken, null,
5479                         requiredPermission, options);
5480             } catch (RemoteException e) {
5481             }
5482             // Platform code can rely on getting a result back when the send is done, but if
5483             // this intent sender is from outside of the system we can't rely on it doing that.
5484             // So instead we don't give it the result receiver, and instead just directly
5485             // report the finish immediately.
5486             if (finishedReceiver != null) {
5487                 try {
5488                     finishedReceiver.performReceive(intent, 0,
5489                             null, null, false, false, UserHandle.getCallingUserId());
5490                 } catch (RemoteException e) {
5491                 }
5492             }
5493             return 0;
5494         }
5495     }
5496 
5497     @Override
cancelIntentSender(IIntentSender sender)5498     public void cancelIntentSender(IIntentSender sender) {
5499         mPendingIntentController.cancelIntentSender(sender);
5500     }
5501 
5502     @Override
getPackageForIntentSender(IIntentSender pendingResult)5503     public String getPackageForIntentSender(IIntentSender pendingResult) {
5504         if (!(pendingResult instanceof PendingIntentRecord)) {
5505             return null;
5506         }
5507         try {
5508             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5509             return res.key.packageName;
5510         } catch (ClassCastException e) {
5511         }
5512         return null;
5513     }
5514 
5515     @Override
registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5516     public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) {
5517         mPendingIntentController.registerIntentSenderCancelListener(sender, receiver);
5518     }
5519 
5520     @Override
unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5521     public void unregisterIntentSenderCancelListener(IIntentSender sender,
5522             IResultReceiver receiver) {
5523         mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver);
5524     }
5525 
5526     @Override
getUidForIntentSender(IIntentSender sender)5527     public int getUidForIntentSender(IIntentSender sender) {
5528         if (sender instanceof PendingIntentRecord) {
5529             try {
5530                 PendingIntentRecord res = (PendingIntentRecord)sender;
5531                 return res.uid;
5532             } catch (ClassCastException e) {
5533             }
5534         }
5535         return -1;
5536     }
5537 
5538     @Override
isIntentSenderTargetedToPackage(IIntentSender pendingResult)5539     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5540         if (!(pendingResult instanceof PendingIntentRecord)) {
5541             return false;
5542         }
5543         try {
5544             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5545             if (res.key.allIntents == null) {
5546                 return false;
5547             }
5548             for (int i=0; i<res.key.allIntents.length; i++) {
5549                 Intent intent = res.key.allIntents[i];
5550                 if (intent.getPackage() != null && intent.getComponent() != null) {
5551                     return false;
5552                 }
5553             }
5554             return true;
5555         } catch (ClassCastException e) {
5556         }
5557         return false;
5558     }
5559 
5560     @Override
isIntentSenderAnActivity(IIntentSender pendingResult)5561     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
5562         if (!(pendingResult instanceof PendingIntentRecord)) {
5563             return false;
5564         }
5565         try {
5566             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5567             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
5568                 return true;
5569             }
5570             return false;
5571         } catch (ClassCastException e) {
5572         }
5573         return false;
5574     }
5575 
5576     @Override
isIntentSenderAForegroundService(IIntentSender pendingResult)5577     public boolean isIntentSenderAForegroundService(IIntentSender pendingResult) {
5578         if (pendingResult instanceof PendingIntentRecord) {
5579             final PendingIntentRecord res = (PendingIntentRecord) pendingResult;
5580             return res.key.type == ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE;
5581         }
5582         return false;
5583     }
5584 
5585     @Override
isIntentSenderABroadcast(IIntentSender pendingResult)5586     public boolean isIntentSenderABroadcast(IIntentSender pendingResult) {
5587         if (pendingResult instanceof PendingIntentRecord) {
5588             final PendingIntentRecord res = (PendingIntentRecord) pendingResult;
5589             return res.key.type == ActivityManager.INTENT_SENDER_BROADCAST;
5590         }
5591         return false;
5592     }
5593 
5594     @Override
getIntentForIntentSender(IIntentSender pendingResult)5595     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
5596         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5597                 "getIntentForIntentSender()");
5598         if (!(pendingResult instanceof PendingIntentRecord)) {
5599             return null;
5600         }
5601         try {
5602             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5603             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
5604         } catch (ClassCastException e) {
5605         }
5606         return null;
5607     }
5608 
5609     @Override
getTagForIntentSender(IIntentSender pendingResult, String prefix)5610     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
5611         if (!(pendingResult instanceof PendingIntentRecord)) {
5612             return null;
5613         }
5614         try {
5615             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5616             synchronized (this) {
5617                 return getTagForIntentSenderLocked(res, prefix);
5618             }
5619         } catch (ClassCastException e) {
5620         }
5621         return null;
5622     }
5623 
getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5624     String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
5625         final Intent intent = res.key.requestIntent;
5626         if (intent != null) {
5627             if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
5628                     || res.lastTagPrefix.equals(prefix))) {
5629                 return res.lastTag;
5630             }
5631             res.lastTagPrefix = prefix;
5632             final StringBuilder sb = new StringBuilder(128);
5633             if (prefix != null) {
5634                 sb.append(prefix);
5635             }
5636             if (intent.getAction() != null) {
5637                 sb.append(intent.getAction());
5638             } else if (intent.getComponent() != null) {
5639                 intent.getComponent().appendShortString(sb);
5640             } else {
5641                 sb.append("?");
5642             }
5643             return res.lastTag = sb.toString();
5644         }
5645         return null;
5646     }
5647 
5648     @Override
setProcessLimit(int max)5649     public void setProcessLimit(int max) {
5650         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5651                 "setProcessLimit()");
5652         synchronized (this) {
5653             mConstants.setOverrideMaxCachedProcesses(max);
5654         }
5655         trimApplications(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
5656     }
5657 
5658     @Override
getProcessLimit()5659     public int getProcessLimit() {
5660         synchronized (this) {
5661             return mConstants.getOverrideMaxCachedProcesses();
5662         }
5663     }
5664 
importanceTokenDied(ImportanceToken token)5665     void importanceTokenDied(ImportanceToken token) {
5666         synchronized (ActivityManagerService.this) {
5667             synchronized (mPidsSelfLocked) {
5668                 ImportanceToken cur
5669                     = mImportantProcesses.get(token.pid);
5670                 if (cur != token) {
5671                     return;
5672                 }
5673                 mImportantProcesses.remove(token.pid);
5674                 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5675                 if (pr == null) {
5676                     return;
5677                 }
5678                 pr.forcingToImportant = null;
5679                 updateProcessForegroundLocked(pr, false, 0, false);
5680             }
5681             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5682         }
5683     }
5684 
5685     @Override
setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5686     public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
5687         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5688                 "setProcessImportant()");
5689         synchronized(this) {
5690             boolean changed = false;
5691 
5692             synchronized (mPidsSelfLocked) {
5693                 ProcessRecord pr = mPidsSelfLocked.get(pid);
5694                 if (pr == null && isForeground) {
5695                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5696                     return;
5697                 }
5698                 ImportanceToken oldToken = mImportantProcesses.get(pid);
5699                 if (oldToken != null) {
5700                     oldToken.token.unlinkToDeath(oldToken, 0);
5701                     mImportantProcesses.remove(pid);
5702                     if (pr != null) {
5703                         pr.forcingToImportant = null;
5704                     }
5705                     changed = true;
5706                 }
5707                 if (isForeground && token != null) {
5708                     ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
5709                         @Override
5710                         public void binderDied() {
5711                             importanceTokenDied(this);
5712                         }
5713                     };
5714                     try {
5715                         token.linkToDeath(newToken, 0);
5716                         mImportantProcesses.put(pid, newToken);
5717                         pr.forcingToImportant = newToken;
5718                         changed = true;
5719                     } catch (RemoteException e) {
5720                         // If the process died while doing this, we will later
5721                         // do the cleanup with the process death link.
5722                     }
5723                 }
5724             }
5725 
5726             if (changed) {
5727                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5728             }
5729         }
5730     }
5731 
isAppForeground(int uid)5732     private boolean isAppForeground(int uid) {
5733         synchronized (this) {
5734             UidRecord uidRec = mProcessList.mActiveUids.get(uid);
5735             if (uidRec == null || uidRec.idle) {
5736                 return false;
5737             }
5738             return uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
5739         }
5740     }
5741 
isAppBad(ApplicationInfo info)5742     private boolean isAppBad(ApplicationInfo info) {
5743         synchronized (this) {
5744             return mAppErrors.isBadProcessLocked(info);
5745         }
5746     }
5747 
5748     // NOTE: this is an internal method used by the OnShellCommand implementation only and should
5749     // be guarded by permission checking.
getUidState(int uid)5750     int getUidState(int uid) {
5751         synchronized (this) {
5752             return mProcessList.getUidProcStateLocked(uid);
5753         }
5754     }
5755 
5756     // =========================================================
5757     // PROCESS INFO
5758     // =========================================================
5759 
5760     static class ProcessInfoService extends IProcessInfoService.Stub {
5761         final ActivityManagerService mActivityManagerService;
ProcessInfoService(ActivityManagerService activityManagerService)5762         ProcessInfoService(ActivityManagerService activityManagerService) {
5763             mActivityManagerService = activityManagerService;
5764         }
5765 
5766         @Override
getProcessStatesFromPids( int[] pids, int[] states)5767         public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
5768             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5769                     /*in*/ pids, /*out*/ states, null);
5770         }
5771 
5772         @Override
getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5773         public void getProcessStatesAndOomScoresFromPids(
5774                 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5775             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5776                     /*in*/ pids, /*out*/ states, /*out*/ scores);
5777         }
5778     }
5779 
5780     /**
5781      * For each PID in the given input array, write the current process state
5782      * for that process into the states array, or -1 to indicate that no
5783      * process with the given PID exists. If scores array is provided, write
5784      * the oom score for the process into the scores array, with INVALID_ADJ
5785      * indicating the PID doesn't exist.
5786      */
getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5787     public void getProcessStatesAndOomScoresForPIDs(
5788             /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5789         if (scores != null) {
5790             enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
5791                     "getProcessStatesAndOomScoresForPIDs()");
5792         }
5793 
5794         if (pids == null) {
5795             throw new NullPointerException("pids");
5796         } else if (states == null) {
5797             throw new NullPointerException("states");
5798         } else if (pids.length != states.length) {
5799             throw new IllegalArgumentException("pids and states arrays have different lengths!");
5800         } else if (scores != null && pids.length != scores.length) {
5801             throw new IllegalArgumentException("pids and scores arrays have different lengths!");
5802         }
5803 
5804         synchronized (mPidsSelfLocked) {
5805             for (int i = 0; i < pids.length; i++) {
5806                 ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
5807                 states[i] = (pr == null) ? PROCESS_STATE_NONEXISTENT : pr.getCurProcState();
5808                 if (scores != null) {
5809                     scores[i] = (pr == null) ? ProcessList.INVALID_ADJ : pr.curAdj;
5810                 }
5811             }
5812         }
5813     }
5814 
5815     // =========================================================
5816     // PERMISSIONS
5817     // =========================================================
5818 
5819     static class PermissionController extends IPermissionController.Stub {
5820         ActivityManagerService mActivityManagerService;
PermissionController(ActivityManagerService activityManagerService)5821         PermissionController(ActivityManagerService activityManagerService) {
5822             mActivityManagerService = activityManagerService;
5823         }
5824 
5825         @Override
checkPermission(String permission, int pid, int uid)5826         public boolean checkPermission(String permission, int pid, int uid) {
5827             return mActivityManagerService.checkPermission(permission, pid,
5828                     uid) == PackageManager.PERMISSION_GRANTED;
5829         }
5830 
5831         @Override
noteOp(String op, int uid, String packageName)5832         public int noteOp(String op, int uid, String packageName) {
5833             return mActivityManagerService.mAppOpsService
5834                     .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName);
5835         }
5836 
5837         @Override
getPackagesForUid(int uid)5838         public String[] getPackagesForUid(int uid) {
5839             return mActivityManagerService.mContext.getPackageManager()
5840                     .getPackagesForUid(uid);
5841         }
5842 
5843         @Override
isRuntimePermission(String permission)5844         public boolean isRuntimePermission(String permission) {
5845             try {
5846                 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
5847                         .getPermissionInfo(permission, 0);
5848                 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
5849                         == PermissionInfo.PROTECTION_DANGEROUS;
5850             } catch (NameNotFoundException nnfe) {
5851                 Slog.e(TAG, "No such permission: "+ permission, nnfe);
5852             }
5853             return false;
5854         }
5855 
5856         @Override
getPackageUid(String packageName, int flags)5857         public int getPackageUid(String packageName, int flags) {
5858             try {
5859                 return mActivityManagerService.mContext.getPackageManager()
5860                         .getPackageUid(packageName, flags);
5861             } catch (NameNotFoundException nnfe) {
5862                 return -1;
5863             }
5864         }
5865     }
5866 
5867     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
5868         @Override
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5869         public int checkComponentPermission(String permission, int pid, int uid,
5870                 int owningUid, boolean exported) {
5871             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
5872                     owningUid, exported);
5873         }
5874 
5875         @Override
getAMSLock()5876         public Object getAMSLock() {
5877             return ActivityManagerService.this;
5878         }
5879     }
5880 
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5881     public static int checkComponentPermission(String permission, int pid, int uid,
5882             int owningUid, boolean exported) {
5883         if (pid == MY_PID) {
5884             return PackageManager.PERMISSION_GRANTED;
5885         }
5886         return ActivityManager.checkComponentPermission(permission, uid,
5887                 owningUid, exported);
5888     }
5889 
5890     /**
5891      * As the only public entry point for permissions checking, this method
5892      * can enforce the semantic that requesting a check on a null global
5893      * permission is automatically denied.  (Internally a null permission
5894      * string is used when calling {@link #checkComponentPermission} in cases
5895      * when only uid-based security is needed.)
5896      *
5897      * This can be called with or without the global lock held.
5898      */
5899     @Override
checkPermission(String permission, int pid, int uid)5900     public int checkPermission(String permission, int pid, int uid) {
5901         if (permission == null) {
5902             return PackageManager.PERMISSION_DENIED;
5903         }
5904         return checkComponentPermission(permission, pid, uid, -1, true);
5905     }
5906 
5907     @Override
checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken)5908     public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) {
5909         if (permission == null) {
5910             return PackageManager.PERMISSION_DENIED;
5911         }
5912 
5913         // We might be performing an operation on behalf of an indirect binder
5914         // invocation, e.g. via {@link #openContentUri}.  Check and adjust the
5915         // client identity accordingly before proceeding.
5916         Identity tlsIdentity = sCallerIdentity.get();
5917         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
5918             Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
5919                     + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
5920             uid = tlsIdentity.uid;
5921             pid = tlsIdentity.pid;
5922         }
5923 
5924         return checkComponentPermission(permission, pid, uid, -1, true);
5925     }
5926 
5927     /**
5928      * Binder IPC calls go through the public entry point.
5929      * This can be called with or without the global lock held.
5930      */
checkCallingPermission(String permission)5931     int checkCallingPermission(String permission) {
5932         return checkPermission(permission,
5933                 Binder.getCallingPid(),
5934                 Binder.getCallingUid());
5935     }
5936 
5937     /**
5938      * This can be called with or without the global lock held.
5939      */
enforceCallingPermission(String permission, String func)5940     void enforceCallingPermission(String permission, String func) {
5941         if (checkCallingPermission(permission)
5942                 == PackageManager.PERMISSION_GRANTED) {
5943             return;
5944         }
5945 
5946         String msg = "Permission Denial: " + func + " from pid="
5947                 + Binder.getCallingPid()
5948                 + ", uid=" + Binder.getCallingUid()
5949                 + " requires " + permission;
5950         Slog.w(TAG, msg);
5951         throw new SecurityException(msg);
5952     }
5953 
5954     /**
5955      * This can be called with or without the global lock held.
5956      */
enforcePermission(String permission, int pid, int uid, String func)5957     void enforcePermission(String permission, int pid, int uid, String func) {
5958         if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) {
5959             return;
5960         }
5961 
5962         String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid
5963                 + " requires " + permission;
5964         Slog.w(TAG, msg);
5965         throw new SecurityException(msg);
5966     }
5967 
isAppStartModeDisabled(int uid, String packageName)5968     public boolean isAppStartModeDisabled(int uid, String packageName) {
5969         synchronized (this) {
5970             return getAppStartModeLocked(uid, packageName, 0, -1, false, true, false)
5971                     == ActivityManager.APP_START_MODE_DISABLED;
5972         }
5973     }
5974 
5975     // Unified app-op and target sdk check
appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)5976     int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
5977         // Apps that target O+ are always subject to background check
5978         if (packageTargetSdk >= Build.VERSION_CODES.O) {
5979             if (DEBUG_BACKGROUND_CHECK) {
5980                 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
5981             }
5982             return ActivityManager.APP_START_MODE_DELAYED_RIGID;
5983         }
5984         // ...and legacy apps get an AppOp check
5985         int appop = mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
5986                 uid, packageName);
5987         if (DEBUG_BACKGROUND_CHECK) {
5988             Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
5989         }
5990         switch (appop) {
5991             case AppOpsManager.MODE_ALLOWED:
5992                 // If force-background-check is enabled, restrict all apps that aren't whitelisted.
5993                 if (mForceBackgroundCheck &&
5994                         !UserHandle.isCore(uid) &&
5995                         !isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ true)) {
5996                     if (DEBUG_BACKGROUND_CHECK) {
5997                         Slog.i(TAG, "Force background check: " +
5998                                 uid + "/" + packageName + " restricted");
5999                     }
6000                     return ActivityManager.APP_START_MODE_DELAYED;
6001                 }
6002                 return ActivityManager.APP_START_MODE_NORMAL;
6003             case AppOpsManager.MODE_IGNORED:
6004                 return ActivityManager.APP_START_MODE_DELAYED;
6005             default:
6006                 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
6007         }
6008     }
6009 
6010     // Service launch is available to apps with run-in-background exemptions but
6011     // some other background operations are not.  If we're doing a check
6012     // of service-launch policy, allow those callers to proceed unrestricted.
appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)6013     int appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
6014         // Persistent app?
6015         if (mPackageManagerInt.isPackagePersistent(packageName)) {
6016             if (DEBUG_BACKGROUND_CHECK) {
6017                 Slog.i(TAG, "App " + uid + "/" + packageName
6018                         + " is persistent; not restricted in background");
6019             }
6020             return ActivityManager.APP_START_MODE_NORMAL;
6021         }
6022 
6023         // Non-persistent but background whitelisted?
6024         if (uidOnBackgroundWhitelist(uid)) {
6025             if (DEBUG_BACKGROUND_CHECK) {
6026                 Slog.i(TAG, "App " + uid + "/" + packageName
6027                         + " on background whitelist; not restricted in background");
6028             }
6029             return ActivityManager.APP_START_MODE_NORMAL;
6030         }
6031 
6032         // Is this app on the battery whitelist?
6033         if (isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ false)) {
6034             if (DEBUG_BACKGROUND_CHECK) {
6035                 Slog.i(TAG, "App " + uid + "/" + packageName
6036                         + " on idle whitelist; not restricted in background");
6037             }
6038             return ActivityManager.APP_START_MODE_NORMAL;
6039         }
6040 
6041         // None of the service-policy criteria apply, so we apply the common criteria
6042         return appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk);
6043     }
6044 
getAppStartModeLocked(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6045     int getAppStartModeLocked(int uid, String packageName, int packageTargetSdk,
6046             int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) {
6047         UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
6048         if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
6049                 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
6050                 + (uidRec != null ? uidRec.idle : false));
6051         if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.idle) {
6052             boolean ephemeral;
6053             if (uidRec == null) {
6054                 ephemeral = getPackageManagerInternalLocked().isPackageEphemeral(
6055                         UserHandle.getUserId(uid), packageName);
6056             } else {
6057                 ephemeral = uidRec.ephemeral;
6058             }
6059 
6060             if (ephemeral) {
6061                 // We are hard-core about ephemeral apps not running in the background.
6062                 return ActivityManager.APP_START_MODE_DISABLED;
6063             } else {
6064                 if (disabledOnly) {
6065                     // The caller is only interested in whether app starts are completely
6066                     // disabled for the given package (that is, it is an instant app).  So
6067                     // we don't need to go further, which is all just seeing if we should
6068                     // apply a "delayed" mode for a regular app.
6069                     return ActivityManager.APP_START_MODE_NORMAL;
6070                 }
6071                 final int startMode = (alwaysRestrict)
6072                         ? appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk)
6073                         : appServicesRestrictedInBackgroundLocked(uid, packageName,
6074                                 packageTargetSdk);
6075                 if (DEBUG_BACKGROUND_CHECK) {
6076                     Slog.d(TAG, "checkAllowBackground: uid=" + uid
6077                             + " pkg=" + packageName + " startMode=" + startMode
6078                             + " onwhitelist=" + isOnDeviceIdleWhitelistLocked(uid, false)
6079                             + " onwhitelist(ei)=" + isOnDeviceIdleWhitelistLocked(uid, true));
6080                 }
6081                 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
6082                     // This is an old app that has been forced into a "compatible as possible"
6083                     // mode of background check.  To increase compatibility, we will allow other
6084                     // foreground apps to cause its services to start.
6085                     if (callingPid >= 0) {
6086                         ProcessRecord proc;
6087                         synchronized (mPidsSelfLocked) {
6088                             proc = mPidsSelfLocked.get(callingPid);
6089                         }
6090                         if (proc != null &&
6091                                 !ActivityManager.isProcStateBackground(proc.getCurProcState())) {
6092                             // Whoever is instigating this is in the foreground, so we will allow it
6093                             // to go through.
6094                             return ActivityManager.APP_START_MODE_NORMAL;
6095                         }
6096                     }
6097                 }
6098                 return startMode;
6099             }
6100         }
6101         return ActivityManager.APP_START_MODE_NORMAL;
6102     }
6103 
6104     /**
6105      * @return whether a UID is in the system, user or temp doze whitelist.
6106      */
isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo)6107     boolean isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo) {
6108         final int appId = UserHandle.getAppId(uid);
6109 
6110         final int[] whitelist = allowExceptIdleToo
6111                 ? mDeviceIdleExceptIdleWhitelist
6112                 : mDeviceIdleWhitelist;
6113 
6114         return Arrays.binarySearch(whitelist, appId) >= 0
6115                 || Arrays.binarySearch(mDeviceIdleTempWhitelist, appId) >= 0
6116                 || mPendingTempWhitelist.indexOfKey(uid) >= 0;
6117     }
6118 
6119     /**
6120      * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6121      * the whitelist
6122      */
getPendingTempWhitelistTagForUidLocked(int uid)6123     String getPendingTempWhitelistTagForUidLocked(int uid) {
6124         final PendingTempWhitelist ptw = mPendingTempWhitelist.get(uid);
6125         return ptw != null ? ptw.tag : null;
6126     }
6127 
getProviderInfoLocked(String authority, int userHandle, int pmFlags)6128     private ProviderInfo getProviderInfoLocked(String authority, int userHandle, int pmFlags) {
6129         ProviderInfo pi = null;
6130         ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
6131         if (cpr != null) {
6132             pi = cpr.info;
6133         } else {
6134             try {
6135                 pi = AppGlobals.getPackageManager().resolveContentProvider(
6136                         authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags,
6137                         userHandle);
6138             } catch (RemoteException ex) {
6139             }
6140         }
6141         return pi;
6142     }
6143 
6144     @VisibleForTesting
grantEphemeralAccessLocked(int userId, Intent intent, int targetAppId, int ephemeralAppId)6145     public void grantEphemeralAccessLocked(int userId, Intent intent,
6146             int targetAppId, int ephemeralAppId) {
6147         getPackageManagerInternalLocked().
6148                 grantEphemeralAccess(userId, intent, targetAppId, ephemeralAppId);
6149     }
6150 
6151     /**
6152      * @param uri This uri must NOT contain an embedded userId.
6153      * @param userId The userId in which the uri is to be resolved.
6154      */
6155     @Override
checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6156     public int checkUriPermission(Uri uri, int pid, int uid,
6157             final int modeFlags, int userId, IBinder callerToken) {
6158         enforceNotIsolatedCaller("checkUriPermission");
6159 
6160         // Another redirected-binder-call permissions check as in
6161         // {@link checkPermissionWithToken}.
6162         Identity tlsIdentity = sCallerIdentity.get();
6163         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
6164             uid = tlsIdentity.uid;
6165             pid = tlsIdentity.pid;
6166         }
6167 
6168         // Our own process gets to do everything.
6169         if (pid == MY_PID) {
6170             return PackageManager.PERMISSION_GRANTED;
6171         }
6172         return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, false), uid, modeFlags)
6173                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
6174     }
6175 
6176     /**
6177      * @param uri This uri must NOT contain an embedded userId.
6178      * @param userId The userId in which the uri is to be resolved.
6179      */
6180     @Override
grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6181     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
6182             final int modeFlags, int userId) {
6183         enforceNotIsolatedCaller("grantUriPermission");
6184         GrantUri grantUri = new GrantUri(userId, uri, false);
6185         synchronized(this) {
6186             final ProcessRecord r = getRecordForAppLocked(caller);
6187             if (r == null) {
6188                 throw new SecurityException("Unable to find app for caller "
6189                         + caller
6190                         + " when granting permission to uri " + grantUri);
6191             }
6192             if (targetPkg == null) {
6193                 throw new IllegalArgumentException("null target");
6194             }
6195             if (grantUri == null) {
6196                 throw new IllegalArgumentException("null uri");
6197             }
6198 
6199             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
6200                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
6201                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
6202                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
6203 
6204             mUgmInternal.grantUriPermission(r.uid, targetPkg, grantUri, modeFlags, null,
6205                     UserHandle.getUserId(r.uid));
6206         }
6207     }
6208 
6209     /**
6210      * @param uri This uri must NOT contain an embedded userId.
6211      * @param userId The userId in which the uri is to be resolved.
6212      */
6213     @Override
revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6214     public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
6215             final int modeFlags, int userId) {
6216         enforceNotIsolatedCaller("revokeUriPermission");
6217         synchronized(this) {
6218             final ProcessRecord r = getRecordForAppLocked(caller);
6219             if (r == null) {
6220                 throw new SecurityException("Unable to find app for caller "
6221                         + caller
6222                         + " when revoking permission to uri " + uri);
6223             }
6224             if (uri == null) {
6225                 Slog.w(TAG, "revokeUriPermission: null uri");
6226                 return;
6227             }
6228 
6229             if (!Intent.isAccessUriMode(modeFlags)) {
6230                 return;
6231             }
6232 
6233             final String authority = uri.getAuthority();
6234             final ProviderInfo pi = getProviderInfoLocked(authority, userId,
6235                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
6236             if (pi == null) {
6237                 Slog.w(TAG, "No content provider found for permission revoke: "
6238                         + uri.toSafeString());
6239                 return;
6240             }
6241 
6242             mUgmInternal.revokeUriPermission(targetPackage, r.uid, new GrantUri(userId, uri, false),
6243                     modeFlags);
6244         }
6245     }
6246 
6247     @Override
showWaitingForDebugger(IApplicationThread who, boolean waiting)6248     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6249         synchronized (this) {
6250             ProcessRecord app =
6251                 who != null ? getRecordForAppLocked(who) : null;
6252             if (app == null) return;
6253 
6254             Message msg = Message.obtain();
6255             msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
6256             msg.obj = app;
6257             msg.arg1 = waiting ? 1 : 0;
6258             mUiHandler.sendMessage(msg);
6259         }
6260     }
6261 
6262     @Override
getMemoryInfo(ActivityManager.MemoryInfo outInfo)6263     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6264         mProcessList.getMemoryInfo(outInfo);
6265     }
6266 
6267     // =========================================================
6268     // TASK MANAGEMENT
6269     // =========================================================
6270 
6271     @Override
getTasks(int maxNum)6272     public List<RunningTaskInfo> getTasks(int maxNum) {
6273         return mActivityTaskManager.getTasks(maxNum);
6274     }
6275 
6276     @Override
getFilteredTasks(int maxNum, @ActivityType int ignoreActivityType, @WindowingMode int ignoreWindowingMode)6277     public List<RunningTaskInfo> getFilteredTasks(int maxNum, @ActivityType int ignoreActivityType,
6278             @WindowingMode int ignoreWindowingMode) {
6279         return mActivityTaskManager.getFilteredTasks(
6280                 maxNum, ignoreActivityType, ignoreWindowingMode);
6281     }
6282 
6283     @Override
cancelTaskWindowTransition(int taskId)6284     public void cancelTaskWindowTransition(int taskId) {
6285         mActivityTaskManager.cancelTaskWindowTransition(taskId);
6286     }
6287 
6288     @Override
setTaskResizeable(int taskId, int resizeableMode)6289     public void setTaskResizeable(int taskId, int resizeableMode) {
6290         mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);
6291     }
6292 
6293     @Override
getTaskSnapshot(int taskId, boolean reducedResolution)6294     public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
6295         return mActivityTaskManager.getTaskSnapshot(taskId, reducedResolution);
6296     }
6297 
6298     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)6299     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
6300         mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);
6301     }
6302 
6303     @Override
getTaskBounds(int taskId)6304     public Rect getTaskBounds(int taskId) {
6305         return mActivityTaskManager.getTaskBounds(taskId);
6306     }
6307 
6308     @Override
removeStack(int stackId)6309     public void removeStack(int stackId) {
6310         mActivityTaskManager.removeStack(stackId);
6311     }
6312 
6313     @Override
removeTask(int taskId)6314     public boolean removeTask(int taskId) {
6315         return mActivityTaskManager.removeTask(taskId);
6316     }
6317 
6318     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6319     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
6320             int flags, Bundle bOptions) {
6321         mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);
6322     }
6323 
6324     /**
6325      * Attempts to move a task backwards in z-order (the order of activities within the task is
6326      * unchanged).
6327      *
6328      * There are several possible results of this call:
6329      * - if the task is locked, then we will show the lock toast
6330      * - if there is a task behind the provided task, then that task is made visible and resumed as
6331      *   this task is moved to the back
6332      * - otherwise, if there are no other tasks in the stack:
6333      *     - if this task is in the pinned stack, then we remove the stack completely, which will
6334      *       have the effect of moving the task to the top or bottom of the fullscreen stack
6335      *       (depending on whether it is visible)
6336      *     - otherwise, we simply return home and hide this task
6337      *
6338      * @param token A reference to the activity we wish to move
6339      * @param nonRoot If false then this only works if the activity is the root
6340      *                of a task; if true it will work for any activity in a task.
6341      * @return Returns true if the move completed, false if not.
6342      */
6343     @Override
moveActivityTaskToBack(IBinder token, boolean nonRoot)6344     public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
6345         return mActivityTaskManager.moveActivityTaskToBack(token, nonRoot);
6346     }
6347 
6348     @Override
moveTaskToStack(int taskId, int stackId, boolean toTop)6349     public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
6350         mActivityTaskManager.moveTaskToStack(taskId, stackId, toTop);
6351     }
6352 
6353     @Override
resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode, boolean preserveWindows, boolean animate, int animationDuration)6354     public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
6355             boolean preserveWindows, boolean animate, int animationDuration) {
6356         mActivityTaskManager.resizeStack(stackId, destBounds, allowResizeInDockedMode,
6357                 preserveWindows, animate, animationDuration);
6358     }
6359 
6360     @Override
getRecentTasks(int maxNum, int flags, int userId)6361     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
6362             int userId) {
6363         return mActivityTaskManager.getRecentTasks(maxNum, flags, userId);
6364     }
6365 
6366     /**
6367      * Moves the top activity in the input stackId to the pinned stack.
6368      *
6369      * @param stackId Id of stack to move the top activity to pinned stack.
6370      * @param bounds Bounds to use for pinned stack.
6371      *
6372      * @return True if the top activity of the input stack was successfully moved to the pinned
6373      *          stack.
6374      */
6375     @Override
moveTopActivityToPinnedStack(int stackId, Rect bounds)6376     public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
6377         return mActivityTaskManager.moveTopActivityToPinnedStack(stackId, bounds);
6378     }
6379 
6380     @Override
resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds, Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds)6381     public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
6382             Rect tempDockedTaskInsetBounds,
6383             Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
6384         mActivityTaskManager.resizeDockedStack(dockedBounds, tempDockedTaskBounds,
6385                 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds);
6386     }
6387 
6388     @Override
positionTaskInStack(int taskId, int stackId, int position)6389     public void positionTaskInStack(int taskId, int stackId, int position) {
6390         mActivityTaskManager.positionTaskInStack(taskId, stackId, position);
6391     }
6392 
6393     @Override
getAllStackInfos()6394     public List<StackInfo> getAllStackInfos() {
6395         return mActivityTaskManager.getAllStackInfos();
6396     }
6397 
6398     @Override
getTaskForActivity(IBinder token, boolean onlyRoot)6399     public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6400         return mActivityTaskManager.getTaskForActivity(token, onlyRoot);
6401     }
6402 
6403     @Override
updateDeviceOwner(String packageName)6404     public void updateDeviceOwner(String packageName) {
6405         final int callingUid = Binder.getCallingUid();
6406         if (callingUid != 0 && callingUid != SYSTEM_UID) {
6407             throw new SecurityException("updateDeviceOwner called from non-system process");
6408         }
6409         synchronized (this) {
6410             mDeviceOwnerName = packageName;
6411         }
6412     }
6413 
6414     @Override
updateLockTaskPackages(int userId, String[] packages)6415     public void updateLockTaskPackages(int userId, String[] packages) {
6416         mActivityTaskManager.updateLockTaskPackages(userId, packages);
6417     }
6418 
6419     @Override
isInLockTaskMode()6420     public boolean isInLockTaskMode() {
6421         return mActivityTaskManager.isInLockTaskMode();
6422     }
6423 
6424     @Override
getLockTaskModeState()6425     public int getLockTaskModeState() {
6426         return mActivityTaskManager.getLockTaskModeState();
6427     }
6428 
6429     @Override
startSystemLockTaskMode(int taskId)6430     public void startSystemLockTaskMode(int taskId) throws RemoteException {
6431         mActivityTaskManager.startSystemLockTaskMode(taskId);
6432     }
6433 
6434     // =========================================================
6435     // CONTENT PROVIDERS
6436     // =========================================================
6437 
generateApplicationProvidersLocked(ProcessRecord app)6438     private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6439         List<ProviderInfo> providers = null;
6440         try {
6441             providers = AppGlobals.getPackageManager()
6442                     .queryContentProviders(app.processName, app.uid,
6443                             STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6444                                     | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
6445                     .getList();
6446         } catch (RemoteException ex) {
6447         }
6448         if (DEBUG_MU) Slog.v(TAG_MU,
6449                 "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6450         int userId = app.userId;
6451         if (providers != null) {
6452             int N = providers.size();
6453             app.pubProviders.ensureCapacity(N + app.pubProviders.size());
6454             for (int i=0; i<N; i++) {
6455                 // TODO: keep logic in sync with installEncryptionUnawareProviders
6456                 ProviderInfo cpi =
6457                     (ProviderInfo)providers.get(i);
6458                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6459                         cpi.name, cpi.flags);
6460                 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) {
6461                     // This is a singleton provider, but a user besides the
6462                     // default user is asking to initialize a process it runs
6463                     // in...  well, no, it doesn't actually run in this process,
6464                     // it runs in the process of the default user.  Get rid of it.
6465                     providers.remove(i);
6466                     N--;
6467                     i--;
6468                     continue;
6469                 }
6470 
6471                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
6472                 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
6473                 if (cpr == null) {
6474                     cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
6475                     mProviderMap.putProviderByClass(comp, cpr);
6476                 }
6477                 if (DEBUG_MU) Slog.v(TAG_MU,
6478                         "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
6479                 app.pubProviders.put(cpi.name, cpr);
6480                 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
6481                     // Don't add this if it is a platform component that is marked
6482                     // to run in multiple processes, because this is actually
6483                     // part of the framework so doesn't make sense to track as a
6484                     // separate apk in the process.
6485                     app.addPackage(cpi.applicationInfo.packageName,
6486                             cpi.applicationInfo.longVersionCode, mProcessStats);
6487                 }
6488                 notifyPackageUse(cpi.applicationInfo.packageName,
6489                                  PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
6490             }
6491         }
6492         return providers;
6493     }
6494 
6495     /**
6496      * Check if the calling UID has a possible chance at accessing the provider
6497      * at the given authority and user.
6498      */
checkContentProviderAccess(String authority, int userId)6499     public String checkContentProviderAccess(String authority, int userId) {
6500         if (userId == UserHandle.USER_ALL) {
6501             mContext.enforceCallingOrSelfPermission(
6502                     Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
6503             userId = UserHandle.getCallingUserId();
6504         }
6505 
6506         ProviderInfo cpi = null;
6507         try {
6508             cpi = AppGlobals.getPackageManager().resolveContentProvider(authority,
6509                     STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6510                             | PackageManager.MATCH_DISABLED_COMPONENTS
6511                             | PackageManager.MATCH_DIRECT_BOOT_AWARE
6512                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
6513                     userId);
6514         } catch (RemoteException ignored) {
6515         }
6516         if (cpi == null) {
6517             return "Failed to find provider " + authority + " for user " + userId
6518                     + "; expected to find a valid ContentProvider for this authority";
6519         }
6520 
6521         ProcessRecord r = null;
6522         synchronized (mPidsSelfLocked) {
6523             r = mPidsSelfLocked.get(Binder.getCallingPid());
6524         }
6525         if (r == null) {
6526             return "Failed to find PID " + Binder.getCallingPid();
6527         }
6528 
6529         synchronized (this) {
6530             return checkContentProviderPermissionLocked(cpi, r, userId, true);
6531         }
6532     }
6533 
6534     /**
6535      * Check if {@link ProcessRecord} has a possible chance at accessing the
6536      * given {@link ProviderInfo}. Final permission checking is always done
6537      * in {@link ContentProvider}.
6538      */
checkContentProviderPermissionLocked( ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser)6539     private final String checkContentProviderPermissionLocked(
6540             ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) {
6541         final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
6542         final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
6543         boolean checkedGrants = false;
6544         if (checkUser) {
6545             // Looking for cross-user grants before enforcing the typical cross-users permissions
6546             int tmpTargetUserId = mUserController.unsafeConvertIncomingUser(userId);
6547             if (tmpTargetUserId != UserHandle.getUserId(callingUid)) {
6548                 if (mUgmInternal.checkAuthorityGrants(
6549                         callingUid, cpi, tmpTargetUserId, checkUser)) {
6550                     return null;
6551                 }
6552                 checkedGrants = true;
6553             }
6554             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
6555                     ALLOW_NON_FULL, "checkContentProviderPermissionLocked " + cpi.authority, null);
6556             if (userId != tmpTargetUserId) {
6557                 // When we actually went to determine the final targer user ID, this ended
6558                 // up different than our initial check for the authority.  This is because
6559                 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to
6560                 // SELF.  So we need to re-check the grants again.
6561                 checkedGrants = false;
6562             }
6563         }
6564         if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
6565                 cpi.applicationInfo.uid, cpi.exported)
6566                 == PackageManager.PERMISSION_GRANTED) {
6567             return null;
6568         }
6569         if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
6570                 cpi.applicationInfo.uid, cpi.exported)
6571                 == PackageManager.PERMISSION_GRANTED) {
6572             return null;
6573         }
6574 
6575         PathPermission[] pps = cpi.pathPermissions;
6576         if (pps != null) {
6577             int i = pps.length;
6578             while (i > 0) {
6579                 i--;
6580                 PathPermission pp = pps[i];
6581                 String pprperm = pp.getReadPermission();
6582                 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid,
6583                         cpi.applicationInfo.uid, cpi.exported)
6584                         == PackageManager.PERMISSION_GRANTED) {
6585                     return null;
6586                 }
6587                 String ppwperm = pp.getWritePermission();
6588                 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid,
6589                         cpi.applicationInfo.uid, cpi.exported)
6590                         == PackageManager.PERMISSION_GRANTED) {
6591                     return null;
6592                 }
6593             }
6594         }
6595         if (!checkedGrants
6596                 && mUgmInternal.checkAuthorityGrants(callingUid, cpi, userId, checkUser)) {
6597             return null;
6598         }
6599 
6600         final String suffix;
6601         if (!cpi.exported) {
6602             suffix = " that is not exported from UID " + cpi.applicationInfo.uid;
6603         } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) {
6604             suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
6605         } else {
6606             suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission;
6607         }
6608         final String msg = "Permission Denial: opening provider " + cpi.name
6609                 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6610                 + ", uid=" + callingUid + ")" + suffix;
6611         Slog.w(TAG, msg);
6612         return msg;
6613     }
6614 
incProviderCountLocked(ProcessRecord r, final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, String callingPackage, String callingTag, boolean stable)6615     ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6616             final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid,
6617             String callingPackage, String callingTag, boolean stable) {
6618         if (r != null) {
6619             for (int i=0; i<r.conProviders.size(); i++) {
6620                 ContentProviderConnection conn = r.conProviders.get(i);
6621                 if (conn.provider == cpr) {
6622                     if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
6623                             "Adding provider requested by "
6624                             + r.processName + " from process "
6625                             + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6626                             + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6627                     if (stable) {
6628                         conn.stableCount++;
6629                         conn.numStableIncs++;
6630                     } else {
6631                         conn.unstableCount++;
6632                         conn.numUnstableIncs++;
6633                     }
6634                     return conn;
6635                 }
6636             }
6637             ContentProviderConnection conn = new ContentProviderConnection(cpr, r, callingPackage);
6638             conn.startAssociationIfNeeded();
6639             if (stable) {
6640                 conn.stableCount = 1;
6641                 conn.numStableIncs = 1;
6642             } else {
6643                 conn.unstableCount = 1;
6644                 conn.numUnstableIncs = 1;
6645             }
6646             cpr.connections.add(conn);
6647             r.conProviders.add(conn);
6648             startAssociationLocked(r.uid, r.processName, r.getCurProcState(),
6649                     cpr.uid, cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
6650             return conn;
6651         }
6652         cpr.addExternalProcessHandleLocked(externalProcessToken, callingUid, callingTag);
6653         return null;
6654     }
6655 
decProviderCountLocked(ContentProviderConnection conn, ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable)6656     boolean decProviderCountLocked(ContentProviderConnection conn,
6657             ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6658         if (conn != null) {
6659             cpr = conn.provider;
6660             if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
6661                     "Removing provider requested by "
6662                     + conn.client.processName + " from process "
6663                     + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6664                     + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6665             if (stable) {
6666                 conn.stableCount--;
6667             } else {
6668                 conn.unstableCount--;
6669             }
6670             if (conn.stableCount == 0 && conn.unstableCount == 0) {
6671                 conn.stopAssociation();
6672                 cpr.connections.remove(conn);
6673                 conn.client.conProviders.remove(conn);
6674                 if (conn.client.setProcState < PROCESS_STATE_LAST_ACTIVITY) {
6675                     // The client is more important than last activity -- note the time this
6676                     // is happening, so we keep the old provider process around a bit as last
6677                     // activity to avoid thrashing it.
6678                     if (cpr.proc != null) {
6679                         cpr.proc.lastProviderTime = SystemClock.uptimeMillis();
6680                     }
6681                 }
6682                 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid,
6683                         cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
6684                 return true;
6685             }
6686             return false;
6687         }
6688         cpr.removeExternalProcessHandleLocked(externalProcessToken);
6689         return false;
6690     }
6691 
checkTime(long startTime, String where)6692     void checkTime(long startTime, String where) {
6693         long now = SystemClock.uptimeMillis();
6694         if ((now-startTime) > 50) {
6695             // If we are taking more than 50ms, log about it.
6696             Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where);
6697         }
6698     }
6699 
6700     private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] {
6701             PROC_SPACE_TERM,
6702             PROC_SPACE_TERM|PROC_PARENS,
6703             PROC_SPACE_TERM|PROC_CHAR|PROC_OUT_LONG,        // 3: process state
6704     };
6705 
6706     private final long[] mProcessStateStatsLongs = new long[1];
6707 
isProcessAliveLocked(ProcessRecord proc)6708     private boolean isProcessAliveLocked(ProcessRecord proc) {
6709         if (proc.pid <= 0) {
6710             if (DEBUG_OOM_ADJ) Slog.d(TAG, "Process hasn't started yet: " + proc);
6711             return false;
6712         }
6713         if (proc.procStatFile == null) {
6714             proc.procStatFile = "/proc/" + proc.pid + "/stat";
6715         }
6716         mProcessStateStatsLongs[0] = 0;
6717         if (!readProcFile(proc.procStatFile, PROCESS_STATE_STATS_FORMAT, null,
6718                 mProcessStateStatsLongs, null)) {
6719             if (DEBUG_OOM_ADJ) Slog.d(TAG, "UNABLE TO RETRIEVE STATE FOR " + proc.procStatFile);
6720             return false;
6721         }
6722         final long state = mProcessStateStatsLongs[0];
6723         if (DEBUG_OOM_ADJ) Slog.d(TAG, "RETRIEVED STATE FOR " + proc.procStatFile + ": "
6724                 + (char)state);
6725         return state != 'Z' && state != 'X' && state != 'x' && state != 'K';
6726     }
6727 
checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, ProviderInfo cpi)6728     private String checkContentProviderAssociation(ProcessRecord callingApp, int callingUid,
6729             ProviderInfo cpi) {
6730         if (callingApp == null) {
6731             return validateAssociationAllowedLocked(cpi.packageName, cpi.applicationInfo.uid,
6732                     null, callingUid) ? null : "<null>";
6733         }
6734         for (int i = callingApp.pkgList.size() - 1; i >= 0; i--) {
6735             if (!validateAssociationAllowedLocked(callingApp.pkgList.keyAt(i), callingApp.uid,
6736                     cpi.packageName, cpi.applicationInfo.uid)) {
6737                 return cpi.packageName;
6738             }
6739         }
6740         return null;
6741     }
6742 
getContentProviderImpl(IApplicationThread caller, String name, IBinder token, int callingUid, String callingPackage, String callingTag, boolean stable, int userId)6743     private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
6744             String name, IBinder token, int callingUid, String callingPackage, String callingTag,
6745             boolean stable, int userId) {
6746         ContentProviderRecord cpr;
6747         ContentProviderConnection conn = null;
6748         ProviderInfo cpi = null;
6749         boolean providerRunning = false;
6750 
6751         synchronized(this) {
6752             long startTime = SystemClock.uptimeMillis();
6753 
6754             ProcessRecord r = null;
6755             if (caller != null) {
6756                 r = getRecordForAppLocked(caller);
6757                 if (r == null) {
6758                     throw new SecurityException(
6759                             "Unable to find app for caller " + caller
6760                           + " (pid=" + Binder.getCallingPid()
6761                           + ") when getting content provider " + name);
6762                 }
6763             }
6764 
6765             boolean checkCrossUser = true;
6766 
6767             checkTime(startTime, "getContentProviderImpl: getProviderByName");
6768 
6769             // First check if this content provider has been published...
6770             cpr = mProviderMap.getProviderByName(name, userId);
6771             // If that didn't work, check if it exists for user 0 and then
6772             // verify that it's a singleton provider before using it.
6773             if (cpr == null && userId != UserHandle.USER_SYSTEM) {
6774                 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM);
6775                 if (cpr != null) {
6776                     cpi = cpr.info;
6777                     if (isSingleton(cpi.processName, cpi.applicationInfo,
6778                             cpi.name, cpi.flags)
6779                             && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) {
6780                         userId = UserHandle.USER_SYSTEM;
6781                         checkCrossUser = false;
6782                     } else {
6783                         cpr = null;
6784                         cpi = null;
6785                     }
6786                 }
6787             }
6788 
6789             if (cpr != null && cpr.proc != null) {
6790                 providerRunning = !cpr.proc.killed;
6791 
6792                 // Note if killedByAm is also set, this means the provider process has just been
6793                 // killed by AM (in ProcessRecord.kill()), but appDiedLocked() hasn't been called
6794                 // yet. So we need to call appDiedLocked() here and let it clean up.
6795                 // (See the commit message on I2c4ba1e87c2d47f2013befff10c49b3dc337a9a7 to see
6796                 // how to test this case.)
6797                 if (cpr.proc.killed && cpr.proc.killedByAm) {
6798                     checkTime(startTime, "getContentProviderImpl: before appDied (killedByAm)");
6799                     final long iden = Binder.clearCallingIdentity();
6800                     try {
6801                         appDiedLocked(cpr.proc);
6802                     } finally {
6803                         Binder.restoreCallingIdentity(iden);
6804                     }
6805                     checkTime(startTime, "getContentProviderImpl: after appDied (killedByAm)");
6806                 }
6807             }
6808 
6809             if (providerRunning) {
6810                 cpi = cpr.info;
6811                 String msg;
6812 
6813                 if (r != null && cpr.canRunHere(r)) {
6814                     if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
6815                         throw new SecurityException("Content provider lookup "
6816                                 + cpr.name.flattenToShortString()
6817                                 + " failed: association not allowed with package " + msg);
6818                     }
6819                     checkTime(startTime,
6820                             "getContentProviderImpl: before checkContentProviderPermission");
6821                     if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
6822                             != null) {
6823                         throw new SecurityException(msg);
6824                     }
6825                     checkTime(startTime,
6826                             "getContentProviderImpl: after checkContentProviderPermission");
6827 
6828                     // This provider has been published or is in the process
6829                     // of being published...  but it is also allowed to run
6830                     // in the caller's process, so don't make a connection
6831                     // and just let the caller instantiate its own instance.
6832                     ContentProviderHolder holder = cpr.newHolder(null);
6833                     // don't give caller the provider object, it needs
6834                     // to make its own.
6835                     holder.provider = null;
6836                     return holder;
6837                 }
6838 
6839                 // Don't expose providers between normal apps and instant apps
6840                 try {
6841                     if (AppGlobals.getPackageManager()
6842                             .resolveContentProvider(name, 0 /*flags*/, userId) == null) {
6843                         return null;
6844                     }
6845                 } catch (RemoteException e) {
6846                 }
6847 
6848                 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
6849                     throw new SecurityException("Content provider lookup "
6850                             + cpr.name.flattenToShortString()
6851                             + " failed: association not allowed with package " + msg);
6852                 }
6853                 checkTime(startTime,
6854                         "getContentProviderImpl: before checkContentProviderPermission");
6855                 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
6856                         != null) {
6857                     throw new SecurityException(msg);
6858                 }
6859                 checkTime(startTime,
6860                         "getContentProviderImpl: after checkContentProviderPermission");
6861 
6862                 final long origId = Binder.clearCallingIdentity();
6863 
6864                 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked");
6865 
6866                 // In this case the provider instance already exists, so we can
6867                 // return it right away.
6868                 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag,
6869                         stable);
6870                 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
6871                     if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_LOW_APP_ADJ) {
6872                         // If this is a perceptible app accessing the provider,
6873                         // make sure to count it as being accessed and thus
6874                         // back up on the LRU list.  This is good because
6875                         // content providers are often expensive to start.
6876                         checkTime(startTime, "getContentProviderImpl: before updateLruProcess");
6877                         mProcessList.updateLruProcessLocked(cpr.proc, false, null);
6878                         checkTime(startTime, "getContentProviderImpl: after updateLruProcess");
6879                     }
6880                 }
6881 
6882                 checkTime(startTime, "getContentProviderImpl: before updateOomAdj");
6883                 final int verifiedAdj = cpr.proc.verifiedAdj;
6884                 boolean success = updateOomAdjLocked(cpr.proc, true,
6885                         OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
6886                 // XXX things have changed so updateOomAdjLocked doesn't actually tell us
6887                 // if the process has been successfully adjusted.  So to reduce races with
6888                 // it, we will check whether the process still exists.  Note that this doesn't
6889                 // completely get rid of races with LMK killing the process, but should make
6890                 // them much smaller.
6891                 if (success && verifiedAdj != cpr.proc.setAdj && !isProcessAliveLocked(cpr.proc)) {
6892                     success = false;
6893                 }
6894                 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name);
6895                 checkTime(startTime, "getContentProviderImpl: after updateOomAdj");
6896                 if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success);
6897                 // NOTE: there is still a race here where a signal could be
6898                 // pending on the process even though we managed to update its
6899                 // adj level.  Not sure what to do about this, but at least
6900                 // the race is now smaller.
6901                 if (!success) {
6902                     // Uh oh...  it looks like the provider's process
6903                     // has been killed on us.  We need to wait for a new
6904                     // process to be started, and make sure its death
6905                     // doesn't kill our process.
6906                     Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString()
6907                             + " is crashing; detaching " + r);
6908                     boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
6909                     checkTime(startTime, "getContentProviderImpl: before appDied");
6910                     appDiedLocked(cpr.proc);
6911                     checkTime(startTime, "getContentProviderImpl: after appDied");
6912                     if (!lastRef) {
6913                         // This wasn't the last ref our process had on
6914                         // the provider...  we have now been killed, bail.
6915                         return null;
6916                     }
6917                     providerRunning = false;
6918                     conn = null;
6919                 } else {
6920                     cpr.proc.verifiedAdj = cpr.proc.setAdj;
6921                 }
6922 
6923                 Binder.restoreCallingIdentity(origId);
6924             }
6925 
6926             if (!providerRunning) {
6927                 try {
6928                     checkTime(startTime, "getContentProviderImpl: before resolveContentProvider");
6929                     cpi = AppGlobals.getPackageManager().
6930                         resolveContentProvider(name,
6931                             STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
6932                     checkTime(startTime, "getContentProviderImpl: after resolveContentProvider");
6933                 } catch (RemoteException ex) {
6934                 }
6935                 if (cpi == null) {
6936                     return null;
6937                 }
6938                 // If the provider is a singleton AND
6939                 // (it's a call within the same user || the provider is a
6940                 // privileged app)
6941                 // Then allow connecting to the singleton provider
6942                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6943                         cpi.name, cpi.flags)
6944                         && isValidSingletonCall(r.uid, cpi.applicationInfo.uid);
6945                 if (singleton) {
6946                     userId = UserHandle.USER_SYSTEM;
6947                 }
6948                 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
6949                 checkTime(startTime, "getContentProviderImpl: got app info for user");
6950 
6951                 String msg;
6952                 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
6953                     throw new SecurityException("Content provider lookup " + name
6954                             + " failed: association not allowed with package " + msg);
6955                 }
6956                 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
6957                 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton))
6958                         != null) {
6959                     throw new SecurityException(msg);
6960                 }
6961                 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
6962 
6963                 if (!mProcessesReady
6964                         && !cpi.processName.equals("system")) {
6965                     // If this content provider does not run in the system
6966                     // process, and the system is not yet ready to run other
6967                     // processes, then fail fast instead of hanging.
6968                     throw new IllegalArgumentException(
6969                             "Attempt to launch content provider before system ready");
6970                 }
6971 
6972                 // If system providers are not installed yet we aggressively crash to avoid
6973                 // creating multiple instance of these providers and then bad things happen!
6974                 if (!mSystemProvidersInstalled && cpi.applicationInfo.isSystemApp()
6975                         && "system".equals(cpi.processName)) {
6976                     throw new IllegalStateException("Cannot access system provider: '"
6977                             + cpi.authority + "' before system providers are installed!");
6978                 }
6979 
6980                 // Make sure that the user who owns this provider is running.  If not,
6981                 // we don't want to allow it to run.
6982                 if (!mUserController.isUserRunning(userId, 0)) {
6983                     Slog.w(TAG, "Unable to launch app "
6984                             + cpi.applicationInfo.packageName + "/"
6985                             + cpi.applicationInfo.uid + " for provider "
6986                             + name + ": user " + userId + " is stopped");
6987                     return null;
6988                 }
6989 
6990                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
6991                 checkTime(startTime, "getContentProviderImpl: before getProviderByClass");
6992                 cpr = mProviderMap.getProviderByClass(comp, userId);
6993                 checkTime(startTime, "getContentProviderImpl: after getProviderByClass");
6994                 final boolean firstClass = cpr == null;
6995                 if (firstClass) {
6996                     final long ident = Binder.clearCallingIdentity();
6997 
6998                     // If permissions need a review before any of the app components can run,
6999                     // we return no provider and launch a review activity if the calling app
7000                     // is in the foreground.
7001                     if (!requestTargetProviderPermissionsReviewIfNeededLocked(cpi, r, userId)) {
7002                         return null;
7003                     }
7004 
7005                     try {
7006                         checkTime(startTime, "getContentProviderImpl: before getApplicationInfo");
7007                         ApplicationInfo ai =
7008                             AppGlobals.getPackageManager().
7009                                 getApplicationInfo(
7010                                         cpi.applicationInfo.packageName,
7011                                         STOCK_PM_FLAGS, userId);
7012                         checkTime(startTime, "getContentProviderImpl: after getApplicationInfo");
7013                         if (ai == null) {
7014                             Slog.w(TAG, "No package info for content provider "
7015                                     + cpi.name);
7016                             return null;
7017                         }
7018                         ai = getAppInfoForUser(ai, userId);
7019                         cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
7020                     } catch (RemoteException ex) {
7021                         // pm is in same process, this will never happen.
7022                     } finally {
7023                         Binder.restoreCallingIdentity(ident);
7024                     }
7025                 }
7026 
7027                 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord");
7028 
7029                 if (r != null && cpr.canRunHere(r)) {
7030                     // If this is a multiprocess provider, then just return its
7031                     // info and allow the caller to instantiate it.  Only do
7032                     // this if the provider is the same user as the caller's
7033                     // process, or can run as root (so can be in any process).
7034                     return cpr.newHolder(null);
7035                 }
7036 
7037                 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid "
7038                             + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): "
7039                             + cpr.info.name + " callers=" + Debug.getCallers(6));
7040 
7041                 // This is single process, and our app is now connecting to it.
7042                 // See if we are already in the process of launching this
7043                 // provider.
7044                 final int N = mLaunchingProviders.size();
7045                 int i;
7046                 for (i = 0; i < N; i++) {
7047                     if (mLaunchingProviders.get(i) == cpr) {
7048                         break;
7049                     }
7050                 }
7051 
7052                 // If the provider is not already being launched, then get it
7053                 // started.
7054                 if (i >= N) {
7055                     final long origId = Binder.clearCallingIdentity();
7056 
7057                     try {
7058                         // Content provider is now in use, its package can't be stopped.
7059                         try {
7060                             checkTime(startTime, "getContentProviderImpl: before set stopped state");
7061                             AppGlobals.getPackageManager().setPackageStoppedState(
7062                                     cpr.appInfo.packageName, false, userId);
7063                             checkTime(startTime, "getContentProviderImpl: after set stopped state");
7064                         } catch (RemoteException e) {
7065                         } catch (IllegalArgumentException e) {
7066                             Slog.w(TAG, "Failed trying to unstop package "
7067                                     + cpr.appInfo.packageName + ": " + e);
7068                         }
7069 
7070                         // Use existing process if already started
7071                         checkTime(startTime, "getContentProviderImpl: looking for process record");
7072                         ProcessRecord proc = getProcessRecordLocked(
7073                                 cpi.processName, cpr.appInfo.uid, false);
7074                         if (proc != null && proc.thread != null && !proc.killed) {
7075                             if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER,
7076                                     "Installing in existing process " + proc);
7077                             if (!proc.pubProviders.containsKey(cpi.name)) {
7078                                 checkTime(startTime, "getContentProviderImpl: scheduling install");
7079                                 proc.pubProviders.put(cpi.name, cpr);
7080                                 try {
7081                                     proc.thread.scheduleInstallProvider(cpi);
7082                                 } catch (RemoteException e) {
7083                                 }
7084                             }
7085                         } else {
7086                             checkTime(startTime, "getContentProviderImpl: before start process");
7087                             proc = startProcessLocked(cpi.processName,
7088                                     cpr.appInfo, false, 0,
7089                                     new HostingRecord("content provider",
7090                                         new ComponentName(cpi.applicationInfo.packageName,
7091                                                 cpi.name)),
7092                                     ZYGOTE_POLICY_FLAG_EMPTY, false, false, false);
7093                             checkTime(startTime, "getContentProviderImpl: after start process");
7094                             if (proc == null) {
7095                                 Slog.w(TAG, "Unable to launch app "
7096                                         + cpi.applicationInfo.packageName + "/"
7097                                         + cpi.applicationInfo.uid + " for provider "
7098                                         + name + ": process is bad");
7099                                 return null;
7100                             }
7101                         }
7102                         cpr.launchingApp = proc;
7103                         mLaunchingProviders.add(cpr);
7104                     } finally {
7105                         Binder.restoreCallingIdentity(origId);
7106                     }
7107                 }
7108 
7109                 checkTime(startTime, "getContentProviderImpl: updating data structures");
7110 
7111                 // Make sure the provider is published (the same provider class
7112                 // may be published under multiple names).
7113                 if (firstClass) {
7114                     mProviderMap.putProviderByClass(comp, cpr);
7115                 }
7116 
7117                 mProviderMap.putProviderByName(name, cpr);
7118                 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag,
7119                         stable);
7120                 if (conn != null) {
7121                     conn.waiting = true;
7122                 }
7123             }
7124             checkTime(startTime, "getContentProviderImpl: done!");
7125 
7126             grantEphemeralAccessLocked(userId, null /*intent*/,
7127                     UserHandle.getAppId(cpi.applicationInfo.uid),
7128                     UserHandle.getAppId(Binder.getCallingUid()));
7129         }
7130 
7131         // Wait for the provider to be published...
7132         final long timeout = SystemClock.uptimeMillis() + CONTENT_PROVIDER_WAIT_TIMEOUT;
7133         boolean timedOut = false;
7134         synchronized (cpr) {
7135             while (cpr.provider == null) {
7136                 if (cpr.launchingApp == null) {
7137                     Slog.w(TAG, "Unable to launch app "
7138                             + cpi.applicationInfo.packageName + "/"
7139                             + cpi.applicationInfo.uid + " for provider "
7140                             + name + ": launching app became null");
7141                     EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
7142                             UserHandle.getUserId(cpi.applicationInfo.uid),
7143                             cpi.applicationInfo.packageName,
7144                             cpi.applicationInfo.uid, name);
7145                     return null;
7146                 }
7147                 try {
7148                     final long wait = Math.max(0L, timeout - SystemClock.uptimeMillis());
7149                     if (DEBUG_MU) Slog.v(TAG_MU,
7150                             "Waiting to start provider " + cpr
7151                             + " launchingApp=" + cpr.launchingApp + " for " + wait + " ms");
7152                     if (conn != null) {
7153                         conn.waiting = true;
7154                     }
7155                     cpr.wait(wait);
7156                     if (cpr.provider == null) {
7157                         timedOut = true;
7158                         break;
7159                     }
7160                 } catch (InterruptedException ex) {
7161                 } finally {
7162                     if (conn != null) {
7163                         conn.waiting = false;
7164                     }
7165                 }
7166             }
7167         }
7168         if (timedOut) {
7169             // Note we do it afer releasing the lock.
7170             String callerName = "unknown";
7171             synchronized (this) {
7172                 final ProcessRecord record = mProcessList.getLRURecordForAppLocked(caller);
7173                 if (record != null) {
7174                     callerName = record.processName;
7175                 }
7176             }
7177 
7178             Slog.wtf(TAG, "Timeout waiting for provider "
7179                     + cpi.applicationInfo.packageName + "/"
7180                     + cpi.applicationInfo.uid + " for provider "
7181                     + name
7182                     + " providerRunning=" + providerRunning
7183                     + " caller=" + callerName + "/" + Binder.getCallingUid());
7184             return null;
7185         }
7186 
7187         return cpr.newHolder(conn);
7188     }
7189 
7190     private static final class StartActivityRunnable implements Runnable {
7191         private final Context mContext;
7192         private final Intent mIntent;
7193         private final UserHandle mUserHandle;
7194 
StartActivityRunnable(Context context, Intent intent, UserHandle userHandle)7195         StartActivityRunnable(Context context, Intent intent, UserHandle userHandle) {
7196             this.mContext = context;
7197             this.mIntent = intent;
7198             this.mUserHandle = userHandle;
7199         }
7200 
7201         @Override
run()7202         public void run() {
7203             mContext.startActivityAsUser(mIntent, mUserHandle);
7204         }
7205     }
7206 
requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, ProcessRecord r, final int userId)7207     private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi,
7208             ProcessRecord r, final int userId) {
7209         if (getPackageManagerInternalLocked().isPermissionsReviewRequired(
7210                 cpi.packageName, userId)) {
7211 
7212             final boolean callerForeground = r == null || r.setSchedGroup
7213                     != ProcessList.SCHED_GROUP_BACKGROUND;
7214 
7215             // Show a permission review UI only for starting from a foreground app
7216             if (!callerForeground) {
7217                 Slog.w(TAG, "u" + userId + " Instantiating a provider in package"
7218                         + cpi.packageName + " requires a permissions review");
7219                 return false;
7220             }
7221 
7222             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
7223             intent.addFlags(FLAG_ACTIVITY_NEW_TASK
7224                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7225             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName);
7226 
7227             if (DEBUG_PERMISSIONS_REVIEW) {
7228                 Slog.i(TAG, "u" + userId + " Launching permission review "
7229                         + "for package " + cpi.packageName);
7230             }
7231 
7232             final UserHandle userHandle = new UserHandle(userId);
7233             mHandler.post(new StartActivityRunnable(mContext, intent, userHandle));
7234 
7235             return false;
7236         }
7237 
7238         return true;
7239     }
7240 
7241     /**
7242      * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The
7243      * PackageManager could be unavailable at construction time and therefore needs to be accessed
7244      * on demand.
7245      */
7246     @VisibleForTesting
getPackageManager()7247     public IPackageManager getPackageManager() {
7248         return AppGlobals.getPackageManager();
7249     }
7250 
7251     @VisibleForTesting
getPackageManagerInternalLocked()7252     public PackageManagerInternal getPackageManagerInternalLocked() {
7253         if (mPackageManagerInt == null) {
7254             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
7255         }
7256         return mPackageManagerInt;
7257     }
7258 
7259     @Override
getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)7260     public final ContentProviderHolder getContentProvider(
7261             IApplicationThread caller, String callingPackage, String name, int userId,
7262             boolean stable) {
7263         enforceNotIsolatedCaller("getContentProvider");
7264         if (caller == null) {
7265             String msg = "null IApplicationThread when getting content provider "
7266                     + name;
7267             Slog.w(TAG, msg);
7268             throw new SecurityException(msg);
7269         }
7270         // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal
7271         // with cross-user grant.
7272         final int callingUid = Binder.getCallingUid();
7273         if (callingPackage != null && mAppOpsService.checkPackage(callingUid, callingPackage)
7274                 != AppOpsManager.MODE_ALLOWED) {
7275             throw new SecurityException("Given calling package " + callingPackage
7276                     + " does not match caller's uid " + callingUid);
7277         }
7278         return getContentProviderImpl(caller, name, null, callingUid, callingPackage,
7279                 null, stable, userId);
7280     }
7281 
getContentProviderExternal( String name, int userId, IBinder token, String tag)7282     public ContentProviderHolder getContentProviderExternal(
7283             String name, int userId, IBinder token, String tag) {
7284         enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
7285             "Do not have permission in call getContentProviderExternal()");
7286         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7287                 userId, false, ALLOW_FULL_ONLY, "getContentProvider", null);
7288         return getContentProviderExternalUnchecked(name, token, Binder.getCallingUid(),
7289                 tag != null ? tag : "*external*", userId);
7290     }
7291 
getContentProviderExternalUnchecked(String name, IBinder token, int callingUid, String callingTag, int userId)7292     private ContentProviderHolder getContentProviderExternalUnchecked(String name,
7293             IBinder token, int callingUid, String callingTag, int userId) {
7294         return getContentProviderImpl(null, name, token, callingUid, null, callingTag,
7295                 true, userId);
7296     }
7297 
7298     /**
7299      * Drop a content provider from a ProcessRecord's bookkeeping
7300      */
removeContentProvider(IBinder connection, boolean stable)7301     public void removeContentProvider(IBinder connection, boolean stable) {
7302         enforceNotIsolatedCaller("removeContentProvider");
7303         long ident = Binder.clearCallingIdentity();
7304         try {
7305             synchronized (this) {
7306                 ContentProviderConnection conn;
7307                 try {
7308                     conn = (ContentProviderConnection)connection;
7309                 } catch (ClassCastException e) {
7310                     String msg ="removeContentProvider: " + connection
7311                             + " not a ContentProviderConnection";
7312                     Slog.w(TAG, msg);
7313                     throw new IllegalArgumentException(msg);
7314                 }
7315                 if (conn == null) {
7316                     throw new NullPointerException("connection is null");
7317                 }
7318                 if (decProviderCountLocked(conn, null, null, stable)) {
7319                     updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER);
7320                 }
7321             }
7322         } finally {
7323             Binder.restoreCallingIdentity(ident);
7324         }
7325     }
7326 
7327     /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */
7328     @Deprecated
7329     @Override
removeContentProviderExternal(String name, IBinder token)7330     public void removeContentProviderExternal(String name, IBinder token) {
7331         removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId());
7332     }
7333 
7334     @Override
removeContentProviderExternalAsUser(String name, IBinder token, int userId)7335     public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) {
7336         enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
7337             "Do not have permission in call removeContentProviderExternal()");
7338         long ident = Binder.clearCallingIdentity();
7339         try {
7340             removeContentProviderExternalUnchecked(name, token, userId);
7341         } finally {
7342             Binder.restoreCallingIdentity(ident);
7343         }
7344     }
7345 
removeContentProviderExternalUnchecked(String name, IBinder token, int userId)7346     private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
7347         synchronized (this) {
7348             ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
7349             if(cpr == null) {
7350                 //remove from mProvidersByClass
7351                 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list");
7352                 return;
7353             }
7354 
7355             //update content provider record entry info
7356             ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
7357             ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
7358             if (localCpr.hasExternalProcessHandles()) {
7359                 if (localCpr.removeExternalProcessHandleLocked(token)) {
7360                     updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER);
7361                 } else {
7362                     Slog.e(TAG, "Attmpt to remove content provider " + localCpr
7363                             + " with no external reference for token: "
7364                             + token + ".");
7365                 }
7366             } else {
7367                 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
7368                         + " with no external references.");
7369             }
7370         }
7371     }
7372 
publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)7373     public final void publishContentProviders(IApplicationThread caller,
7374             List<ContentProviderHolder> providers) {
7375         if (providers == null) {
7376             return;
7377         }
7378 
7379         enforceNotIsolatedCaller("publishContentProviders");
7380         synchronized (this) {
7381             final ProcessRecord r = getRecordForAppLocked(caller);
7382             if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
7383             if (r == null) {
7384                 throw new SecurityException(
7385                         "Unable to find app for caller " + caller
7386                       + " (pid=" + Binder.getCallingPid()
7387                       + ") when publishing content providers");
7388             }
7389 
7390             final long origId = Binder.clearCallingIdentity();
7391 
7392             final int N = providers.size();
7393             for (int i = 0; i < N; i++) {
7394                 ContentProviderHolder src = providers.get(i);
7395                 if (src == null || src.info == null || src.provider == null) {
7396                     continue;
7397                 }
7398                 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
7399                 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
7400                 if (dst != null) {
7401                     ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
7402                     mProviderMap.putProviderByClass(comp, dst);
7403                     String names[] = dst.info.authority.split(";");
7404                     for (int j = 0; j < names.length; j++) {
7405                         mProviderMap.putProviderByName(names[j], dst);
7406                     }
7407 
7408                     int launchingCount = mLaunchingProviders.size();
7409                     int j;
7410                     boolean wasInLaunchingProviders = false;
7411                     for (j = 0; j < launchingCount; j++) {
7412                         if (mLaunchingProviders.get(j) == dst) {
7413                             mLaunchingProviders.remove(j);
7414                             wasInLaunchingProviders = true;
7415                             j--;
7416                             launchingCount--;
7417                         }
7418                     }
7419                     if (wasInLaunchingProviders) {
7420                         mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
7421                     }
7422                     // Make sure the package is associated with the process.
7423                     // XXX We shouldn't need to do this, since we have added the package
7424                     // when we generated the providers in generateApplicationProvidersLocked().
7425                     // But for some reason in some cases we get here with the package no longer
7426                     // added...  for now just patch it in to make things happy.
7427                     r.addPackage(dst.info.applicationInfo.packageName,
7428                             dst.info.applicationInfo.longVersionCode, mProcessStats);
7429                     synchronized (dst) {
7430                         dst.provider = src.provider;
7431                         dst.setProcess(r);
7432                         dst.notifyAll();
7433                     }
7434                     updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
7435                     maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
7436                             src.info.authority);
7437                 }
7438             }
7439 
7440             Binder.restoreCallingIdentity(origId);
7441         }
7442     }
7443 
refContentProvider(IBinder connection, int stable, int unstable)7444     public boolean refContentProvider(IBinder connection, int stable, int unstable) {
7445         ContentProviderConnection conn;
7446         try {
7447             conn = (ContentProviderConnection)connection;
7448         } catch (ClassCastException e) {
7449             String msg ="refContentProvider: " + connection
7450                     + " not a ContentProviderConnection";
7451             Slog.w(TAG, msg);
7452             throw new IllegalArgumentException(msg);
7453         }
7454         if (conn == null) {
7455             throw new NullPointerException("connection is null");
7456         }
7457 
7458         synchronized (this) {
7459             if (stable > 0) {
7460                 conn.numStableIncs += stable;
7461             }
7462             stable = conn.stableCount + stable;
7463             if (stable < 0) {
7464                 throw new IllegalStateException("stableCount < 0: " + stable);
7465             }
7466 
7467             if (unstable > 0) {
7468                 conn.numUnstableIncs += unstable;
7469             }
7470             unstable = conn.unstableCount + unstable;
7471             if (unstable < 0) {
7472                 throw new IllegalStateException("unstableCount < 0: " + unstable);
7473             }
7474 
7475             if ((stable+unstable) <= 0) {
7476                 throw new IllegalStateException("ref counts can't go to zero here: stable="
7477                         + stable + " unstable=" + unstable);
7478             }
7479             conn.stableCount = stable;
7480             conn.unstableCount = unstable;
7481             return !conn.dead;
7482         }
7483     }
7484 
unstableProviderDied(IBinder connection)7485     public void unstableProviderDied(IBinder connection) {
7486         ContentProviderConnection conn;
7487         try {
7488             conn = (ContentProviderConnection)connection;
7489         } catch (ClassCastException e) {
7490             String msg ="refContentProvider: " + connection
7491                     + " not a ContentProviderConnection";
7492             Slog.w(TAG, msg);
7493             throw new IllegalArgumentException(msg);
7494         }
7495         if (conn == null) {
7496             throw new NullPointerException("connection is null");
7497         }
7498 
7499         // Safely retrieve the content provider associated with the connection.
7500         IContentProvider provider;
7501         synchronized (this) {
7502             provider = conn.provider.provider;
7503         }
7504 
7505         if (provider == null) {
7506             // Um, yeah, we're way ahead of you.
7507             return;
7508         }
7509 
7510         // Make sure the caller is being honest with us.
7511         if (provider.asBinder().pingBinder()) {
7512             // Er, no, still looks good to us.
7513             synchronized (this) {
7514                 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
7515                         + " says " + conn + " died, but we don't agree");
7516                 return;
7517             }
7518         }
7519 
7520         // Well look at that!  It's dead!
7521         synchronized (this) {
7522             if (conn.provider.provider != provider) {
7523                 // But something changed...  good enough.
7524                 return;
7525             }
7526 
7527             ProcessRecord proc = conn.provider.proc;
7528             if (proc == null || proc.thread == null) {
7529                 // Seems like the process is already cleaned up.
7530                 return;
7531             }
7532 
7533             // As far as we're concerned, this is just like receiving a
7534             // death notification...  just a bit prematurely.
7535             reportUidInfoMessageLocked(TAG,
7536                     "Process " + proc.processName + " (pid " + proc.pid
7537                             + ") early provider death",
7538                     proc.info.uid);
7539             final long ident = Binder.clearCallingIdentity();
7540             try {
7541                 appDiedLocked(proc);
7542             } finally {
7543                 Binder.restoreCallingIdentity(ident);
7544             }
7545         }
7546     }
7547 
7548     @Override
appNotRespondingViaProvider(IBinder connection)7549     public void appNotRespondingViaProvider(IBinder connection) {
7550         enforceCallingPermission(REMOVE_TASKS, "appNotRespondingViaProvider()");
7551 
7552         final ContentProviderConnection conn = (ContentProviderConnection) connection;
7553         if (conn == null) {
7554             Slog.w(TAG, "ContentProviderConnection is null");
7555             return;
7556         }
7557 
7558         final ProcessRecord host = conn.provider.proc;
7559         if (host == null) {
7560             Slog.w(TAG, "Failed to find hosting ProcessRecord");
7561             return;
7562         }
7563 
7564         mHandler.post(new Runnable() {
7565             @Override
7566             public void run() {
7567                 host.appNotResponding(
7568                         null, null, null, null, false, "ContentProvider not responding");
7569             }
7570         });
7571     }
7572 
installSystemProviders()7573     public final void installSystemProviders() {
7574         List<ProviderInfo> providers;
7575         synchronized (this) {
7576             ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
7577             providers = generateApplicationProvidersLocked(app);
7578             if (providers != null) {
7579                 for (int i=providers.size()-1; i>=0; i--) {
7580                     ProviderInfo pi = (ProviderInfo)providers.get(i);
7581                     if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7582                         Slog.w(TAG, "Not installing system proc provider " + pi.name
7583                                 + ": not system .apk");
7584                         providers.remove(i);
7585                     }
7586                 }
7587             }
7588         }
7589         if (providers != null) {
7590             mSystemThread.installSystemProviders(providers);
7591         }
7592 
7593         synchronized (this) {
7594             mSystemProvidersInstalled = true;
7595         }
7596         mConstants.start(mContext.getContentResolver());
7597         mCoreSettingsObserver = new CoreSettingsObserver(this);
7598         mActivityTaskManager.installSystemProviders();
7599         mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
7600         SettingsToPropertiesMapper.start(mContext.getContentResolver());
7601         mOomAdjuster.initSettings();
7602 
7603         // Now that the settings provider is published we can consider sending
7604         // in a rescue party.
7605         RescueParty.onSettingsProviderPublished(mContext);
7606 
7607         //mUsageStatsService.monitorPackages();
7608     }
7609 
startPersistentApps(int matchFlags)7610     void startPersistentApps(int matchFlags) {
7611         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
7612 
7613         synchronized (this) {
7614             try {
7615                 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
7616                         .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
7617                 for (ApplicationInfo app : apps) {
7618                     if (!"android".equals(app.packageName)) {
7619                         addAppLocked(app, null, false, null /* ABI override */,
7620                                 ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
7621                     }
7622                 }
7623             } catch (RemoteException ex) {
7624             }
7625         }
7626     }
7627 
7628     /**
7629      * When a user is unlocked, we need to install encryption-unaware providers
7630      * belonging to any running apps.
7631      */
installEncryptionUnawareProviders(int userId)7632     void installEncryptionUnawareProviders(int userId) {
7633         // We're only interested in providers that are encryption unaware, and
7634         // we don't care about uninstalled apps, since there's no way they're
7635         // running at this point.
7636         final int matchFlags = GET_PROVIDERS | MATCH_DIRECT_BOOT_UNAWARE;
7637 
7638         synchronized (this) {
7639             final int NP = mProcessList.mProcessNames.getMap().size();
7640             for (int ip = 0; ip < NP; ip++) {
7641                 final SparseArray<ProcessRecord> apps = mProcessList.mProcessNames.getMap().valueAt
7642                         (ip);
7643                 final int NA = apps.size();
7644                 for (int ia = 0; ia < NA; ia++) {
7645                     final ProcessRecord app = apps.valueAt(ia);
7646                     if (app.userId != userId || app.thread == null || app.unlocked) continue;
7647 
7648                     final int NG = app.pkgList.size();
7649                     for (int ig = 0; ig < NG; ig++) {
7650                         try {
7651                             final String pkgName = app.pkgList.keyAt(ig);
7652                             final PackageInfo pkgInfo = AppGlobals.getPackageManager()
7653                                     .getPackageInfo(pkgName, matchFlags, userId);
7654                             if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) {
7655                                 for (ProviderInfo pi : pkgInfo.providers) {
7656                                     // TODO: keep in sync with generateApplicationProvidersLocked
7657                                     final boolean processMatch = Objects.equals(pi.processName,
7658                                             app.processName) || pi.multiprocess;
7659                                     final boolean userMatch = isSingleton(pi.processName,
7660                                             pi.applicationInfo, pi.name, pi.flags)
7661                                                     ? (app.userId == UserHandle.USER_SYSTEM) : true;
7662                                     if (processMatch && userMatch) {
7663                                         Log.v(TAG, "Installing " + pi);
7664                                         app.thread.scheduleInstallProvider(pi);
7665                                     } else {
7666                                         Log.v(TAG, "Skipping " + pi);
7667                                     }
7668                                 }
7669                             }
7670                         } catch (RemoteException ignored) {
7671                         }
7672                     }
7673                 }
7674             }
7675         }
7676     }
7677 
7678     /**
7679      * Allows apps to retrieve the MIME type of a URI.
7680      * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
7681      * users, then it does not need permission to access the ContentProvider.
7682      * Either, it needs cross-user uri grants.
7683      *
7684      * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7685      *
7686      * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7687      *     src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7688      */
getProviderMimeType(Uri uri, int userId)7689     public String getProviderMimeType(Uri uri, int userId) {
7690         enforceNotIsolatedCaller("getProviderMimeType");
7691         final String name = uri.getAuthority();
7692         int callingUid = Binder.getCallingUid();
7693         int callingPid = Binder.getCallingPid();
7694         long ident = 0;
7695         boolean clearedIdentity = false;
7696         userId = mUserController.unsafeConvertIncomingUser(userId);
7697         if (canClearIdentity(callingPid, callingUid, userId)) {
7698             clearedIdentity = true;
7699             ident = Binder.clearCallingIdentity();
7700         }
7701         ContentProviderHolder holder = null;
7702         try {
7703             holder = getContentProviderExternalUnchecked(name, null, callingUid,
7704                     "*getmimetype*", userId);
7705             if (holder != null) {
7706                 return holder.provider.getType(uri);
7707             }
7708         } catch (RemoteException e) {
7709             Log.w(TAG, "Content provider dead retrieving " + uri, e);
7710             return null;
7711         } catch (Exception e) {
7712             Log.w(TAG, "Exception while determining type of " + uri, e);
7713             return null;
7714         } finally {
7715             // We need to clear the identity to call removeContentProviderExternalUnchecked
7716             if (!clearedIdentity) {
7717                 ident = Binder.clearCallingIdentity();
7718             }
7719             try {
7720                 if (holder != null) {
7721                     removeContentProviderExternalUnchecked(name, null, userId);
7722                 }
7723             } finally {
7724                 Binder.restoreCallingIdentity(ident);
7725             }
7726         }
7727 
7728         return null;
7729     }
7730 
canClearIdentity(int callingPid, int callingUid, int userId)7731     private boolean canClearIdentity(int callingPid, int callingUid, int userId) {
7732         if (UserHandle.getUserId(callingUid) == userId) {
7733             return true;
7734         }
7735         if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
7736                 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
7737                 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
7738                 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
7739                 return true;
7740         }
7741         return false;
7742     }
7743 
7744     // =========================================================
7745     // GLOBAL MANAGEMENT
7746     // =========================================================
7747 
uidOnBackgroundWhitelist(final int uid)7748     private boolean uidOnBackgroundWhitelist(final int uid) {
7749         final int appId = UserHandle.getAppId(uid);
7750         final int[] whitelist = mBackgroundAppIdWhitelist;
7751         final int N = whitelist.length;
7752         for (int i = 0; i < N; i++) {
7753             if (appId == whitelist[i]) {
7754                 return true;
7755             }
7756         }
7757         return false;
7758     }
7759 
7760     @Override
isBackgroundRestricted(String packageName)7761     public boolean isBackgroundRestricted(String packageName) {
7762         final int callingUid = Binder.getCallingUid();
7763         final IPackageManager pm = AppGlobals.getPackageManager();
7764         try {
7765             final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
7766                     UserHandle.getUserId(callingUid));
7767             if (packageUid != callingUid) {
7768                 throw new IllegalArgumentException("Uid " + callingUid
7769                         + " cannot query restriction state for package " + packageName);
7770             }
7771         } catch (RemoteException exc) {
7772             // Ignore.
7773         }
7774         return isBackgroundRestrictedNoCheck(callingUid, packageName);
7775     }
7776 
isBackgroundRestrictedNoCheck(final int uid, final String packageName)7777     boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) {
7778         final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
7779                 uid, packageName);
7780         return mode != AppOpsManager.MODE_ALLOWED;
7781     }
7782 
7783     @Override
backgroundWhitelistUid(final int uid)7784     public void backgroundWhitelistUid(final int uid) {
7785         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7786             throw new SecurityException("Only the OS may call backgroundWhitelistUid()");
7787         }
7788 
7789         if (DEBUG_BACKGROUND_CHECK) {
7790             Slog.i(TAG, "Adding uid " + uid + " to bg uid whitelist");
7791         }
7792         synchronized (this) {
7793             final int N = mBackgroundAppIdWhitelist.length;
7794             int[] newList = new int[N+1];
7795             System.arraycopy(mBackgroundAppIdWhitelist, 0, newList, 0, N);
7796             newList[N] = UserHandle.getAppId(uid);
7797             mBackgroundAppIdWhitelist = newList;
7798         }
7799     }
7800 
7801     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride, int zygotePolicyFlags)7802     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7803             String abiOverride, int zygotePolicyFlags) {
7804         return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */,
7805                 false /* mountExtStorageFull */, abiOverride, zygotePolicyFlags);
7806     }
7807 
7808     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride, int zygotePolicyFlags)7809     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7810             boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride,
7811             int zygotePolicyFlags) {
7812         return addAppLocked(info, customProcess, isolated, disableHiddenApiChecks,
7813                 false /* disableTestApiChecks */, mountExtStorageFull, abiOverride,
7814                 zygotePolicyFlags);
7815     }
7816 
7817     // TODO: Move to ProcessList?
7818     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean disableTestApiChecks, boolean mountExtStorageFull, String abiOverride, int zygotePolicyFlags)7819     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7820             boolean disableHiddenApiChecks, boolean disableTestApiChecks,
7821             boolean mountExtStorageFull, String abiOverride, int zygotePolicyFlags) {
7822         ProcessRecord app;
7823         if (!isolated) {
7824             app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
7825                     info.uid, true);
7826         } else {
7827             app = null;
7828         }
7829 
7830         if (app == null) {
7831             app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0,
7832                     new HostingRecord("added application",
7833                             customProcess != null ? customProcess : info.processName));
7834             mProcessList.updateLruProcessLocked(app, false, null);
7835             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
7836         }
7837 
7838         // This package really, really can not be stopped.
7839         try {
7840             AppGlobals.getPackageManager().setPackageStoppedState(
7841                     info.packageName, false, UserHandle.getUserId(app.uid));
7842         } catch (RemoteException e) {
7843         } catch (IllegalArgumentException e) {
7844             Slog.w(TAG, "Failed trying to unstop package "
7845                     + info.packageName + ": " + e);
7846         }
7847 
7848         if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
7849             app.setPersistent(true);
7850             app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
7851         }
7852         if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7853             mPersistentStartingProcesses.add(app);
7854             mProcessList.startProcessLocked(app, new HostingRecord("added application",
7855                     customProcess != null ? customProcess : app.processName),
7856                     zygotePolicyFlags, disableHiddenApiChecks, disableTestApiChecks,
7857                     mountExtStorageFull, abiOverride);
7858         }
7859 
7860         return app;
7861     }
7862 
unhandledBack()7863     public void unhandledBack() {
7864         mActivityTaskManager.unhandledBack();
7865     }
7866 
openContentUri(String uriString)7867     public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
7868         enforceNotIsolatedCaller("openContentUri");
7869         final int userId = UserHandle.getCallingUserId();
7870         final Uri uri = Uri.parse(uriString);
7871         String name = uri.getAuthority();
7872         ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null,
7873                 Binder.getCallingUid(), "*opencontent*", userId);
7874         ParcelFileDescriptor pfd = null;
7875         if (cph != null) {
7876             // We record the binder invoker's uid in thread-local storage before
7877             // going to the content provider to open the file.  Later, in the code
7878             // that handles all permissions checks, we look for this uid and use
7879             // that rather than the Activity Manager's own uid.  The effect is that
7880             // we do the check against the caller's permissions even though it looks
7881             // to the content provider like the Activity Manager itself is making
7882             // the request.
7883             Binder token = new Binder();
7884             sCallerIdentity.set(new Identity(
7885                     token, Binder.getCallingPid(), Binder.getCallingUid()));
7886             try {
7887                 pfd = cph.provider.openFile(null, uri, "r", null, token);
7888             } catch (FileNotFoundException e) {
7889                 // do nothing; pfd will be returned null
7890             } finally {
7891                 // Ensure that whatever happens, we clean up the identity state
7892                 sCallerIdentity.remove();
7893                 // Ensure we're done with the provider.
7894                 removeContentProviderExternalUnchecked(name, null, userId);
7895             }
7896         } else {
7897             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
7898         }
7899         return pfd;
7900     }
7901 
reportGlobalUsageEventLocked(int event)7902     void reportGlobalUsageEventLocked(int event) {
7903         mUsageStatsService.reportEvent("android", mUserController.getCurrentUserId(), event);
7904         int[] profiles = mUserController.getCurrentProfileIds();
7905         if (profiles != null) {
7906             for (int i = profiles.length - 1; i >= 0; i--) {
7907                 mUsageStatsService.reportEvent((String)null, profiles[i], event);
7908             }
7909         }
7910     }
7911 
reportCurWakefulnessUsageEventLocked()7912     void reportCurWakefulnessUsageEventLocked() {
7913         reportGlobalUsageEventLocked(mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE
7914                 ? UsageEvents.Event.SCREEN_INTERACTIVE
7915                 : UsageEvents.Event.SCREEN_NON_INTERACTIVE);
7916     }
7917 
onWakefulnessChanged(int wakefulness)7918     void onWakefulnessChanged(int wakefulness) {
7919         synchronized(this) {
7920             boolean wasAwake = mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
7921             boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
7922             mWakefulness = wakefulness;
7923 
7924             if (wasAwake != isAwake) {
7925                 // Also update state in a special way for running foreground services UI.
7926                 mServices.updateScreenStateLocked(isAwake);
7927                 reportCurWakefulnessUsageEventLocked();
7928                 mActivityTaskManager.onScreenAwakeChanged(isAwake);
7929                 mOomAdjProfiler.onWakefulnessChanged(wakefulness);
7930             }
7931             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
7932         }
7933     }
7934 
7935     @Override
notifyCleartextNetwork(int uid, byte[] firstPacket)7936     public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
7937         mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
7938     }
7939 
7940     @Override
shutdown(int timeout)7941     public boolean shutdown(int timeout) {
7942         if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7943                 != PackageManager.PERMISSION_GRANTED) {
7944             throw new SecurityException("Requires permission "
7945                     + android.Manifest.permission.SHUTDOWN);
7946         }
7947 
7948         final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout);
7949 
7950         mAppOpsService.shutdown();
7951         if (mUsageStatsService != null) {
7952             mUsageStatsService.prepareShutdown();
7953         }
7954         mBatteryStatsService.shutdown();
7955         synchronized (this) {
7956             mProcessStats.shutdownLocked();
7957         }
7958 
7959         return timedout;
7960     }
7961 
7962     @Override
notifyLockedProfile(@serIdInt int userId)7963     public void notifyLockedProfile(@UserIdInt int userId) {
7964         mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId());
7965     }
7966 
7967     @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7968     public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7969         mAtmInternal.startConfirmDeviceCredentialIntent(intent, options);
7970     }
7971 
7972     @Override
stopAppSwitches()7973     public void stopAppSwitches() {
7974         mActivityTaskManager.stopAppSwitches();
7975     }
7976 
7977     @Override
resumeAppSwitches()7978     public void resumeAppSwitches() {
7979         mActivityTaskManager.resumeAppSwitches();
7980     }
7981 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7982     public void setDebugApp(String packageName, boolean waitForDebugger,
7983             boolean persistent) {
7984         enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7985                 "setDebugApp()");
7986 
7987         long ident = Binder.clearCallingIdentity();
7988         try {
7989             // Note that this is not really thread safe if there are multiple
7990             // callers into it at the same time, but that's not a situation we
7991             // care about.
7992             if (persistent) {
7993                 final ContentResolver resolver = mContext.getContentResolver();
7994                 Settings.Global.putString(
7995                     resolver, Settings.Global.DEBUG_APP,
7996                     packageName);
7997                 Settings.Global.putInt(
7998                     resolver, Settings.Global.WAIT_FOR_DEBUGGER,
7999                     waitForDebugger ? 1 : 0);
8000             }
8001 
8002             synchronized (this) {
8003                 if (!persistent) {
8004                     mOrigDebugApp = mDebugApp;
8005                     mOrigWaitForDebugger = mWaitForDebugger;
8006                 }
8007                 mDebugApp = packageName;
8008                 mWaitForDebugger = waitForDebugger;
8009                 mDebugTransient = !persistent;
8010                 if (packageName != null) {
8011                     forceStopPackageLocked(packageName, -1, false, false, true, true,
8012                             false, UserHandle.USER_ALL, "set debug app");
8013                 }
8014             }
8015         } finally {
8016             Binder.restoreCallingIdentity(ident);
8017         }
8018     }
8019 
8020     /**
8021      * Set or remove an agent to be run whenever an app with the given process name starts.
8022      *
8023      * This method will not check whether the given process name matches a debuggable app. That
8024      * would require scanning all current packages, and a rescan when new packages are installed
8025      * or updated.
8026      *
8027      * Instead, do the check when an application is started and matched to a stored agent.
8028      *
8029      * @param packageName the process name of the app.
8030      * @param agent the agent string to be used, or null to remove any previously set agent.
8031      */
8032     @Override
setAgentApp(@onNull String packageName, @Nullable String agent)8033     public void setAgentApp(@NonNull String packageName, @Nullable String agent) {
8034         synchronized (this) {
8035             // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
8036             // its own permission.
8037             if (checkCallingPermission(
8038                     android.Manifest.permission.SET_ACTIVITY_WATCHER) !=
8039                         PackageManager.PERMISSION_GRANTED) {
8040                 throw new SecurityException(
8041                         "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8042             }
8043 
8044             if (agent == null) {
8045                 if (mAppAgentMap != null) {
8046                     mAppAgentMap.remove(packageName);
8047                     if (mAppAgentMap.isEmpty()) {
8048                         mAppAgentMap = null;
8049                     }
8050                 }
8051             } else {
8052                 if (mAppAgentMap == null) {
8053                     mAppAgentMap = new HashMap<>();
8054                 }
8055                 if (mAppAgentMap.size() >= 100) {
8056                     // Limit the size of the map, to avoid OOMEs.
8057                     Slog.e(TAG, "App agent map has too many entries, cannot add " + packageName
8058                             + "/" + agent);
8059                     return;
8060                 }
8061                 mAppAgentMap.put(packageName, agent);
8062             }
8063         }
8064     }
8065 
setTrackAllocationApp(ApplicationInfo app, String processName)8066     void setTrackAllocationApp(ApplicationInfo app, String processName) {
8067         synchronized (this) {
8068             boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8069             if (!isDebuggable) {
8070                 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
8071                     throw new SecurityException("Process not debuggable: " + app.packageName);
8072                 }
8073             }
8074 
8075             mTrackAllocationApp = processName;
8076         }
8077     }
8078 
setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)8079     void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) {
8080         synchronized (this) {
8081             boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8082             if (!isDebuggable) {
8083                 if (!app.isProfileableByShell()) {
8084                     throw new SecurityException("Process not debuggable, "
8085                             + "and not profileable by shell: " + app.packageName);
8086                 }
8087             }
8088             mProfileData.setProfileApp(processName);
8089 
8090             if (mProfileData.getProfilerInfo() != null) {
8091                 if (mProfileData.getProfilerInfo().profileFd != null) {
8092                     try {
8093                         mProfileData.getProfilerInfo().profileFd.close();
8094                     } catch (IOException e) {
8095                     }
8096                 }
8097             }
8098             mProfileData.setProfilerInfo(new ProfilerInfo(profilerInfo));
8099             mProfileType = 0;
8100         }
8101     }
8102 
setNativeDebuggingAppLocked(ApplicationInfo app, String processName)8103     void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
8104         boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8105         if (!isDebuggable) {
8106             if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
8107                 throw new SecurityException("Process not debuggable: " + app.packageName);
8108             }
8109         }
8110         mNativeDebuggingApp = processName;
8111     }
8112 
8113     @Override
setAlwaysFinish(boolean enabled)8114     public void setAlwaysFinish(boolean enabled) {
8115         enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
8116                 "setAlwaysFinish()");
8117 
8118         long ident = Binder.clearCallingIdentity();
8119         try {
8120             Settings.Global.putInt(
8121                     mContext.getContentResolver(),
8122                     Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
8123 
8124             synchronized (this) {
8125                 mAlwaysFinishActivities = enabled;
8126             }
8127         } finally {
8128             Binder.restoreCallingIdentity(ident);
8129         }
8130     }
8131 
8132     @Override
setActivityController(IActivityController controller, boolean imAMonkey)8133     public void setActivityController(IActivityController controller, boolean imAMonkey) {
8134         mActivityTaskManager.setActivityController(controller, imAMonkey);
8135     }
8136 
8137     @Override
setUserIsMonkey(boolean userIsMonkey)8138     public void setUserIsMonkey(boolean userIsMonkey) {
8139         synchronized (this) {
8140             synchronized (mPidsSelfLocked) {
8141                 final int callingPid = Binder.getCallingPid();
8142                 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
8143                 if (proc == null) {
8144                     throw new SecurityException("Unknown process: " + callingPid);
8145                 }
8146                 if (proc.getActiveInstrumentation() == null
8147                         || proc.getActiveInstrumentation().mUiAutomationConnection == null) {
8148                     throw new SecurityException("Only an instrumentation process "
8149                             + "with a UiAutomation can call setUserIsMonkey");
8150                 }
8151             }
8152             mUserIsMonkey = userIsMonkey;
8153         }
8154     }
8155 
8156     @Override
isUserAMonkey()8157     public boolean isUserAMonkey() {
8158         synchronized (this) {
8159             // If there is a controller also implies the user is a monkey.
8160             return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey();
8161         }
8162     }
8163 
8164     @Override
requestSystemServerHeapDump()8165     public void requestSystemServerHeapDump() {
8166         if (!Build.IS_DEBUGGABLE) {
8167             Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build");
8168             return;
8169         }
8170         if (Binder.getCallingUid() != SYSTEM_UID) {
8171             // This also intentionally excludes secondary profiles from calling this.
8172             throw new SecurityException(
8173                     "Only the system process is allowed to request a system heap dump");
8174         }
8175         ProcessRecord pr;
8176         synchronized (mPidsSelfLocked) {
8177             pr = mPidsSelfLocked.get(myPid());
8178         }
8179         if (pr == null) {
8180             Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid());
8181             return;
8182         }
8183         synchronized (this) {
8184             startHeapDumpLocked(pr, true);
8185         }
8186     }
8187 
8188     /**
8189      * @deprecated This method is only used by a few internal components and it will soon be
8190      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8191      * No new code should be calling it.
8192      */
8193     @Deprecated
8194     @Override
requestBugReport(int bugreportType)8195     public void requestBugReport(int bugreportType) {
8196         String extraOptions = null;
8197         switch (bugreportType) {
8198             case ActivityManager.BUGREPORT_OPTION_FULL:
8199                 extraOptions = "bugreportfull";
8200                 break;
8201             case ActivityManager.BUGREPORT_OPTION_INTERACTIVE:
8202                 extraOptions = "bugreportplus";
8203                 break;
8204             case ActivityManager.BUGREPORT_OPTION_REMOTE:
8205                 extraOptions = "bugreportremote";
8206                 break;
8207             case ActivityManager.BUGREPORT_OPTION_WEAR:
8208                 extraOptions = "bugreportwear";
8209                 break;
8210             case ActivityManager.BUGREPORT_OPTION_TELEPHONY:
8211                 extraOptions = "bugreporttelephony";
8212                 break;
8213             case ActivityManager.BUGREPORT_OPTION_WIFI:
8214                 extraOptions = "bugreportwifi";
8215                 break;
8216             default:
8217                 throw new IllegalArgumentException("Provided bugreport type is not correct, value: "
8218                         + bugreportType);
8219         }
8220         // Always log caller, even if it does not have permission to dump.
8221         String type = extraOptions == null ? "bugreport" : extraOptions;
8222         Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid());
8223 
8224         enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
8225         if (extraOptions != null) {
8226             SystemProperties.set("dumpstate.options", extraOptions);
8227         }
8228         SystemProperties.set("ctl.start", "bugreport");
8229     }
8230 
8231     /**
8232      * @deprecated This method is only used by a few internal components and it will soon be
8233      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8234      * No new code should be calling it.
8235      */
8236     @Deprecated
requestBugReportWithDescription(String shareTitle, String shareDescription, int bugreportType)8237     private void requestBugReportWithDescription(String shareTitle, String shareDescription,
8238                                                  int bugreportType) {
8239         if (!TextUtils.isEmpty(shareTitle)) {
8240             if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
8241                 String errorStr = "shareTitle should be less than " +
8242                         MAX_BUGREPORT_TITLE_SIZE + " characters";
8243                 throw new IllegalArgumentException(errorStr);
8244             } else {
8245                 if (!TextUtils.isEmpty(shareDescription)) {
8246                     int length;
8247                     try {
8248                         length = shareDescription.getBytes("UTF-8").length;
8249                     } catch (UnsupportedEncodingException e) {
8250                         String errorStr = "shareDescription: UnsupportedEncodingException";
8251                         throw new IllegalArgumentException(errorStr);
8252                     }
8253                     if (length > SystemProperties.PROP_VALUE_MAX) {
8254                         String errorStr = "shareTitle should be less than " +
8255                                 SystemProperties.PROP_VALUE_MAX + " bytes";
8256                         throw new IllegalArgumentException(errorStr);
8257                     } else {
8258                         SystemProperties.set("dumpstate.options.description", shareDescription);
8259                     }
8260                 }
8261                 SystemProperties.set("dumpstate.options.title", shareTitle);
8262             }
8263         }
8264 
8265         Slog.d(TAG, "Bugreport notification title " + shareTitle
8266                 + " description " + shareDescription);
8267         requestBugReport(bugreportType);
8268     }
8269 
8270     /**
8271      * @deprecated This method is only used by a few internal components and it will soon be
8272      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8273      * No new code should be calling it.
8274      */
8275     @Deprecated
8276     @Override
requestTelephonyBugReport(String shareTitle, String shareDescription)8277     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
8278         requestBugReportWithDescription(shareTitle, shareDescription,
8279                 ActivityManager.BUGREPORT_OPTION_TELEPHONY);
8280     }
8281 
8282     /**
8283      * @deprecated This method is only used by a few internal components and it will soon be
8284      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8285      * No new code should be calling it.
8286      */
8287     @Deprecated
8288     @Override
requestWifiBugReport(String shareTitle, String shareDescription)8289     public void requestWifiBugReport(String shareTitle, String shareDescription) {
8290         requestBugReportWithDescription(shareTitle, shareDescription,
8291                 ActivityManager.BUGREPORT_OPTION_WIFI);
8292     }
8293 
registerProcessObserver(IProcessObserver observer)8294     public void registerProcessObserver(IProcessObserver observer) {
8295         enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
8296                 "registerProcessObserver()");
8297         synchronized (this) {
8298             mProcessObservers.register(observer);
8299         }
8300     }
8301 
8302     @Override
unregisterProcessObserver(IProcessObserver observer)8303     public void unregisterProcessObserver(IProcessObserver observer) {
8304         synchronized (this) {
8305             mProcessObservers.unregister(observer);
8306         }
8307     }
8308 
isActiveInstrumentation(int uid)8309     private boolean isActiveInstrumentation(int uid) {
8310         synchronized (ActivityManagerService.this) {
8311             for (int i = mActiveInstrumentation.size() - 1; i >= 0; i--) {
8312                 final ActiveInstrumentation instrumentation = mActiveInstrumentation.get(i);
8313                 for (int j = instrumentation.mRunningProcesses.size() - 1; j >= 0; j--) {
8314                     final ProcessRecord process = instrumentation.mRunningProcesses.get(j);
8315                     if (process.uid == uid) {
8316                         return true;
8317                     }
8318                 }
8319             }
8320         }
8321         return false;
8322     }
8323 
8324     @Override
getUidProcessState(int uid, String callingPackage)8325     public int getUidProcessState(int uid, String callingPackage) {
8326         if (!hasUsageStatsPermission(callingPackage)) {
8327             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8328                     "getUidProcessState");
8329         }
8330 
8331         synchronized (this) {
8332             return mProcessList.getUidProcStateLocked(uid);
8333         }
8334     }
8335 
8336     @Override
registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)8337     public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
8338             String callingPackage) {
8339         if (!hasUsageStatsPermission(callingPackage)) {
8340             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8341                     "registerUidObserver");
8342         }
8343         synchronized (this) {
8344             mUidObservers.register(observer, new UidObserverRegistration(Binder.getCallingUid(),
8345                     callingPackage, which, cutpoint));
8346         }
8347     }
8348 
8349     @Override
unregisterUidObserver(IUidObserver observer)8350     public void unregisterUidObserver(IUidObserver observer) {
8351         synchronized (this) {
8352             mUidObservers.unregister(observer);
8353         }
8354     }
8355 
8356     @Override
isUidActive(int uid, String callingPackage)8357     public boolean isUidActive(int uid, String callingPackage) {
8358         if (!hasUsageStatsPermission(callingPackage)) {
8359             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8360                     "isUidActive");
8361         }
8362         synchronized (this) {
8363             return isUidActiveLocked(uid);
8364         }
8365     }
8366 
isUidActiveLocked(int uid)8367     boolean isUidActiveLocked(int uid) {
8368         final UidRecord uidRecord = mProcessList.getUidRecordLocked(uid);
8369         return uidRecord != null && !uidRecord.setIdle;
8370     }
8371 
8372     @Override
setPersistentVrThread(int tid)8373     public void setPersistentVrThread(int tid) {
8374         mActivityTaskManager.setPersistentVrThread(tid);
8375     }
8376 
8377     /**
8378      * Schedule the given thread a normal scheduling priority.
8379      *
8380      * @param tid the tid of the thread to adjust the scheduling of.
8381      * @param suppressLogs {@code true} if any error logging should be disabled.
8382      *
8383      * @return {@code true} if this succeeded.
8384      */
scheduleAsRegularPriority(int tid, boolean suppressLogs)8385     public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
8386         try {
8387             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
8388             return true;
8389         } catch (IllegalArgumentException e) {
8390             if (!suppressLogs) {
8391                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
8392             }
8393         } catch (SecurityException e) {
8394             if (!suppressLogs) {
8395                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
8396             }
8397         }
8398         return false;
8399     }
8400 
8401     /**
8402      * Schedule the given thread an FIFO scheduling priority.
8403      *
8404      * @param tid the tid of the thread to adjust the scheduling of.
8405      * @param suppressLogs {@code true} if any error logging should be disabled.
8406      *
8407      * @return {@code true} if this succeeded.
8408      */
scheduleAsFifoPriority(int tid, boolean suppressLogs)8409     public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
8410         try {
8411             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
8412             return true;
8413         } catch (IllegalArgumentException e) {
8414             if (!suppressLogs) {
8415                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
8416             }
8417         } catch (SecurityException e) {
8418             if (!suppressLogs) {
8419                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
8420             }
8421         }
8422         return false;
8423     }
8424 
8425     @Override
setRenderThread(int tid)8426     public void setRenderThread(int tid) {
8427         synchronized (this) {
8428             ProcessRecord proc;
8429             int pid = Binder.getCallingPid();
8430             if (pid == Process.myPid()) {
8431                 demoteSystemServerRenderThread(tid);
8432                 return;
8433             }
8434             synchronized (mPidsSelfLocked) {
8435                 proc = mPidsSelfLocked.get(pid);
8436                 if (proc != null && proc.renderThreadTid == 0 && tid > 0) {
8437                     // ensure the tid belongs to the process
8438                     if (!isThreadInProcess(pid, tid)) {
8439                         throw new IllegalArgumentException(
8440                             "Render thread does not belong to process");
8441                     }
8442                     proc.renderThreadTid = tid;
8443                     if (DEBUG_OOM_ADJ) {
8444                         Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
8445                     }
8446                     // promote to FIFO now
8447                     if (proc.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) {
8448                         if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
8449                         if (mUseFifoUiScheduling) {
8450                             setThreadScheduler(proc.renderThreadTid,
8451                                 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
8452                         } else {
8453                             setThreadPriority(proc.renderThreadTid, TOP_APP_PRIORITY_BOOST);
8454                         }
8455                     }
8456                 } else {
8457                     if (DEBUG_OOM_ADJ) {
8458                         Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " +
8459                                "PID: " + pid + ", TID: " + tid + " FIFO: " +
8460                                mUseFifoUiScheduling);
8461                     }
8462                 }
8463             }
8464         }
8465     }
8466 
8467     /**
8468      * We only use RenderThread in system_server to store task snapshots to the disk, which should
8469      * happen in the background. Thus, demote render thread from system_server to a lower priority.
8470      *
8471      * @param tid the tid of the RenderThread
8472      */
demoteSystemServerRenderThread(int tid)8473     private void demoteSystemServerRenderThread(int tid) {
8474         setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
8475     }
8476 
8477     @Override
isVrModePackageEnabled(ComponentName packageName)8478     public boolean isVrModePackageEnabled(ComponentName packageName) {
8479         mActivityTaskManager.enforceSystemHasVrFeature();
8480 
8481         final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
8482 
8483         return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
8484                 VrManagerInternal.NO_ERROR;
8485     }
8486 
isTopActivityImmersive()8487     public boolean isTopActivityImmersive() {
8488         return mActivityTaskManager.isTopActivityImmersive();
8489     }
8490 
8491     @Override
isTopOfTask(IBinder token)8492     public boolean isTopOfTask(IBinder token) {
8493         return mActivityTaskManager.isTopOfTask(token);
8494     }
8495 
8496     @Override
setHasTopUi(boolean hasTopUi)8497     public void setHasTopUi(boolean hasTopUi) throws RemoteException {
8498         if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
8499             String msg = "Permission Denial: setHasTopUi() from pid="
8500                     + Binder.getCallingPid()
8501                     + ", uid=" + Binder.getCallingUid()
8502                     + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
8503             Slog.w(TAG, msg);
8504             throw new SecurityException(msg);
8505         }
8506         final int pid = Binder.getCallingPid();
8507         final long origId = Binder.clearCallingIdentity();
8508         try {
8509             synchronized (this) {
8510                 boolean changed = false;
8511                 ProcessRecord pr;
8512                 synchronized (mPidsSelfLocked) {
8513                     pr = mPidsSelfLocked.get(pid);
8514                     if (pr == null) {
8515                         Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
8516                         return;
8517                     }
8518                     if (pr.hasTopUi() != hasTopUi) {
8519                         if (DEBUG_OOM_ADJ) {
8520                             Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
8521                         }
8522                         pr.setHasTopUi(hasTopUi);
8523                         changed = true;
8524                     }
8525                 }
8526                 if (changed) {
8527                     updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
8528                 }
8529             }
8530         } finally {
8531             Binder.restoreCallingIdentity(origId);
8532         }
8533     }
8534 
enterSafeMode()8535     public final void enterSafeMode() {
8536         synchronized(this) {
8537             // It only makes sense to do this before the system is ready
8538             // and started launching other packages.
8539             if (!mSystemReady) {
8540                 try {
8541                     AppGlobals.getPackageManager().enterSafeMode();
8542                 } catch (RemoteException e) {
8543                 }
8544             }
8545 
8546             mSafeMode = true;
8547         }
8548     }
8549 
showSafeModeOverlay()8550     public final void showSafeModeOverlay() {
8551         View v = LayoutInflater.from(mContext).inflate(
8552                 com.android.internal.R.layout.safe_mode, null);
8553         WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
8554         lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
8555         lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
8556         lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
8557         lp.gravity = Gravity.BOTTOM | Gravity.START;
8558         lp.format = v.getBackground().getOpacity();
8559         lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
8560                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
8561         lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
8562         ((WindowManager)mContext.getSystemService(
8563                 Context.WINDOW_SERVICE)).addView(v, lp);
8564     }
8565 
8566     @Override
noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8567     public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid,
8568             String sourcePkg, String tag) {
8569         if (workSource != null && workSource.isEmpty()) {
8570             workSource = null;
8571         }
8572 
8573         if (sourceUid <= 0 && workSource == null) {
8574             // Try and derive a UID to attribute things to based on the caller.
8575             if (sender != null) {
8576                 if (!(sender instanceof PendingIntentRecord)) {
8577                     return;
8578                 }
8579 
8580                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8581                 final int callerUid = Binder.getCallingUid();
8582                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8583             } else {
8584                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8585                 // haven't been able to derive a UID to attribute things to.
8586                 return;
8587             }
8588         }
8589 
8590         int standbyBucket = 0;
8591 
8592         mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag);
8593         if (workSource != null) {
8594             String workSourcePackage = workSource.getName(0);
8595             int workSourceUid = workSource.getAttributionUid();
8596             if (workSourcePackage == null) {
8597                 workSourcePackage = sourcePkg;
8598                 workSourceUid = sourceUid;
8599             }
8600 
8601             if (mUsageStatsService != null) {
8602                 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage,
8603                         UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime());
8604             }
8605 
8606             StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, sourcePkg,
8607                     standbyBucket);
8608             if (DEBUG_POWER) {
8609                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8610                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8611                         + standbyBucket + " wsName=" + workSourcePackage + ")]");
8612             }
8613         } else {
8614             if (mUsageStatsService != null) {
8615                 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg,
8616                         UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime());
8617             }
8618             StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, null, tag,
8619                     sourcePkg, standbyBucket);
8620             if (DEBUG_POWER) {
8621                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8622                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8623                         + standbyBucket + "]");
8624             }
8625         }
8626 
8627     }
8628 
8629     @Override
noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8630     public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid,
8631             String tag) {
8632         if (workSource != null && workSource.isEmpty()) {
8633             workSource = null;
8634         }
8635 
8636         if (sourceUid <= 0 && workSource == null) {
8637             // Try and derive a UID to attribute things to based on the caller.
8638             if (sender != null) {
8639                 if (!(sender instanceof PendingIntentRecord)) {
8640                     return;
8641                 }
8642 
8643                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8644                 final int callerUid = Binder.getCallingUid();
8645                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8646             } else {
8647                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8648                 // haven't been able to derive a UID to attribute things to.
8649                 return;
8650             }
8651         }
8652 
8653         if (DEBUG_POWER) {
8654             Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource +
8655                     ", tag=" + tag + "]");
8656         }
8657 
8658         mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid);
8659     }
8660 
8661     @Override
noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8662     public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid,
8663             String tag) {
8664         if (workSource != null && workSource.isEmpty()) {
8665             workSource = null;
8666         }
8667 
8668         if (sourceUid <= 0 && workSource == null) {
8669             // Try and derive a UID to attribute things to based on the caller.
8670             if (sender != null) {
8671                 if (!(sender instanceof PendingIntentRecord)) {
8672                     return;
8673                 }
8674 
8675                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8676                 final int callerUid = Binder.getCallingUid();
8677                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8678             } else {
8679                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8680                 // haven't been able to derive a UID to attribute things to.
8681                 return;
8682             }
8683         }
8684 
8685         if (DEBUG_POWER) {
8686             Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource +
8687                     ", tag=" + tag + "]");
8688         }
8689 
8690         mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid);
8691     }
8692 
killPids(int[] pids, String pReason, boolean secure)8693     public boolean killPids(int[] pids, String pReason, boolean secure) {
8694         if (Binder.getCallingUid() != SYSTEM_UID) {
8695             throw new SecurityException("killPids only available to the system");
8696         }
8697         String reason = (pReason == null) ? "Unknown" : pReason;
8698         // XXX Note: don't acquire main activity lock here, because the window
8699         // manager calls in with its locks held.
8700 
8701         boolean killed = false;
8702         synchronized (mPidsSelfLocked) {
8703             int worstType = 0;
8704             for (int i=0; i<pids.length; i++) {
8705                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8706                 if (proc != null) {
8707                     int type = proc.setAdj;
8708                     if (type > worstType) {
8709                         worstType = type;
8710                     }
8711                 }
8712             }
8713 
8714             // If the worst oom_adj is somewhere in the cached proc LRU range,
8715             // then constrain it so we will kill all cached procs.
8716             if (worstType < ProcessList.CACHED_APP_MAX_ADJ
8717                     && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
8718                 worstType = ProcessList.CACHED_APP_MIN_ADJ;
8719             }
8720 
8721             // If this is not a secure call, don't let it kill processes that
8722             // are important.
8723             if (!secure && worstType < ProcessList.SERVICE_ADJ) {
8724                 worstType = ProcessList.SERVICE_ADJ;
8725             }
8726 
8727             Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
8728             for (int i=0; i<pids.length; i++) {
8729                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8730                 if (proc == null) {
8731                     continue;
8732                 }
8733                 int adj = proc.setAdj;
8734                 if (adj >= worstType && !proc.killedByAm) {
8735                     proc.kill(reason, true);
8736                     killed = true;
8737                 }
8738             }
8739         }
8740         return killed;
8741     }
8742 
8743     @Override
killUid(int appId, int userId, String reason)8744     public void killUid(int appId, int userId, String reason) {
8745         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
8746         synchronized (this) {
8747             final long identity = Binder.clearCallingIdentity();
8748             try {
8749                 mProcessList.killPackageProcessesLocked(null /* packageName */, appId, userId,
8750                         ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
8751                         true /* callerWillRestart */, true /* doit */, true /* evenPersistent */,
8752                         false /* setRemoved */, reason != null ? reason : "kill uid");
8753             } finally {
8754                 Binder.restoreCallingIdentity(identity);
8755             }
8756         }
8757     }
8758 
8759     @Override
killProcessesBelowForeground(String reason)8760     public boolean killProcessesBelowForeground(String reason) {
8761         if (Binder.getCallingUid() != SYSTEM_UID) {
8762             throw new SecurityException("killProcessesBelowForeground() only available to system");
8763         }
8764 
8765         return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
8766     }
8767 
killProcessesBelowAdj(int belowAdj, String reason)8768     private boolean killProcessesBelowAdj(int belowAdj, String reason) {
8769         if (Binder.getCallingUid() != SYSTEM_UID) {
8770             throw new SecurityException("killProcessesBelowAdj() only available to system");
8771         }
8772 
8773         boolean killed = false;
8774         synchronized (mPidsSelfLocked) {
8775             final int size = mPidsSelfLocked.size();
8776             for (int i = 0; i < size; i++) {
8777                 final int pid = mPidsSelfLocked.keyAt(i);
8778                 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8779                 if (proc == null) continue;
8780 
8781                 final int adj = proc.setAdj;
8782                 if (adj > belowAdj && !proc.killedByAm) {
8783                     proc.kill(reason, true);
8784                     killed = true;
8785                 }
8786             }
8787         }
8788         return killed;
8789     }
8790 
8791     @Override
hang(final IBinder who, boolean allowRestart)8792     public void hang(final IBinder who, boolean allowRestart) {
8793         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8794                 != PackageManager.PERMISSION_GRANTED) {
8795             throw new SecurityException("Requires permission "
8796                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8797         }
8798 
8799         final IBinder.DeathRecipient death = new DeathRecipient() {
8800             @Override
8801             public void binderDied() {
8802                 synchronized (this) {
8803                     notifyAll();
8804                 }
8805             }
8806         };
8807 
8808         try {
8809             who.linkToDeath(death, 0);
8810         } catch (RemoteException e) {
8811             Slog.w(TAG, "hang: given caller IBinder is already dead.");
8812             return;
8813         }
8814 
8815         synchronized (this) {
8816             Watchdog.getInstance().setAllowRestart(allowRestart);
8817             Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
8818             synchronized (death) {
8819                 while (who.isBinderAlive()) {
8820                     try {
8821                         death.wait();
8822                     } catch (InterruptedException e) {
8823                     }
8824                 }
8825             }
8826             Watchdog.getInstance().setAllowRestart(true);
8827         }
8828     }
8829 
8830     @Override
restart()8831     public void restart() {
8832         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8833                 != PackageManager.PERMISSION_GRANTED) {
8834             throw new SecurityException("Requires permission "
8835                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8836         }
8837 
8838         Log.i(TAG, "Sending shutdown broadcast...");
8839 
8840         BroadcastReceiver br = new BroadcastReceiver() {
8841             @Override public void onReceive(Context context, Intent intent) {
8842                 // Now the broadcast is done, finish up the low-level shutdown.
8843                 Log.i(TAG, "Shutting down activity manager...");
8844                 shutdown(10000);
8845                 Log.i(TAG, "Shutdown complete, restarting!");
8846                 killProcess(myPid());
8847                 System.exit(10);
8848             }
8849         };
8850 
8851         // First send the high-level shut down broadcast.
8852         Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
8853         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8854         intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
8855         /* For now we are not doing a clean shutdown, because things seem to get unhappy.
8856         mContext.sendOrderedBroadcastAsUser(intent,
8857                 UserHandle.ALL, null, br, mHandler, 0, null, null);
8858         */
8859         br.onReceive(mContext, intent);
8860     }
8861 
getLowRamTimeSinceIdle(long now)8862     private long getLowRamTimeSinceIdle(long now) {
8863         return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0);
8864     }
8865 
8866     @Override
performIdleMaintenance()8867     public void performIdleMaintenance() {
8868         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8869                 != PackageManager.PERMISSION_GRANTED) {
8870             throw new SecurityException("Requires permission "
8871                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8872         }
8873 
8874         synchronized (this) {
8875             final long now = SystemClock.uptimeMillis();
8876             final long timeSinceLastIdle = now - mLastIdleTime;
8877 
8878             // Compact all non-zygote processes to freshen up the page cache.
8879             mOomAdjuster.mAppCompact.compactAllSystem();
8880 
8881             final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
8882             mLastIdleTime = now;
8883             mLowRamTimeSinceLastIdle = 0;
8884             if (mLowRamStartTime != 0) {
8885                 mLowRamStartTime = now;
8886             }
8887 
8888             StringBuilder sb = new StringBuilder(128);
8889             sb.append("Idle maintenance over ");
8890             TimeUtils.formatDuration(timeSinceLastIdle, sb);
8891             sb.append(" low RAM for ");
8892             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
8893             Slog.i(TAG, sb.toString());
8894 
8895             // If at least 1/3 of our time since the last idle period has been spent
8896             // with RAM low, then we want to kill processes.
8897             boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
8898             // If the processes' memory has increased by more than 1% of the total memory,
8899             // or 10 MB, whichever is greater, then the processes' are eligible to be killed.
8900             final long totalMemoryInKb = getTotalMemory() / 1000;
8901             final long memoryGrowthThreshold =
8902                     Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
8903 
8904             for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) {
8905                 ProcessRecord proc = mProcessList.mLruProcesses.get(i);
8906                 if (proc.notCachedSinceIdle) {
8907                     if (proc.setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
8908                             && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
8909                         if (doKilling && proc.initialIdlePss != 0
8910                                 && proc.lastPss > ((proc.initialIdlePss * 3) / 2)
8911                                 && proc.lastPss > (proc.initialIdlePss + memoryGrowthThreshold)) {
8912                             sb = new StringBuilder(128);
8913                             sb.append("Kill");
8914                             sb.append(proc.processName);
8915                             sb.append(" in idle maint: pss=");
8916                             sb.append(proc.lastPss);
8917                             sb.append(", swapPss=");
8918                             sb.append(proc.lastSwapPss);
8919                             sb.append(", initialPss=");
8920                             sb.append(proc.initialIdlePss);
8921                             sb.append(", period=");
8922                             TimeUtils.formatDuration(timeSinceLastIdle, sb);
8923                             sb.append(", lowRamPeriod=");
8924                             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
8925                             Slog.wtfQuiet(TAG, sb.toString());
8926                             proc.kill("idle maint (pss " + proc.lastPss
8927                                     + " from " + proc.initialIdlePss + ")", true);
8928                         }
8929                     }
8930                 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME
8931                         && proc.setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
8932                     proc.notCachedSinceIdle = true;
8933                     proc.initialIdlePss = 0;
8934                     proc.nextPssTime = ProcessList.computeNextPssTime(proc.setProcState, null,
8935                             mTestPssMode, mAtmInternal.isSleeping(), now);
8936                 }
8937             }
8938         }
8939     }
8940 
8941     @Override
sendIdleJobTrigger()8942     public void sendIdleJobTrigger() {
8943         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8944                 != PackageManager.PERMISSION_GRANTED) {
8945             throw new SecurityException("Requires permission "
8946                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8947         }
8948 
8949         final long ident = Binder.clearCallingIdentity();
8950         try {
8951             Intent intent = new Intent(ACTION_TRIGGER_IDLE)
8952                     .setPackage("android")
8953                     .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8954             broadcastIntent(null, intent, null, null, 0, null, null, null,
8955                     OP_NONE, null, false, false, UserHandle.USER_ALL);
8956         } finally {
8957             Binder.restoreCallingIdentity(ident);
8958         }
8959     }
8960 
retrieveSettings()8961     private void retrieveSettings() {
8962         final ContentResolver resolver = mContext.getContentResolver();
8963         mActivityTaskManager.retrieveSettings(resolver);
8964 
8965         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
8966         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
8967         final boolean alwaysFinishActivities =
8968                 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
8969         final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver,
8970                 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS);
8971         mHiddenApiBlacklist.registerObserver();
8972 
8973         final long pssDeferralMs = DeviceConfig.getLong(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
8974                 ACTIVITY_START_PSS_DEFER_CONFIG, 0L);
8975         DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
8976                 ActivityThread.currentApplication().getMainExecutor(),
8977                 mPssDelayConfigListener);
8978 
8979         synchronized (this) {
8980             mDebugApp = mOrigDebugApp = debugApp;
8981             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
8982             mAlwaysFinishActivities = alwaysFinishActivities;
8983             // Load resources only after the current configuration has been set.
8984             final Resources res = mContext.getResources();
8985             mAppErrors.loadAppsNotReportingCrashesFromConfigLocked(res.getString(
8986                     com.android.internal.R.string.config_appsNotReportingCrashes));
8987             mUserController.mUserSwitchUiEnabled = !res.getBoolean(
8988                     com.android.internal.R.bool.config_customUserSwitchUi);
8989             mUserController.mMaxRunningUsers = res.getInteger(
8990                     com.android.internal.R.integer.config_multiuserMaxRunningUsers);
8991             mUserController.mDelayUserDataLocking = res.getBoolean(
8992                     com.android.internal.R.bool.config_multiuserDelayUserDataLocking);
8993 
8994             mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs;
8995             mPssDeferralTime = pssDeferralMs;
8996         }
8997     }
8998 
systemReady(final Runnable goingCallback, TimingsTraceLog traceLog)8999     public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
9000         traceLog.traceBegin("PhaseActivityManagerReady");
9001         synchronized(this) {
9002             if (mSystemReady) {
9003                 // If we're done calling all the receivers, run the next "boot phase" passed in
9004                 // by the SystemServer
9005                 if (goingCallback != null) {
9006                     goingCallback.run();
9007                 }
9008                 return;
9009             }
9010 
9011             mLocalDeviceIdleController
9012                     = LocalServices.getService(DeviceIdleController.LocalService.class);
9013             mActivityTaskManager.onSystemReady();
9014             // Make sure we have the current profile info, since it is needed for security checks.
9015             mUserController.onSystemReady();
9016             mAppOpsService.systemReady();
9017             mSystemReady = true;
9018         }
9019 
9020         try {
9021             sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
9022                     ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
9023                     .getSerial();
9024         } catch (RemoteException e) {}
9025 
9026         ArrayList<ProcessRecord> procsToKill = null;
9027         synchronized(mPidsSelfLocked) {
9028             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
9029                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
9030                 if (!isAllowedWhileBooting(proc.info)){
9031                     if (procsToKill == null) {
9032                         procsToKill = new ArrayList<ProcessRecord>();
9033                     }
9034                     procsToKill.add(proc);
9035                 }
9036             }
9037         }
9038 
9039         synchronized(this) {
9040             if (procsToKill != null) {
9041                 for (int i=procsToKill.size()-1; i>=0; i--) {
9042                     ProcessRecord proc = procsToKill.get(i);
9043                     Slog.i(TAG, "Removing system update proc: " + proc);
9044                     mProcessList.removeProcessLocked(proc, true, false, "system update done");
9045                 }
9046             }
9047 
9048             // Now that we have cleaned up any update processes, we
9049             // are ready to start launching real processes and know that
9050             // we won't trample on them any more.
9051             mProcessesReady = true;
9052         }
9053 
9054         Slog.i(TAG, "System now ready");
9055         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());
9056 
9057         mAtmInternal.updateTopComponentForFactoryTest();
9058         mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
9059 
9060         watchDeviceProvisioning(mContext);
9061 
9062         retrieveSettings();
9063         mUgmInternal.onSystemReady();
9064 
9065         final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
9066         if (pmi != null) {
9067             pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
9068                     state -> updateForceBackgroundCheck(state.batterySaverEnabled));
9069             updateForceBackgroundCheck(
9070                     pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
9071         } else {
9072             Slog.wtf(TAG, "PowerManagerInternal not found.");
9073         }
9074 
9075         if (goingCallback != null) goingCallback.run();
9076         // Check the current user here as a user can be started inside goingCallback.run() from
9077         // other system services.
9078         final int currentUserId = mUserController.getCurrentUserId();
9079         Slog.i(TAG, "Current user:" + currentUserId);
9080         if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
9081             // User other than system user has started. Make sure that system user is already
9082             // started before switching user.
9083             throw new RuntimeException("System user not started while current user is:"
9084                     + currentUserId);
9085         }
9086         traceLog.traceBegin("ActivityManagerStartApps");
9087         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
9088                 Integer.toString(currentUserId), currentUserId);
9089         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
9090                 Integer.toString(currentUserId), currentUserId);
9091 
9092         // On Automotive, at this point the system user has already been started and unlocked,
9093         // and some of the tasks we do here have already been done. So skip those in that case.
9094         // TODO(b/132262830): this workdound shouldn't be necessary once we move the
9095         // headless-user start logic to UserManager-land
9096         final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
9097 
9098         if (bootingSystemUser) {
9099             mSystemServiceManager.startUser(currentUserId);
9100         }
9101 
9102         synchronized (this) {
9103             // Only start up encryption-aware persistent apps; once user is
9104             // unlocked we'll come back around and start unaware apps
9105             startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
9106 
9107             // Start up initial activity.
9108             mBooting = true;
9109             // Enable home activity for system user, so that the system can always boot. We don't
9110             // do this when the system user is not setup since the setup wizard should be the one
9111             // to handle home activity in this case.
9112             if (UserManager.isSplitSystemUser() &&
9113                     Settings.Secure.getInt(mContext.getContentResolver(),
9114                          Settings.Secure.USER_SETUP_COMPLETE, 0) != 0
9115                     || SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
9116                 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
9117                 try {
9118                     AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
9119                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
9120                             UserHandle.USER_SYSTEM);
9121                 } catch (RemoteException e) {
9122                     throw e.rethrowAsRuntimeException();
9123                 }
9124             }
9125 
9126             if (bootingSystemUser) {
9127                 mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
9128             }
9129 
9130             mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
9131 
9132             if (bootingSystemUser) {
9133                 final int callingUid = Binder.getCallingUid();
9134                 final int callingPid = Binder.getCallingPid();
9135                 long ident = Binder.clearCallingIdentity();
9136                 try {
9137                     Intent intent = new Intent(Intent.ACTION_USER_STARTED);
9138                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
9139                             | Intent.FLAG_RECEIVER_FOREGROUND);
9140                     intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9141                     broadcastIntentLocked(null, null, intent,
9142                             null, null, 0, null, null, null, OP_NONE,
9143                             null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9144                             currentUserId);
9145                     intent = new Intent(Intent.ACTION_USER_STARTING);
9146                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
9147                     intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9148                     broadcastIntentLocked(null, null, intent,
9149                             null, new IIntentReceiver.Stub() {
9150                                 @Override
9151                                 public void performReceive(Intent intent, int resultCode, String data,
9152                                         Bundle extras, boolean ordered, boolean sticky, int sendingUser)
9153                                         throws RemoteException {
9154                                 }
9155                             }, 0, null, null,
9156                             new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
9157                             null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9158                             UserHandle.USER_ALL);
9159                 } catch (Throwable t) {
9160                     Slog.wtf(TAG, "Failed sending first user broadcasts", t);
9161                 } finally {
9162                     Binder.restoreCallingIdentity(ident);
9163                 }
9164             } else {
9165                 Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
9166                         + currentUserId);
9167             }
9168             mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
9169             if (bootingSystemUser) {
9170                 mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
9171             }
9172 
9173             BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
9174                     BINDER_PROXY_LOW_WATERMARK);
9175             BinderInternal.nSetBinderProxyCountEnabled(true);
9176             BinderInternal.setBinderProxyCountCallback(
9177                     new BinderInternal.BinderProxyLimitListener() {
9178                         @Override
9179                         public void onLimitReached(int uid) {
9180                             Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
9181                                     + Process.myUid());
9182                             BinderProxy.dumpProxyDebugInfo();
9183                             if (uid == Process.SYSTEM_UID) {
9184                                 Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
9185                             } else {
9186                                 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
9187                                         "Too many Binders sent to SYSTEM");
9188                             }
9189                         }
9190                     }, mHandler);
9191 
9192             traceLog.traceEnd(); // ActivityManagerStartApps
9193             traceLog.traceEnd(); // PhaseActivityManagerReady
9194         }
9195     }
9196 
watchDeviceProvisioning(Context context)9197     private void watchDeviceProvisioning(Context context) {
9198         // setting system property based on whether device is provisioned
9199 
9200         if (isDeviceProvisioned(context)) {
9201             SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
9202         } else {
9203             // watch for device provisioning change
9204             context.getContentResolver().registerContentObserver(
9205                     Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false,
9206                     new ContentObserver(new Handler(Looper.getMainLooper())) {
9207                         @Override
9208                         public void onChange(boolean selfChange) {
9209                             if (isDeviceProvisioned(context)) {
9210                                 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
9211                                 context.getContentResolver().unregisterContentObserver(this);
9212                             }
9213                         }
9214                     });
9215         }
9216     }
9217 
isDeviceProvisioned(Context context)9218     private boolean isDeviceProvisioned(Context context) {
9219         return Settings.Global.getInt(context.getContentResolver(),
9220                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
9221     }
9222 
startBroadcastObservers()9223     private void startBroadcastObservers() {
9224         for (BroadcastQueue queue : mBroadcastQueues) {
9225             queue.start(mContext.getContentResolver());
9226         }
9227     }
9228 
updateForceBackgroundCheck(boolean enabled)9229     private void updateForceBackgroundCheck(boolean enabled) {
9230         synchronized (this) {
9231             if (mForceBackgroundCheck != enabled) {
9232                 mForceBackgroundCheck = enabled;
9233 
9234                 if (DEBUG_BACKGROUND_CHECK) {
9235                     Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled"));
9236                 }
9237 
9238                 if (mForceBackgroundCheck) {
9239                     // Stop background services for idle UIDs.
9240                     mProcessList.doStopUidForIdleUidsLocked();
9241                 }
9242             }
9243         }
9244     }
9245 
killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog)9246     void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
9247         synchronized (this) {
9248             mAppErrors.killAppAtUserRequestLocked(app, fromDialog);
9249         }
9250     }
9251 
skipCurrentReceiverLocked(ProcessRecord app)9252     void skipCurrentReceiverLocked(ProcessRecord app) {
9253         for (BroadcastQueue queue : mBroadcastQueues) {
9254             queue.skipCurrentReceiverLocked(app);
9255         }
9256     }
9257 
9258     /**
9259      * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
9260      * The application process will exit immediately after this call returns.
9261      * @param app object of the crashing app, null for the system server
9262      * @param crashInfo describing the exception
9263      */
handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)9264     public void handleApplicationCrash(IBinder app,
9265             ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
9266         ProcessRecord r = findAppProcess(app, "Crash");
9267         final String processName = app == null ? "system_server"
9268                 : (r == null ? "unknown" : r.processName);
9269 
9270         handleApplicationCrashInner("crash", r, processName, crashInfo);
9271     }
9272 
9273     /* Native crash reporting uses this inner version because it needs to be somewhat
9274      * decoupled from the AM-managed cleanup lifecycle
9275      */
handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)9276     void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
9277             ApplicationErrorReport.CrashInfo crashInfo) {
9278         EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
9279                 UserHandle.getUserId(Binder.getCallingUid()), processName,
9280                 r == null ? -1 : r.info.flags,
9281                 crashInfo.exceptionClassName,
9282                 crashInfo.exceptionMessage,
9283                 crashInfo.throwFileName,
9284                 crashInfo.throwLineNumber);
9285 
9286         StatsLog.write(StatsLog.APP_CRASH_OCCURRED,
9287                 Binder.getCallingUid(),
9288                 eventType,
9289                 processName,
9290                 Binder.getCallingPid(),
9291                 (r != null && r.info != null) ? r.info.packageName : "",
9292                 (r != null && r.info != null) ? (r.info.isInstantApp()
9293                         ? StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE
9294                         : StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE)
9295                         : StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE,
9296                 r != null ? (r.isInterestingToUserLocked()
9297                         ? StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND
9298                         : StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND)
9299                         : StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN,
9300                 processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER
9301                         : (r != null) ? r.getProcessClassEnum()
9302                                       : ServerProtoEnums.ERROR_SOURCE_UNKNOWN
9303         );
9304 
9305         final int relaunchReason = r == null ? RELAUNCH_REASON_NONE
9306                         : r.getWindowProcessController().computeRelaunchReason();
9307         final String relaunchReasonString = relaunchReasonToString(relaunchReason);
9308         if (crashInfo.crashTag == null) {
9309             crashInfo.crashTag = relaunchReasonString;
9310         } else {
9311             crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString;
9312         }
9313 
9314         addErrorToDropBox(
9315                 eventType, r, processName, null, null, null, null, null, null, crashInfo);
9316 
9317         mAppErrors.crashApplication(r, crashInfo);
9318     }
9319 
handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9320     public void handleApplicationStrictModeViolation(
9321             IBinder app,
9322             int penaltyMask,
9323             StrictMode.ViolationInfo info) {
9324         // We're okay if the ProcessRecord is missing; it probably means that
9325         // we're reporting a violation from the system process itself.
9326         final ProcessRecord r = findAppProcess(app, "StrictMode");
9327 
9328         if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) {
9329             Integer stackFingerprint = info.hashCode();
9330             boolean logIt = true;
9331             synchronized (mAlreadyLoggedViolatedStacks) {
9332                 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
9333                     logIt = false;
9334                     // TODO: sub-sample into EventLog for these, with
9335                     // the info.durationMillis?  Then we'd get
9336                     // the relative pain numbers, without logging all
9337                     // the stack traces repeatedly.  We'd want to do
9338                     // likewise in the client code, which also does
9339                     // dup suppression, before the Binder call.
9340                 } else {
9341                     if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
9342                         mAlreadyLoggedViolatedStacks.clear();
9343                     }
9344                     mAlreadyLoggedViolatedStacks.add(stackFingerprint);
9345                 }
9346             }
9347             if (logIt) {
9348                 logStrictModeViolationToDropBox(r, info);
9349             }
9350         }
9351 
9352         if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) {
9353             AppErrorResult result = new AppErrorResult();
9354             synchronized (this) {
9355                 final long origId = Binder.clearCallingIdentity();
9356 
9357                 Message msg = Message.obtain();
9358                 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG;
9359                 HashMap<String, Object> data = new HashMap<String, Object>();
9360                 data.put("result", result);
9361                 data.put("app", r);
9362                 data.put("info", info);
9363                 msg.obj = data;
9364                 mUiHandler.sendMessage(msg);
9365 
9366                 Binder.restoreCallingIdentity(origId);
9367             }
9368             int res = result.get();
9369             Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
9370         }
9371     }
9372 
9373     // Depending on the policy in effect, there could be a bunch of
9374     // these in quick succession so we try to batch these together to
9375     // minimize disk writes, number of dropbox entries, and maximize
9376     // compression, by having more fewer, larger records.
logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9377     private void logStrictModeViolationToDropBox(
9378             ProcessRecord process,
9379             StrictMode.ViolationInfo info) {
9380         if (info == null) {
9381             return;
9382         }
9383         final boolean isSystemApp = process == null ||
9384                 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
9385                                        ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
9386         final String processName = process == null ? "unknown" : process.processName;
9387         final DropBoxManager dbox = (DropBoxManager)
9388                 mContext.getSystemService(Context.DROPBOX_SERVICE);
9389 
9390         // Exit early if the dropbox isn't configured to accept this report type.
9391         final String dropboxTag = processClass(process) + "_strictmode";
9392         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9393 
9394         final StringBuilder sb = new StringBuilder(1024);
9395         synchronized (sb) {
9396             appendDropBoxProcessHeaders(process, processName, sb);
9397             sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9398             sb.append("System-App: ").append(isSystemApp).append("\n");
9399             sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
9400             if (info.violationNumThisLoop != 0) {
9401                 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
9402             }
9403             if (info.numAnimationsRunning != 0) {
9404                 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
9405             }
9406             if (info.broadcastIntentAction != null) {
9407                 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
9408             }
9409             if (info.durationMillis != -1) {
9410                 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
9411             }
9412             if (info.numInstances != -1) {
9413                 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
9414             }
9415             if (info.tags != null) {
9416                 for (String tag : info.tags) {
9417                     sb.append("Span-Tag: ").append(tag).append("\n");
9418                 }
9419             }
9420             sb.append("\n");
9421             sb.append(info.getStackTrace());
9422             sb.append("\n");
9423             if (info.getViolationDetails() != null) {
9424                 sb.append(info.getViolationDetails());
9425                 sb.append("\n");
9426             }
9427         }
9428 
9429         final String res = sb.toString();
9430         IoThread.getHandler().post(() -> {
9431             dbox.addText(dropboxTag, res);
9432         });
9433     }
9434 
9435     /**
9436      * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
9437      * @param app object of the crashing app, null for the system server
9438      * @param tag reported by the caller
9439      * @param system whether this wtf is coming from the system
9440      * @param crashInfo describing the context of the error
9441      * @return true if the process should exit immediately (WTF is fatal)
9442      */
handleApplicationWtf(final IBinder app, final String tag, boolean system, final ApplicationErrorReport.ParcelableCrashInfo crashInfo)9443     public boolean handleApplicationWtf(final IBinder app, final String tag, boolean system,
9444             final ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
9445         final int callingUid = Binder.getCallingUid();
9446         final int callingPid = Binder.getCallingPid();
9447 
9448         if (system) {
9449             // If this is coming from the system, we could very well have low-level
9450             // system locks held, so we want to do this all asynchronously.  And we
9451             // never want this to become fatal, so there is that too.
9452             mHandler.post(new Runnable() {
9453                 @Override public void run() {
9454                     handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo);
9455                 }
9456             });
9457             return false;
9458         }
9459 
9460         final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag,
9461                 crashInfo);
9462 
9463         final boolean isFatal = Build.IS_ENG || Settings.Global
9464                 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0;
9465         final boolean isSystem = (r == null) || r.isPersistent();
9466 
9467         if (isFatal && !isSystem) {
9468             mAppErrors.crashApplication(r, crashInfo);
9469             return true;
9470         } else {
9471             return false;
9472         }
9473     }
9474 
handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, final ApplicationErrorReport.CrashInfo crashInfo)9475     ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag,
9476             final ApplicationErrorReport.CrashInfo crashInfo) {
9477         final ProcessRecord r = findAppProcess(app, "WTF");
9478         final String processName = app == null ? "system_server"
9479                 : (r == null ? "unknown" : r.processName);
9480 
9481         EventLog.writeEvent(EventLogTags.AM_WTF, UserHandle.getUserId(callingUid), callingPid,
9482                 processName, r == null ? -1 : r.info.flags, tag, crashInfo.exceptionMessage);
9483 
9484         StatsLog.write(StatsLog.WTF_OCCURRED, callingUid, tag, processName,
9485                 callingPid, (r != null) ? r.getProcessClassEnum() : 0);
9486 
9487         addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo);
9488 
9489         return r;
9490     }
9491 
9492     /**
9493      * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
9494      * @return the corresponding {@link ProcessRecord} object, or null if none could be found
9495      */
findAppProcess(IBinder app, String reason)9496     private ProcessRecord findAppProcess(IBinder app, String reason) {
9497         if (app == null) {
9498             return null;
9499         }
9500 
9501         synchronized (this) {
9502             return mProcessList.findAppProcessLocked(app, reason);
9503         }
9504     }
9505 
9506     /**
9507      * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
9508      * to append various headers to the dropbox log text.
9509      */
appendDropBoxProcessHeaders(ProcessRecord process, String processName, StringBuilder sb)9510     private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
9511             StringBuilder sb) {
9512         // Watchdog thread ends up invoking this function (with
9513         // a null ProcessRecord) to add the stack file to dropbox.
9514         // Do not acquire a lock on this (am) in such cases, as it
9515         // could cause a potential deadlock, if and when watchdog
9516         // is invoked due to unavailability of lock on am and it
9517         // would prevent watchdog from killing system_server.
9518         if (process == null) {
9519             sb.append("Process: ").append(processName).append("\n");
9520             return;
9521         }
9522         // Note: ProcessRecord 'process' is guarded by the service
9523         // instance.  (notably process.pkgList, which could otherwise change
9524         // concurrently during execution of this method)
9525         synchronized (this) {
9526             sb.append("Process: ").append(processName).append("\n");
9527             sb.append("PID: ").append(process.pid).append("\n");
9528             sb.append("UID: ").append(process.uid).append("\n");
9529             int flags = process.info.flags;
9530             IPackageManager pm = AppGlobals.getPackageManager();
9531             sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n");
9532             for (int ip=0; ip<process.pkgList.size(); ip++) {
9533                 String pkg = process.pkgList.keyAt(ip);
9534                 sb.append("Package: ").append(pkg);
9535                 try {
9536                     PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
9537                     if (pi != null) {
9538                         sb.append(" v").append(pi.getLongVersionCode());
9539                         if (pi.versionName != null) {
9540                             sb.append(" (").append(pi.versionName).append(")");
9541                         }
9542                     }
9543                 } catch (RemoteException e) {
9544                     Slog.e(TAG, "Error getting package info: " + pkg, e);
9545                 }
9546                 sb.append("\n");
9547             }
9548             if (process.info.isInstantApp()) {
9549                 sb.append("Instant-App: true\n");
9550             }
9551         }
9552     }
9553 
processClass(ProcessRecord process)9554     private static String processClass(ProcessRecord process) {
9555         if (process == null || process.pid == MY_PID) {
9556             return "system_server";
9557         } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9558             return "system_app";
9559         } else {
9560             return "data_app";
9561         }
9562     }
9563 
9564     private volatile long mWtfClusterStart;
9565     private volatile int mWtfClusterCount;
9566 
9567     /**
9568      * Write a description of an error (crash, WTF, ANR) to the drop box.
9569      * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
9570      * @param process which caused the error, null means the system server
9571      * @param activityShortComponentName which triggered the error, null if unknown
9572      * @param parentShortComponentName activity related to the error, null if unknown
9573      * @param parentProcess parent process
9574      * @param subject line related to the error, null if absent
9575      * @param report in long form describing the error, null if absent
9576      * @param dataFile text file to include in the report, null if none
9577      * @param crashInfo giving an application stack trace, null if absent
9578      */
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)9579     public void addErrorToDropBox(String eventType,
9580             ProcessRecord process, String processName, String activityShortComponentName,
9581             String parentShortComponentName, ProcessRecord parentProcess,
9582             String subject, final String report, final File dataFile,
9583             final ApplicationErrorReport.CrashInfo crashInfo) {
9584         // NOTE -- this must never acquire the ActivityManagerService lock,
9585         // otherwise the watchdog may be prevented from resetting the system.
9586 
9587         // Bail early if not published yet
9588         if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return;
9589         final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class);
9590 
9591         // Exit early if the dropbox isn't configured to accept this report type.
9592         final String dropboxTag = processClass(process) + "_" + eventType;
9593         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9594 
9595         // Rate-limit how often we're willing to do the heavy lifting below to
9596         // collect and record logs; currently 5 logs per 10 second period.
9597         final long now = SystemClock.elapsedRealtime();
9598         if (now - mWtfClusterStart > 10 * DateUtils.SECOND_IN_MILLIS) {
9599             mWtfClusterStart = now;
9600             mWtfClusterCount = 1;
9601         } else {
9602             if (mWtfClusterCount++ >= 5) return;
9603         }
9604 
9605         final StringBuilder sb = new StringBuilder(1024);
9606         appendDropBoxProcessHeaders(process, processName, sb);
9607         if (process != null) {
9608             sb.append("Foreground: ")
9609                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
9610                     .append("\n");
9611         }
9612         if (activityShortComponentName != null) {
9613             sb.append("Activity: ").append(activityShortComponentName).append("\n");
9614         }
9615         if (parentShortComponentName != null) {
9616             if (parentProcess != null && parentProcess.pid != process.pid) {
9617                 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n");
9618             }
9619             if (!parentShortComponentName.equals(activityShortComponentName)) {
9620                 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n");
9621             }
9622         }
9623         if (subject != null) {
9624             sb.append("Subject: ").append(subject).append("\n");
9625         }
9626         sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9627         if (Debug.isDebuggerConnected()) {
9628             sb.append("Debugger: Connected\n");
9629         }
9630         if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) {
9631             sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n");
9632         }
9633         sb.append("\n");
9634 
9635         // Do the rest in a worker thread to avoid blocking the caller on I/O
9636         // (After this point, we shouldn't access AMS internal data structures.)
9637         Thread worker = new Thread("Error dump: " + dropboxTag) {
9638             @Override
9639             public void run() {
9640                 if (report != null) {
9641                     sb.append(report);
9642                 }
9643 
9644                 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
9645                 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
9646                 int maxDataFileSize = DROPBOX_MAX_SIZE - sb.length()
9647                         - lines * RESERVED_BYTES_PER_LOGCAT_LINE;
9648 
9649                 if (dataFile != null && maxDataFileSize > 0) {
9650                     try {
9651                         sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize,
9652                                     "\n\n[[TRUNCATED]]"));
9653                     } catch (IOException e) {
9654                         Slog.e(TAG, "Error reading " + dataFile, e);
9655                     }
9656                 }
9657                 if (crashInfo != null && crashInfo.stackTrace != null) {
9658                     sb.append(crashInfo.stackTrace);
9659                 }
9660 
9661                 if (lines > 0) {
9662                     sb.append("\n");
9663 
9664                     // Merge several logcat streams, and take the last N lines
9665                     InputStreamReader input = null;
9666                     try {
9667                         java.lang.Process logcat = new ProcessBuilder(
9668                                 "/system/bin/timeout", "-k", "15s", "10s",
9669                                 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system",
9670                                 "-b", "main", "-b", "crash", "-t", String.valueOf(lines))
9671                                         .redirectErrorStream(true).start();
9672 
9673                         try { logcat.getOutputStream().close(); } catch (IOException e) {}
9674                         try { logcat.getErrorStream().close(); } catch (IOException e) {}
9675                         input = new InputStreamReader(logcat.getInputStream());
9676 
9677                         int num;
9678                         char[] buf = new char[8192];
9679                         while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
9680                     } catch (IOException e) {
9681                         Slog.e(TAG, "Error running logcat", e);
9682                     } finally {
9683                         if (input != null) try { input.close(); } catch (IOException e) {}
9684                     }
9685                 }
9686 
9687                 dbox.addText(dropboxTag, sb.toString());
9688             }
9689         };
9690 
9691         if (process == null) {
9692             // If process is null, we are being called from some internal code
9693             // and may be about to die -- run this synchronously.
9694             final int oldMask = StrictMode.allowThreadDiskWritesMask();
9695             try {
9696                 worker.run();
9697             } finally {
9698                 StrictMode.setThreadPolicyMask(oldMask);
9699             }
9700         } else {
9701             worker.start();
9702         }
9703     }
9704 
9705     @Override
getProcessesInErrorState()9706     public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
9707         enforceNotIsolatedCaller("getProcessesInErrorState");
9708         // assume our apps are happy - lazy create the list
9709         List<ActivityManager.ProcessErrorStateInfo> errList = null;
9710 
9711         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9712                 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
9713         int userId = UserHandle.getUserId(Binder.getCallingUid());
9714 
9715         synchronized (this) {
9716 
9717             // iterate across all processes
9718             for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) {
9719                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
9720                 if (!allUsers && app.userId != userId) {
9721                     continue;
9722                 }
9723                 final boolean crashing = app.isCrashing();
9724                 final boolean notResponding = app.isNotResponding();
9725                 if ((app.thread != null) && (crashing || notResponding)) {
9726                     // This one's in trouble, so we'll generate a report for it
9727                     // crashes are higher priority (in case there's a crash *and* an anr)
9728                     ActivityManager.ProcessErrorStateInfo report = null;
9729                     if (crashing) {
9730                         report = app.crashingReport;
9731                     } else if (notResponding) {
9732                         report = app.notRespondingReport;
9733                     }
9734 
9735                     if (report != null) {
9736                         if (errList == null) {
9737                             errList = new ArrayList<>(1);
9738                         }
9739                         errList.add(report);
9740                     } else {
9741                         Slog.w(TAG, "Missing app error report, app = " + app.processName +
9742                                 " crashing = " + crashing +
9743                                 " notResponding = " + notResponding);
9744                     }
9745                 }
9746             }
9747         }
9748 
9749         return errList;
9750     }
9751 
9752     @Override
getRunningAppProcesses()9753     public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
9754         enforceNotIsolatedCaller("getRunningAppProcesses");
9755 
9756         final int callingUid = Binder.getCallingUid();
9757         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9758 
9759         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9760                 callingUid) == PackageManager.PERMISSION_GRANTED;
9761         final int userId = UserHandle.getUserId(callingUid);
9762         final boolean allUids = mAtmInternal.isGetTasksAllowed(
9763                 "getRunningAppProcesses", Binder.getCallingPid(), callingUid);
9764 
9765         synchronized (this) {
9766             // Iterate across all processes
9767             return mProcessList.getRunningAppProcessesLocked(allUsers, userId, allUids,
9768                     callingUid, clientTargetSdk);
9769         }
9770     }
9771 
9772     @Override
getRunningExternalApplications()9773     public List<ApplicationInfo> getRunningExternalApplications() {
9774         enforceNotIsolatedCaller("getRunningExternalApplications");
9775         List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
9776         List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
9777         if (runningApps != null && runningApps.size() > 0) {
9778             Set<String> extList = new HashSet<String>();
9779             for (ActivityManager.RunningAppProcessInfo app : runningApps) {
9780                 if (app.pkgList != null) {
9781                     for (String pkg : app.pkgList) {
9782                         extList.add(pkg);
9783                     }
9784                 }
9785             }
9786             IPackageManager pm = AppGlobals.getPackageManager();
9787             for (String pkg : extList) {
9788                 try {
9789                     ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
9790                     if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
9791                         retList.add(info);
9792                     }
9793                 } catch (RemoteException e) {
9794                 }
9795             }
9796         }
9797         return retList;
9798     }
9799 
9800     @Override
getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)9801     public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) {
9802         if (outState == null) {
9803             throw new IllegalArgumentException("outState is null");
9804         }
9805         enforceNotIsolatedCaller("getMyMemoryState");
9806 
9807         final int callingUid = Binder.getCallingUid();
9808         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9809 
9810         synchronized (this) {
9811             ProcessRecord proc;
9812             synchronized (mPidsSelfLocked) {
9813                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9814             }
9815             if (proc != null) {
9816                 mProcessList.fillInProcMemInfoLocked(proc, outState, clientTargetSdk);
9817             }
9818         }
9819     }
9820 
9821     @Override
getMemoryTrimLevel()9822     public int getMemoryTrimLevel() {
9823         enforceNotIsolatedCaller("getMyMemoryState");
9824         synchronized (this) {
9825             return mLastMemoryLevel;
9826         }
9827     }
9828 
9829     @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)9830     public void onShellCommand(FileDescriptor in, FileDescriptor out,
9831             FileDescriptor err, String[] args, ShellCallback callback,
9832             ResultReceiver resultReceiver) {
9833         (new ActivityManagerShellCommand(this, false)).exec(
9834                 this, in, out, err, args, callback, resultReceiver);
9835     }
9836 
9837     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)9838     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9839         PriorityDump.dump(mPriorityDumper, fd, pw, args);
9840     }
9841 
dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId)9842     private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti,
9843             boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority,
9844             int dumpAppId) {
9845 
9846         ActiveServices.ServiceDumper sdumper;
9847 
9848         synchronized(this) {
9849             mConstants.dump(pw);
9850             mOomAdjuster.dumpAppCompactorSettings(pw);
9851             pw.println();
9852             if (dumpAll) {
9853                 pw.println("-------------------------------------------------------------------------------");
9854 
9855             }
9856             dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9857             pw.println();
9858             if (dumpAll) {
9859                 pw.println("-------------------------------------------------------------------------------");
9860 
9861             }
9862             mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage);
9863             pw.println();
9864             if (dumpAll) {
9865                 pw.println("-------------------------------------------------------------------------------");
9866             }
9867             dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9868             pw.println();
9869             if (dumpAll) {
9870                 pw.println("-------------------------------------------------------------------------------");
9871             }
9872             if (dumpAll || dumpPackage != null) {
9873                 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9874                 pw.println();
9875                 if (dumpAll) {
9876                     pw.println("-------------------------------------------------------------------------------");
9877                 }
9878             }
9879             dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9880             pw.println();
9881             if (dumpAll) {
9882                 pw.println("-------------------------------------------------------------------------------");
9883             }
9884             dumpPermissionsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9885             pw.println();
9886             sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9887             if (!dumpClient) {
9888                 if (dumpAll) {
9889                     pw.println("-------------------------------------------------------------------------------");
9890                 }
9891                 sdumper.dumpLocked();
9892             }
9893         }
9894         // We drop the lock here because we can't call dumpWithClient() with the lock held;
9895         // if the caller wants a consistent state for the !dumpClient case, it can call this
9896         // method with the lock held.
9897         if (dumpClient) {
9898             if (dumpAll) {
9899                 pw.println("-------------------------------------------------------------------------------");
9900             }
9901             sdumper.dumpWithClient();
9902         }
9903         if (dumpPackage == null) {
9904             // Intentionally dropping the lock for this, because dumpBinderProxies() will make many
9905             // outgoing binder calls to retrieve interface descriptors; while that is system code,
9906             // there is nothing preventing an app from overriding this implementation by talking to
9907             // the binder driver directly, and hang up system_server in the process. So, dump
9908             // without locks held, and even then only when there is an unreasonably large number of
9909             // proxies in the first place.
9910             pw.println();
9911             if (dumpAll) {
9912                 pw.println("-------------------------------------------------------------------------------");
9913             }
9914             dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */);
9915         }
9916         synchronized(this) {
9917             pw.println();
9918             if (dumpAll) {
9919                 pw.println("-------------------------------------------------------------------------------");
9920             }
9921             mAtmInternal.dump(
9922                     DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9923             pw.println();
9924             if (dumpAll) {
9925                 pw.println("-------------------------------------------------------------------------------");
9926             }
9927             mAtmInternal.dump(
9928                     DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9929             pw.println();
9930             if (dumpAll) {
9931                 pw.println("-------------------------------------------------------------------------------");
9932             }
9933             mAtmInternal.dump(
9934                     DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9935             pw.println();
9936             if (dumpAll) {
9937                 pw.println("-------------------------------------------------------------------------------");
9938             }
9939             mAtmInternal.dump(
9940                     DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9941             // Activities section is dumped as part of the Critical priority dump. Exclude the
9942             // section if priority is Normal.
9943             if (!dumpNormalPriority) {
9944                 pw.println();
9945                 if (dumpAll) {
9946                     pw.println("-------------------------------------------------------------------------------");
9947                 }
9948                 mAtmInternal.dump(
9949                         DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9950             }
9951             if (mAssociations.size() > 0) {
9952                 pw.println();
9953                 if (dumpAll) {
9954                     pw.println("-------------------------------------------------------------------------------");
9955                 }
9956                 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9957             }
9958             if (dumpPackage == null) {
9959                 pw.println();
9960                 if (dumpAll) {
9961                     pw.println("-------------------------------------------------------------------------------");
9962                 }
9963                 mOomAdjProfiler.dump(pw);
9964                 pw.println();
9965                 if (dumpAll) {
9966                     pw.println("-------------------------------------------------------------------------------");
9967                 }
9968                 dumpLmkLocked(pw);
9969             }
9970             pw.println();
9971             if (dumpAll) {
9972                 pw.println("-------------------------------------------------------------------------------");
9973             }
9974             dumpLruLocked(pw, dumpPackage);
9975             pw.println();
9976             if (dumpAll) {
9977                 pw.println("-------------------------------------------------------------------------------");
9978             }
9979             dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId);
9980         }
9981     }
9982 
9983     /**
9984      * Wrapper function to print out debug data filtered by specified arguments.
9985     */
doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)9986     private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
9987         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
9988 
9989         boolean dumpAll = false;
9990         boolean dumpClient = false;
9991         boolean dumpCheckin = false;
9992         boolean dumpCheckinFormat = false;
9993         boolean dumpNormalPriority = false;
9994         boolean dumpVisibleStacksOnly = false;
9995         boolean dumpFocusedStackOnly = false;
9996         String dumpPackage = null;
9997 
9998         int opti = 0;
9999         while (opti < args.length) {
10000             String opt = args[opti];
10001             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10002                 break;
10003             }
10004             opti++;
10005             if ("-a".equals(opt)) {
10006                 dumpAll = true;
10007             } else if ("-c".equals(opt)) {
10008                 dumpClient = true;
10009             } else if ("-v".equals(opt)) {
10010                 dumpVisibleStacksOnly = true;
10011             } else if ("-f".equals(opt)) {
10012                 dumpFocusedStackOnly = true;
10013             } else if ("-p".equals(opt)) {
10014                 if (opti < args.length) {
10015                     dumpPackage = args[opti];
10016                     opti++;
10017                 } else {
10018                     pw.println("Error: -p option requires package argument");
10019                     return;
10020                 }
10021                 dumpClient = true;
10022             } else if ("--checkin".equals(opt)) {
10023                 dumpCheckin = dumpCheckinFormat = true;
10024             } else if ("-C".equals(opt)) {
10025                 dumpCheckinFormat = true;
10026             } else if ("--normal-priority".equals(opt)) {
10027                 dumpNormalPriority = true;
10028             } else if ("-h".equals(opt)) {
10029                 ActivityManagerShellCommand.dumpHelp(pw, true);
10030                 return;
10031             } else {
10032                 pw.println("Unknown argument: " + opt + "; use -h for help");
10033             }
10034         }
10035 
10036         long origId = Binder.clearCallingIdentity();
10037 
10038         if (useProto) {
10039             final ProtoOutputStream proto = new ProtoOutputStream(fd);
10040             String cmd = opti < args.length ? args[opti] : "";
10041             opti++;
10042 
10043             if ("activities".equals(cmd) || "a".equals(cmd)) {
10044                 // output proto is ActivityManagerServiceDumpActivitiesProto
10045                 mAtmInternal.writeActivitiesToProto(proto);
10046             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10047                 // output proto is ActivityManagerServiceDumpBroadcastsProto
10048                 synchronized (this) {
10049                     writeBroadcastsToProtoLocked(proto);
10050                 }
10051             } else if ("provider".equals(cmd)) {
10052                 String[] newArgs;
10053                 String name;
10054                 if (opti >= args.length) {
10055                     name = null;
10056                     newArgs = EMPTY_STRING_ARRAY;
10057                 } else {
10058                     name = args[opti];
10059                     opti++;
10060                     newArgs = new String[args.length - opti];
10061                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10062                             args.length - opti);
10063                 }
10064                 if (!dumpProviderProto(fd, pw, name, newArgs)) {
10065                     pw.println("No providers match: " + name);
10066                     pw.println("Use -h for help.");
10067                 }
10068             } else if ("service".equals(cmd)) {
10069                 // output proto is ActivityManagerServiceDumpServicesProto
10070                 mServices.writeToProto(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10071             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10072                 if (opti < args.length) {
10073                     dumpPackage = args[opti];
10074                     opti++;
10075                 }
10076                 // output proto is ProcessProto
10077                 synchronized (this) {
10078                     writeProcessesToProtoLocked(proto, dumpPackage);
10079                 }
10080             } else {
10081                 // default option, dump everything, output is ActivityManagerServiceProto
10082                 synchronized (this) {
10083                     long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES);
10084                     mAtmInternal.writeActivitiesToProto(proto);
10085                     proto.end(activityToken);
10086 
10087                     long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS);
10088                     writeBroadcastsToProtoLocked(proto);
10089                     proto.end(broadcastToken);
10090 
10091                     long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES);
10092                     mServices.writeToProto(proto,
10093                             ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10094                     proto.end(serviceToken);
10095 
10096                     long processToken = proto.start(ActivityManagerServiceProto.PROCESSES);
10097                     writeProcessesToProtoLocked(proto, dumpPackage);
10098                     proto.end(processToken);
10099                 }
10100             }
10101             proto.flush();
10102             Binder.restoreCallingIdentity(origId);
10103             return;
10104         }
10105 
10106         int dumpAppId = getAppId(dumpPackage);
10107         boolean more = false;
10108         // Is the caller requesting to dump a particular piece of data?
10109         if (opti < args.length) {
10110             String cmd = args[opti];
10111             opti++;
10112             if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
10113                     || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
10114                     || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
10115                     || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
10116                 mAtmInternal.dump(
10117                         cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage);
10118             } else if ("binder-proxies".equals(cmd)) {
10119                 if (opti >= args.length) {
10120                     dumpBinderProxies(pw, 0 /* minToDump */);
10121                 } else {
10122                     String uid = args[opti];
10123                     opti++;
10124                     // Ensure Binder Proxy Count is as up to date as possible
10125                     System.gc();
10126                     System.runFinalization();
10127                     System.gc();
10128                     pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid)));
10129                 }
10130             } else if ("allowed-associations".equals(cmd)) {
10131                 if (opti < args.length) {
10132                     dumpPackage = args[opti];
10133                     opti++;
10134                 }
10135                 synchronized (this) {
10136                     dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage);
10137                 }
10138             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10139                 if (opti < args.length) {
10140                     dumpPackage = args[opti];
10141                     opti++;
10142                 }
10143                 synchronized (this) {
10144                     dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage);
10145                 }
10146             } else if ("broadcast-stats".equals(cmd)) {
10147                 if (opti < args.length) {
10148                     dumpPackage = args[opti];
10149                     opti++;
10150                 }
10151                 synchronized (this) {
10152                     if (dumpCheckinFormat) {
10153                         dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
10154                                 dumpPackage);
10155                     } else {
10156                         dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
10157                     }
10158                 }
10159             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
10160                 if (opti < args.length) {
10161                     dumpPackage = args[opti];
10162                     opti++;
10163                 }
10164                 synchronized (this) {
10165                     mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage);
10166                 }
10167             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10168                 if (opti < args.length) {
10169                     dumpPackage = args[opti];
10170                     opti++;
10171                 }
10172                 synchronized (this) {
10173                     dumpProcessesLocked(fd, pw, args, opti, true, dumpPackage, dumpAppId);
10174                 }
10175             } else if ("oom".equals(cmd) || "o".equals(cmd)) {
10176                 synchronized (this) {
10177                     dumpOomLocked(fd, pw, args, opti, true);
10178                 }
10179             } else if ("lmk".equals(cmd)) {
10180                 synchronized (this) {
10181                     dumpLmkLocked(pw);
10182                 }
10183             } else if ("lru".equals(cmd)) {
10184                 synchronized (this) {
10185                     dumpLruLocked(pw, null);
10186                 }
10187             } else if ("permissions".equals(cmd) || "perm".equals(cmd)) {
10188                 synchronized (this) {
10189                     dumpPermissionsLocked(fd, pw, args, opti, true, null);
10190                 }
10191             } else if ("provider".equals(cmd)) {
10192                 String[] newArgs;
10193                 String name;
10194                 if (opti >= args.length) {
10195                     name = null;
10196                     newArgs = EMPTY_STRING_ARRAY;
10197                 } else {
10198                     name = args[opti];
10199                     opti++;
10200                     newArgs = new String[args.length - opti];
10201                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
10202                 }
10203                 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
10204                     pw.println("No providers match: " + name);
10205                     pw.println("Use -h for help.");
10206                 }
10207             } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
10208                 synchronized (this) {
10209                     dumpProvidersLocked(fd, pw, args, opti, true, null);
10210                 }
10211             } else if ("service".equals(cmd)) {
10212                 String[] newArgs;
10213                 String name;
10214                 if (opti >= args.length) {
10215                     name = null;
10216                     newArgs = EMPTY_STRING_ARRAY;
10217                 } else {
10218                     name = args[opti];
10219                     opti++;
10220                     newArgs = new String[args.length - opti];
10221                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10222                             args.length - opti);
10223                 }
10224                 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
10225                     pw.println("No services match: " + name);
10226                     pw.println("Use -h for help.");
10227                 }
10228             } else if ("package".equals(cmd)) {
10229                 String[] newArgs;
10230                 if (opti >= args.length) {
10231                     pw.println("package: no package name specified");
10232                     pw.println("Use -h for help.");
10233                 } else {
10234                     dumpPackage = args[opti];
10235                     opti++;
10236                     newArgs = new String[args.length - opti];
10237                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10238                             args.length - opti);
10239                     args = newArgs;
10240                     opti = 0;
10241                     more = true;
10242                 }
10243             } else if ("associations".equals(cmd) || "as".equals(cmd)) {
10244                 synchronized (this) {
10245                     dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage);
10246                 }
10247             } else if ("settings".equals(cmd)) {
10248                 synchronized (this) {
10249                     mConstants.dump(pw);
10250                     mOomAdjuster.dumpAppCompactorSettings(pw);
10251                 }
10252             } else if ("services".equals(cmd) || "s".equals(cmd)) {
10253                 if (dumpClient) {
10254                     ActiveServices.ServiceDumper dumper;
10255                     synchronized (this) {
10256                         dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10257                                 dumpPackage);
10258                     }
10259                     dumper.dumpWithClient();
10260                 } else {
10261                     synchronized (this) {
10262                         mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10263                                 dumpPackage).dumpLocked();
10264                     }
10265                 }
10266             } else if ("locks".equals(cmd)) {
10267                 LockGuard.dump(fd, pw, args);
10268             } else {
10269                 // Dumping a single activity?
10270                 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll,
10271                         dumpVisibleStacksOnly, dumpFocusedStackOnly)) {
10272                     ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true);
10273                     int res = shell.exec(this, null, fd, null, args, null,
10274                             new ResultReceiver(null));
10275                     if (res < 0) {
10276                         pw.println("Bad activity command, or no activities match: " + cmd);
10277                         pw.println("Use -h for help.");
10278                     }
10279                 }
10280             }
10281             if (!more) {
10282                 Binder.restoreCallingIdentity(origId);
10283                 return;
10284             }
10285         }
10286 
10287         // No piece of data specified, dump everything.
10288         if (dumpCheckinFormat) {
10289             dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage);
10290         } else {
10291             if (dumpClient) {
10292                 // dumpEverything() will take the lock when needed, and momentarily drop
10293                 // it for dumping client state.
10294                 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
10295                         dumpNormalPriority, dumpAppId);
10296             } else {
10297                 // Take the lock here, so we get a consistent state for the entire dump;
10298                 // dumpEverything() will take the lock as well, but that is fine.
10299                 synchronized(this) {
10300                     dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
10301                             dumpNormalPriority, dumpAppId);
10302                 }
10303             }
10304         }
10305         Binder.restoreCallingIdentity(origId);
10306     }
10307 
dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)10308     void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10309             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
10310         pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)");
10311 
10312         int dumpUid = 0;
10313         if (dumpPackage != null) {
10314             IPackageManager pm = AppGlobals.getPackageManager();
10315             try {
10316                 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0);
10317             } catch (RemoteException e) {
10318             }
10319         }
10320 
10321         boolean printedAnything = false;
10322 
10323         final long now = SystemClock.uptimeMillis();
10324 
10325         for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
10326             ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
10327                     = mAssociations.valueAt(i1);
10328             for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
10329                 SparseArray<ArrayMap<String, Association>> sourceUids
10330                         = targetComponents.valueAt(i2);
10331                 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) {
10332                     ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3);
10333                     for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
10334                         Association ass = sourceProcesses.valueAt(i4);
10335                         if (dumpPackage != null) {
10336                             if (!ass.mTargetComponent.getPackageName().equals(dumpPackage)
10337                                     && UserHandle.getAppId(ass.mSourceUid) != dumpUid) {
10338                                 continue;
10339                             }
10340                         }
10341                         printedAnything = true;
10342                         pw.print("  ");
10343                         pw.print(ass.mTargetProcess);
10344                         pw.print("/");
10345                         UserHandle.formatUid(pw, ass.mTargetUid);
10346                         pw.print(" <- ");
10347                         pw.print(ass.mSourceProcess);
10348                         pw.print("/");
10349                         UserHandle.formatUid(pw, ass.mSourceUid);
10350                         pw.println();
10351                         pw.print("    via ");
10352                         pw.print(ass.mTargetComponent.flattenToShortString());
10353                         pw.println();
10354                         pw.print("    ");
10355                         long dur = ass.mTime;
10356                         if (ass.mNesting > 0) {
10357                             dur += now - ass.mStartTime;
10358                         }
10359                         TimeUtils.formatDuration(dur, pw);
10360                         pw.print(" (");
10361                         pw.print(ass.mCount);
10362                         pw.print(" times)");
10363                         pw.print("  ");
10364                         for (int i=0; i<ass.mStateTimes.length; i++) {
10365                             long amt = ass.mStateTimes[i];
10366                             if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10367                                 amt += now - ass.mLastStateUptime;
10368                             }
10369                             if (amt != 0) {
10370                                 pw.print(" ");
10371                                 pw.print(ProcessList.makeProcStateString(
10372                                             i + ActivityManager.MIN_PROCESS_STATE));
10373                                 pw.print("=");
10374                                 TimeUtils.formatDuration(amt, pw);
10375                                 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10376                                     pw.print("*");
10377                                 }
10378                             }
10379                         }
10380                         pw.println();
10381                         if (ass.mNesting > 0) {
10382                             pw.print("    Currently active: ");
10383                             TimeUtils.formatDuration(now - ass.mStartTime, pw);
10384                             pw.println();
10385                         }
10386                     }
10387                 }
10388             }
10389 
10390         }
10391 
10392         if (!printedAnything) {
10393             pw.println("  (nothing)");
10394         }
10395     }
10396 
getAppId(String dumpPackage)10397     private int getAppId(String dumpPackage) {
10398         if (dumpPackage != null) {
10399             try {
10400                 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
10401                         dumpPackage, 0);
10402                 return UserHandle.getAppId(info.uid);
10403             } catch (NameNotFoundException e) {
10404                 e.printStackTrace();
10405             }
10406         }
10407         return -1;
10408     }
10409 
dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids, String header, boolean needSep)10410     boolean dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids,
10411                 String header, boolean needSep) {
10412         boolean printed = false;
10413         for (int i=0; i<uids.size(); i++) {
10414             UidRecord uidRec = uids.valueAt(i);
10415             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != dumpAppId) {
10416                 continue;
10417             }
10418             if (!printed) {
10419                 printed = true;
10420                 if (needSep) {
10421                     pw.println();
10422                 }
10423                 pw.print("  ");
10424                 pw.println(header);
10425                 needSep = true;
10426             }
10427             pw.print("    UID "); UserHandle.formatUid(pw, uidRec.uid);
10428             pw.print(": "); pw.println(uidRec);
10429         }
10430         return printed;
10431     }
10432 
dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)10433     void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) {
10434         final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50);
10435 
10436         pw.println(header);
10437         for (int i = 0; i < proxyCounts.length; i++) {
10438             pw.println("    #" + (i + 1) + ": " + proxyCounts[i]);
10439         }
10440     }
10441 
dumpBinderProxiesCounts(PrintWriter pw, String header)10442     boolean dumpBinderProxiesCounts(PrintWriter pw, String header) {
10443         SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
10444         if(counts != null) {
10445             pw.println(header);
10446             for (int i = 0; i < counts.size(); i++) {
10447                 final int uid = counts.keyAt(i);
10448                 final int binderCount = counts.valueAt(i);
10449                 pw.print("    UID ");
10450                 pw.print(uid);
10451                 pw.print(", binder count = ");
10452                 pw.print(binderCount);
10453                 pw.print(", package(s)= ");
10454                 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid);
10455                 if (pkgNames != null) {
10456                     for (int j = 0; j < pkgNames.length; j++) {
10457                         pw.print(pkgNames[j]);
10458                         pw.print("; ");
10459                     }
10460                 } else {
10461                     pw.print("NO PACKAGE NAME FOUND");
10462                 }
10463                 pw.println();
10464             }
10465             return true;
10466         }
10467         return false;
10468     }
10469 
dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)10470     void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) {
10471         pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)");
10472         final int proxyCount = BinderProxy.getProxyCount();
10473         if (proxyCount >= minCountToDumpInterfaces) {
10474             dumpBinderProxyInterfaceCounts(pw,
10475                     "Top proxy interface names held by SYSTEM");
10476         } else {
10477             pw.print("Not dumping proxy interface counts because size ("
10478                     + Integer.toString(proxyCount) + ") looks reasonable");
10479             pw.println();
10480         }
10481         dumpBinderProxiesCounts(pw,
10482                 "  Counts of Binder Proxies held by SYSTEM");
10483     }
10484 
dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc)10485     void dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc) {
10486         pw.print("    #");
10487         pw.print(index);
10488         pw.print(": ");
10489         pw.print(ProcessList.makeOomAdjString(proc.setAdj, false));
10490         pw.print(" ");
10491         pw.print(ProcessList.makeProcStateString(proc.getCurProcState()));
10492         pw.print(" ");
10493         pw.print(proc.toShortString());
10494         pw.print(" ");
10495         if (proc.hasActivitiesOrRecentTasks() || proc.hasClientActivities()
10496                 || proc.treatLikeActivity) {
10497             pw.print(" activity=");
10498             boolean printed = false;
10499             if (proc.hasActivities()) {
10500                 pw.print("activities");
10501                 printed = true;
10502             }
10503             if (proc.hasRecentTasks()) {
10504                 if (printed) {
10505                     pw.print("|");
10506                 }
10507                 pw.print("recents");
10508                 printed = true;
10509             }
10510             if (proc.hasClientActivities()) {
10511                 if (printed) {
10512                     pw.print("|");
10513                 }
10514                 pw.print("client");
10515                 printed = true;
10516             }
10517             if (proc.treatLikeActivity) {
10518                 if (printed) {
10519                     pw.print("|");
10520                 }
10521                 pw.print("treated");
10522             }
10523         }
10524         pw.println();
10525     }
10526 
10527     // TODO: Move to ProcessList?
dumpLruLocked(PrintWriter pw, String dumpPackage)10528     void dumpLruLocked(PrintWriter pw, String dumpPackage) {
10529         pw.println("ACTIVITY MANAGER LRU PROCESSES (dumpsys activity lru)");
10530         final int N = mProcessList.mLruProcesses.size();
10531         int i;
10532         boolean first = true;
10533         for (i = N - 1; i >= mProcessList.mLruProcessActivityStart; i--) {
10534             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
10535             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10536                 continue;
10537             }
10538             if (first) {
10539                 pw.println("  Activities:");
10540                 first = false;
10541             }
10542             dumpLruEntryLocked(pw, i, r);
10543         }
10544         first = true;
10545         for (; i >= mProcessList.mLruProcessServiceStart; i--) {
10546             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
10547             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10548                 continue;
10549             }
10550             if (first) {
10551                 pw.println("  Services:");
10552                 first = false;
10553             }
10554             dumpLruEntryLocked(pw, i, r);
10555         }
10556         first = true;
10557         for (; i >= 0; i--) {
10558             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
10559             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10560                 continue;
10561             }
10562             if (first) {
10563                 pw.println("  Other:");
10564                 first = false;
10565             }
10566             dumpLruEntryLocked(pw, i, r);
10567         }
10568     }
10569 
10570     // TODO: Move to ProcessList?
10571     @GuardedBy("this")
dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int dumpAppId)10572     void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10573             int opti, boolean dumpAll, String dumpPackage, int dumpAppId) {
10574         boolean needSep = false;
10575         int numPers = 0;
10576 
10577         pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
10578 
10579         if (dumpAll) {
10580             final int NP = mProcessList.mProcessNames.getMap().size();
10581             for (int ip=0; ip<NP; ip++) {
10582                 SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip);
10583                 final int NA = procs.size();
10584                 for (int ia=0; ia<NA; ia++) {
10585                     ProcessRecord r = procs.valueAt(ia);
10586                     if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10587                         continue;
10588                     }
10589                     if (!needSep) {
10590                         pw.println("  All known processes:");
10591                         needSep = true;
10592                     }
10593                     pw.print(r.isPersistent() ? "  *PERS*" : "  *APP*");
10594                         pw.print(" UID "); pw.print(procs.keyAt(ia));
10595                         pw.print(" "); pw.println(r);
10596                     r.dump(pw, "    ");
10597                     if (r.isPersistent()) {
10598                         numPers++;
10599                     }
10600                 }
10601             }
10602         }
10603 
10604         if (mProcessList.mIsolatedProcesses.size() > 0) {
10605             boolean printed = false;
10606             for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) {
10607                 ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i);
10608                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10609                     continue;
10610                 }
10611                 if (!printed) {
10612                     if (needSep) {
10613                         pw.println();
10614                     }
10615                     pw.println("  Isolated process list (sorted by uid):");
10616                     printed = true;
10617                     needSep = true;
10618                 }
10619                 pw.print("    Isolated #"); pw.print(i); pw.print(": ");
10620                 pw.println(r);
10621             }
10622         }
10623 
10624         if (mActiveInstrumentation.size() > 0) {
10625             boolean printed = false;
10626             for (int i=0; i<mActiveInstrumentation.size(); i++) {
10627                 ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10628                 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10629                         && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10630                     continue;
10631                 }
10632                 if (!printed) {
10633                     if (needSep) {
10634                         pw.println();
10635                     }
10636                     pw.println("  Active instrumentation:");
10637                     printed = true;
10638                     needSep = true;
10639                 }
10640                 pw.print("    Instrumentation #"); pw.print(i); pw.print(": ");
10641                 pw.println(ai);
10642                 ai.dump(pw, "      ");
10643             }
10644         }
10645 
10646         if (mProcessList.mActiveUids.size() > 0) {
10647             if (dumpUids(pw, dumpPackage, dumpAppId, mProcessList.mActiveUids,
10648                     "UID states:", needSep)) {
10649                 needSep = true;
10650             }
10651         }
10652 
10653         if (dumpAll) {
10654             if (mValidateUids.size() > 0) {
10655                 if (dumpUids(pw, dumpPackage, dumpAppId, mValidateUids, "UID validation:",
10656                         needSep)) {
10657                     needSep = true;
10658                 }
10659             }
10660         }
10661 
10662         if (mProcessList.getLruSizeLocked() > 0) {
10663             if (needSep) {
10664                 pw.println();
10665             }
10666             mProcessList.dumpLruListHeaderLocked(pw);
10667             dumpProcessOomList(pw, this, mProcessList.mLruProcesses, "    ", "Proc", "PERS", false,
10668                     dumpPackage);
10669             needSep = true;
10670         }
10671 
10672         if (dumpAll || dumpPackage != null) {
10673             synchronized (mPidsSelfLocked) {
10674                 boolean printed = false;
10675                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
10676                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10677                     if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10678                         continue;
10679                     }
10680                     if (!printed) {
10681                         if (needSep) pw.println();
10682                         needSep = true;
10683                         pw.println("  PID mappings:");
10684                         printed = true;
10685                     }
10686                     pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
10687                         pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
10688                 }
10689             }
10690         }
10691 
10692         if (mImportantProcesses.size() > 0) {
10693             synchronized (mPidsSelfLocked) {
10694                 boolean printed = false;
10695                 for (int i = 0; i< mImportantProcesses.size(); i++) {
10696                     ProcessRecord r = mPidsSelfLocked.get(
10697                             mImportantProcesses.valueAt(i).pid);
10698                     if (dumpPackage != null && (r == null
10699                             || !r.pkgList.containsKey(dumpPackage))) {
10700                         continue;
10701                     }
10702                     if (!printed) {
10703                         if (needSep) pw.println();
10704                         needSep = true;
10705                         pw.println("  Foreground Processes:");
10706                         printed = true;
10707                     }
10708                     pw.print("    PID #"); pw.print(mImportantProcesses.keyAt(i));
10709                             pw.print(": "); pw.println(mImportantProcesses.valueAt(i));
10710                 }
10711             }
10712         }
10713 
10714         if (mPersistentStartingProcesses.size() > 0) {
10715             if (needSep) pw.println();
10716             needSep = true;
10717             pw.println("  Persisent processes that are starting:");
10718             dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
10719                     "Starting Norm", "Restarting PERS", dumpPackage);
10720         }
10721 
10722         if (mProcessList.mRemovedProcesses.size() > 0) {
10723             if (needSep) pw.println();
10724             needSep = true;
10725             pw.println("  Processes that are being removed:");
10726             dumpProcessList(pw, this, mProcessList.mRemovedProcesses, "    ",
10727                     "Removed Norm", "Removed PERS", dumpPackage);
10728         }
10729 
10730         if (mProcessesOnHold.size() > 0) {
10731             if (needSep) pw.println();
10732             needSep = true;
10733             pw.println("  Processes that are on old until the system is ready:");
10734             dumpProcessList(pw, this, mProcessesOnHold, "    ",
10735                     "OnHold Norm", "OnHold PERS", dumpPackage);
10736         }
10737 
10738         needSep = dumpProcessesToGc(pw, needSep, dumpPackage);
10739 
10740         needSep = mAppErrors.dumpLocked(fd, pw, needSep, dumpPackage);
10741 
10742         if (dumpPackage == null) {
10743             pw.println();
10744             needSep = false;
10745             mUserController.dump(pw, dumpAll);
10746         }
10747 
10748         needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep,
10749                 mTestPssMode, mWakefulness);
10750 
10751         if (dumpAll && mProcessList.mPendingStarts.size() > 0) {
10752             if (needSep) pw.println();
10753             needSep = true;
10754             pw.println("  mPendingStarts: ");
10755             for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) {
10756                 pw.println("    " + mProcessList.mPendingStarts.keyAt(i) + ": "
10757                         + mProcessList.mPendingStarts.valueAt(i));
10758             }
10759         }
10760         if (dumpAll) {
10761             final int NI = mUidObservers.getRegisteredCallbackCount();
10762             boolean printed = false;
10763             for (int i=0; i<NI; i++) {
10764                 final UidObserverRegistration reg = (UidObserverRegistration)
10765                         mUidObservers.getRegisteredCallbackCookie(i);
10766                 if (dumpPackage == null || dumpPackage.equals(reg.pkg)) {
10767                     if (!printed) {
10768                         pw.println("  mUidObservers:");
10769                         printed = true;
10770                     }
10771                     pw.print("    "); UserHandle.formatUid(pw, reg.uid);
10772                     pw.print(" "); pw.print(reg.pkg);
10773                     final IUidObserver observer = mUidObservers.getRegisteredCallbackItem(i);
10774                     pw.print(" "); pw.print(observer.getClass().getTypeName()); pw.print(":");
10775                     if ((reg.which&ActivityManager.UID_OBSERVER_IDLE) != 0) {
10776                         pw.print(" IDLE");
10777                     }
10778                     if ((reg.which&ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
10779                         pw.print(" ACT" );
10780                     }
10781                     if ((reg.which&ActivityManager.UID_OBSERVER_GONE) != 0) {
10782                         pw.print(" GONE");
10783                     }
10784                     if ((reg.which&ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
10785                         pw.print(" STATE");
10786                         pw.print(" (cut="); pw.print(reg.cutpoint);
10787                         pw.print(")");
10788                     }
10789                     pw.println();
10790                     if (reg.lastProcStates != null) {
10791                         final int NJ = reg.lastProcStates.size();
10792                         for (int j=0; j<NJ; j++) {
10793                             pw.print("      Last ");
10794                             UserHandle.formatUid(pw, reg.lastProcStates.keyAt(j));
10795                             pw.print(": "); pw.println(reg.lastProcStates.valueAt(j));
10796                         }
10797                     }
10798                 }
10799             }
10800             pw.println("  mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
10801             pw.println("  mDeviceIdleExceptIdleWhitelist="
10802                     + Arrays.toString(mDeviceIdleExceptIdleWhitelist));
10803             pw.println("  mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
10804             if (mPendingTempWhitelist.size() > 0) {
10805                 pw.println("  mPendingTempWhitelist:");
10806                 for (int i = 0; i < mPendingTempWhitelist.size(); i++) {
10807                     PendingTempWhitelist ptw = mPendingTempWhitelist.valueAt(i);
10808                     pw.print("    ");
10809                     UserHandle.formatUid(pw, ptw.targetUid);
10810                     pw.print(": ");
10811                     TimeUtils.formatDuration(ptw.duration, pw);
10812                     pw.print(" ");
10813                     pw.println(ptw.tag);
10814                 }
10815             }
10816         }
10817         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
10818                 || mOrigWaitForDebugger) {
10819             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
10820                     || dumpPackage.equals(mOrigDebugApp)) {
10821                 if (needSep) {
10822                     pw.println();
10823                     needSep = false;
10824                 }
10825                 pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
10826                         + " mDebugTransient=" + mDebugTransient
10827                         + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
10828             }
10829         }
10830         if (mMemWatchProcesses.getMap().size() > 0) {
10831             pw.println("  Mem watch processes:");
10832             final ArrayMap<String, SparseArray<Pair<Long, String>>> procs
10833                     = mMemWatchProcesses.getMap();
10834             for (int i=0; i<procs.size(); i++) {
10835                 final String proc = procs.keyAt(i);
10836                 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i);
10837                 for (int j=0; j<uids.size(); j++) {
10838                     if (needSep) {
10839                         pw.println();
10840                         needSep = false;
10841                     }
10842                     StringBuilder sb = new StringBuilder();
10843                     sb.append("    ").append(proc).append('/');
10844                     UserHandle.formatUid(sb, uids.keyAt(j));
10845                     Pair<Long, String> val = uids.valueAt(j);
10846                     sb.append(": "); DebugUtils.sizeValueToString(val.first, sb);
10847                     if (val.second != null) {
10848                         sb.append(", report to ").append(val.second);
10849                     }
10850                     pw.println(sb.toString());
10851                 }
10852             }
10853             pw.print("  mMemWatchDumpProcName="); pw.println(mMemWatchDumpProcName);
10854             pw.print("  mMemWatchDumpFile="); pw.println(mMemWatchDumpFile);
10855             pw.print("  mMemWatchDumpPid="); pw.println(mMemWatchDumpPid);
10856             pw.print("  mMemWatchDumpUid="); pw.println(mMemWatchDumpUid);
10857             pw.print("  mMemWatchIsUserInitiated="); pw.println(mMemWatchIsUserInitiated);
10858         }
10859         if (mTrackAllocationApp != null) {
10860             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
10861                 if (needSep) {
10862                     pw.println();
10863                     needSep = false;
10864                 }
10865                 pw.println("  mTrackAllocationApp=" + mTrackAllocationApp);
10866             }
10867         }
10868         if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null
10869                 || (mProfileData.getProfilerInfo() != null &&
10870                 (mProfileData.getProfilerInfo().profileFile != null
10871                         || mProfileData.getProfilerInfo().profileFd != null))) {
10872             if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) {
10873                 if (needSep) {
10874                     pw.println();
10875                     needSep = false;
10876                 }
10877                 pw.println("  mProfileApp=" + mProfileData.getProfileApp()
10878                         + " mProfileProc=" + mProfileData.getProfileProc());
10879                 if (mProfileData.getProfilerInfo() != null) {
10880                     pw.println("  mProfileFile=" + mProfileData.getProfilerInfo().profileFile
10881                             + " mProfileFd=" + mProfileData.getProfilerInfo().profileFd);
10882                     pw.println("  mSamplingInterval="
10883                             + mProfileData.getProfilerInfo().samplingInterval +
10884                             " mAutoStopProfiler="
10885                             + mProfileData.getProfilerInfo().autoStopProfiler +
10886                             " mStreamingOutput=" + mProfileData.getProfilerInfo().streamingOutput);
10887                     pw.println("  mProfileType=" + mProfileType);
10888                 }
10889             }
10890         }
10891         if (mNativeDebuggingApp != null) {
10892             if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
10893                 if (needSep) {
10894                     pw.println();
10895                     needSep = false;
10896                 }
10897                 pw.println("  mNativeDebuggingApp=" + mNativeDebuggingApp);
10898             }
10899         }
10900         if (dumpPackage == null) {
10901             if (mAlwaysFinishActivities) {
10902                 pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities);
10903             }
10904             if (dumpAll) {
10905                 pw.println("  Total persistent processes: " + numPers);
10906                 pw.println("  mProcessesReady=" + mProcessesReady
10907                         + " mSystemReady=" + mSystemReady
10908                         + " mBooted=" + mBooted
10909                         + " mFactoryTest=" + mFactoryTest);
10910                 pw.println("  mBooting=" + mBooting
10911                         + " mCallFinishBooting=" + mCallFinishBooting
10912                         + " mBootAnimationComplete=" + mBootAnimationComplete);
10913                 pw.print("  mLastPowerCheckUptime=");
10914                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
10915                         pw.println("");
10916                 mOomAdjuster.dumpSequenceNumbersLocked(pw);
10917                 mOomAdjuster.dumpProcCountsLocked(pw);
10918                 pw.println("  mAllowLowerMemLevel=" + mAllowLowerMemLevel
10919                         + " mLastMemoryLevel=" + mLastMemoryLevel
10920                         + " mLastNumProcesses=" + mLastNumProcesses);
10921                 long now = SystemClock.uptimeMillis();
10922                 pw.print("  mLastIdleTime=");
10923                         TimeUtils.formatDuration(now, mLastIdleTime, pw);
10924                         pw.print(" mLowRamSinceLastIdle=");
10925                         TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw);
10926                         pw.println();
10927                 pw.println();
10928                 pw.print("  mUidChangeDispatchCount=");
10929                 pw.print(mUidChangeDispatchCount);
10930                 pw.println();
10931 
10932                 pw.println("  Slow UID dispatches:");
10933                 final int N = mUidObservers.beginBroadcast();
10934                 for (int i = 0; i < N; i++) {
10935                     UidObserverRegistration r =
10936                             (UidObserverRegistration) mUidObservers.getBroadcastCookie(i);
10937                     pw.print("    ");
10938                     pw.print(mUidObservers.getBroadcastItem(i).getClass().getTypeName());
10939                     pw.print(": ");
10940                     pw.print(r.mSlowDispatchCount);
10941                     pw.print(" / Max ");
10942                     pw.print(r.mMaxDispatchTime);
10943                     pw.println("ms");
10944                 }
10945                 mUidObservers.finishBroadcast();
10946 
10947                 pw.println();
10948                 pw.println("  ServiceManager statistics:");
10949                 ServiceManager.sStatLogger.dump(pw, "    ");
10950                 pw.println();
10951             }
10952         }
10953         pw.println("  mForceBackgroundCheck=" + mForceBackgroundCheck);
10954     }
10955 
10956     @GuardedBy("this")
writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage)10957     void writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage) {
10958         int numPers = 0;
10959 
10960         final int NP = mProcessList.mProcessNames.getMap().size();
10961         for (int ip=0; ip<NP; ip++) {
10962             SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip);
10963             final int NA = procs.size();
10964             for (int ia = 0; ia<NA; ia++) {
10965                 ProcessRecord r = procs.valueAt(ia);
10966                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10967                     continue;
10968                 }
10969                 r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.PROCS,
10970                         mProcessList.mLruProcesses.indexOf(r)
10971                 );
10972                 if (r.isPersistent()) {
10973                     numPers++;
10974                 }
10975             }
10976         }
10977 
10978         for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) {
10979             ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i);
10980             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10981                 continue;
10982             }
10983             r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ISOLATED_PROCS,
10984                     mProcessList.mLruProcesses.indexOf(r)
10985             );
10986         }
10987 
10988         for (int i=0; i<mActiveInstrumentation.size(); i++) {
10989             ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10990             if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10991                     && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10992                 continue;
10993             }
10994             ai.writeToProto(proto,
10995                     ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS);
10996         }
10997 
10998         int whichAppId = getAppId(dumpPackage);
10999         for (int i = 0; i < mProcessList.mActiveUids.size(); i++) {
11000             UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
11001             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) {
11002                 continue;
11003             }
11004             uidRec.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ACTIVE_UIDS);
11005         }
11006 
11007         for (int i = 0; i < mValidateUids.size(); i++) {
11008             UidRecord uidRec = mValidateUids.valueAt(i);
11009             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) {
11010                 continue;
11011             }
11012             uidRec.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS);
11013         }
11014 
11015         if (mProcessList.getLruSizeLocked() > 0) {
11016             long lruToken = proto.start(ActivityManagerServiceDumpProcessesProto.LRU_PROCS);
11017             int total = mProcessList.getLruSizeLocked();
11018             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.SIZE, total);
11019             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_ACT_AT,
11020                     total - mProcessList.mLruProcessActivityStart);
11021             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_SVC_AT,
11022                     total - mProcessList.mLruProcessServiceStart);
11023             writeProcessOomListToProto(proto,
11024                     ActivityManagerServiceDumpProcessesProto.LruProcesses.LIST, this,
11025                     mProcessList.mLruProcesses,false, dumpPackage);
11026             proto.end(lruToken);
11027         }
11028 
11029         if (dumpPackage != null) {
11030             synchronized (mPidsSelfLocked) {
11031                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
11032                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
11033                     if (!r.pkgList.containsKey(dumpPackage)) {
11034                         continue;
11035                     }
11036                     r.writeToProto(proto,
11037                             ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED);
11038                 }
11039             }
11040         }
11041 
11042         if (mImportantProcesses.size() > 0) {
11043             synchronized (mPidsSelfLocked) {
11044                 for (int i=0; i<mImportantProcesses.size(); i++) {
11045                     ImportanceToken it = mImportantProcesses.valueAt(i);
11046                     ProcessRecord r = mPidsSelfLocked.get(it.pid);
11047                     if (dumpPackage != null && (r == null
11048                             || !r.pkgList.containsKey(dumpPackage))) {
11049                         continue;
11050                     }
11051                     it.writeToProto(proto,
11052                             ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS);
11053                 }
11054             }
11055         }
11056 
11057         for (int i=0; i<mPersistentStartingProcesses.size(); i++) {
11058             ProcessRecord r = mPersistentStartingProcesses.get(i);
11059             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11060                 continue;
11061             }
11062             r.writeToProto(proto,
11063                     ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS);
11064         }
11065 
11066         for (int i = 0; i < mProcessList.mRemovedProcesses.size(); i++) {
11067             ProcessRecord r = mProcessList.mRemovedProcesses.get(i);
11068             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11069                 continue;
11070             }
11071             r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS);
11072         }
11073 
11074         for (int i=0; i<mProcessesOnHold.size(); i++) {
11075             ProcessRecord r = mProcessesOnHold.get(i);
11076             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11077                 continue;
11078             }
11079             r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS);
11080         }
11081 
11082         writeProcessesToGcToProto(proto, ActivityManagerServiceDumpProcessesProto.GC_PROCS,
11083                 dumpPackage);
11084         mAppErrors.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS,
11085                 dumpPackage);
11086         mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness, mTestPssMode);
11087 
11088         if (dumpPackage == null) {
11089             mUserController.writeToProto(proto,
11090             ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER);
11091         }
11092 
11093         final int NI = mUidObservers.getRegisteredCallbackCount();
11094         for (int i=0; i<NI; i++) {
11095             final UidObserverRegistration reg = (UidObserverRegistration)
11096                     mUidObservers.getRegisteredCallbackCookie(i);
11097             if (dumpPackage == null || dumpPackage.equals(reg.pkg)) {
11098                 reg.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.UID_OBSERVERS);
11099             }
11100         }
11101 
11102         for (int v : mDeviceIdleWhitelist) {
11103             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v);
11104         }
11105 
11106         for (int v : mDeviceIdleTempWhitelist) {
11107             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v);
11108         }
11109 
11110         if (mPendingTempWhitelist.size() > 0) {
11111             for (int i=0; i < mPendingTempWhitelist.size(); i++) {
11112                 mPendingTempWhitelist.valueAt(i).writeToProto(proto,
11113                         ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST);
11114             }
11115         }
11116 
11117         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
11118                 || mOrigWaitForDebugger) {
11119             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
11120                     || dumpPackage.equals(mOrigDebugApp)) {
11121                 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG);
11122                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp);
11123                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp);
11124                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient);
11125                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger);
11126                 proto.end(debugAppToken);
11127             }
11128         }
11129 
11130         if (mMemWatchProcesses.getMap().size() > 0) {
11131             final long token = proto.start(ActivityManagerServiceDumpProcessesProto.MEM_WATCH_PROCESSES);
11132             ArrayMap<String, SparseArray<Pair<Long, String>>> procs = mMemWatchProcesses.getMap();
11133             for (int i=0; i<procs.size(); i++) {
11134                 final String proc = procs.keyAt(i);
11135                 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i);
11136                 final long ptoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.PROCS);
11137                 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.NAME, proc);
11138                 for (int j=0; j<uids.size(); j++) {
11139                     final long utoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MEM_STATS);
11140                     Pair<Long, String> val = uids.valueAt(j);
11141                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.UID, uids.keyAt(j));
11142                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.SIZE,
11143                             DebugUtils.sizeValueToString(val.first, new StringBuilder()));
11144                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.REPORT_TO, val.second);
11145                     proto.end(utoken);
11146                 }
11147                 proto.end(ptoken);
11148             }
11149 
11150             final long dtoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.DUMP);
11151             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PROC_NAME, mMemWatchDumpProcName);
11152             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.FILE, mMemWatchDumpFile);
11153             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PID, mMemWatchDumpPid);
11154             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.UID, mMemWatchDumpUid);
11155             proto.write(
11156                     ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.IS_USER_INITIATED,
11157                     mMemWatchIsUserInitiated);
11158             proto.end(dtoken);
11159 
11160             proto.end(token);
11161         }
11162 
11163         if (mTrackAllocationApp != null) {
11164             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
11165                 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP,
11166                         mTrackAllocationApp);
11167             }
11168         }
11169 
11170         if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null
11171                 || (mProfileData.getProfilerInfo() != null &&
11172                 (mProfileData.getProfilerInfo().profileFile != null
11173                         || mProfileData.getProfilerInfo().profileFd != null))) {
11174             if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) {
11175                 final long token = proto.start(ActivityManagerServiceDumpProcessesProto.PROFILE);
11176                 proto.write(ActivityManagerServiceDumpProcessesProto.Profile.APP_NAME,
11177                         mProfileData.getProfileApp());
11178                 mProfileData.getProfileProc().writeToProto(proto,
11179                         ActivityManagerServiceDumpProcessesProto.Profile.PROC);
11180                 if (mProfileData.getProfilerInfo() != null) {
11181                     mProfileData.getProfilerInfo().writeToProto(proto,
11182                             ActivityManagerServiceDumpProcessesProto.Profile.INFO);
11183                     proto.write(ActivityManagerServiceDumpProcessesProto.Profile.TYPE,
11184                             mProfileType);
11185                 }
11186                 proto.end(token);
11187             }
11188         }
11189 
11190         if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
11191             proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp);
11192         }
11193 
11194         if (dumpPackage == null) {
11195             proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities);
11196             proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers);
11197             proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady);
11198             proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady);
11199             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted);
11200             proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest);
11201             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting);
11202             proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting);
11203             proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete);
11204             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime);
11205             mOomAdjuster.dumpProcessListVariablesLocked(proto);
11206             proto.write(ActivityManagerServiceDumpProcessesProto.ALLOW_LOWER_MEM_LEVEL, mAllowLowerMemLevel);
11207             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_MEMORY_LEVEL, mLastMemoryLevel);
11208             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_NUM_PROCESSES, mLastNumProcesses);
11209             long now = SystemClock.uptimeMillis();
11210             ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now);
11211             proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, getLowRamTimeSinceIdle(now));
11212         }
11213     }
11214 
writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage)11215     void writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage) {
11216         if (mProcessesToGc.size() > 0) {
11217             long now = SystemClock.uptimeMillis();
11218             for (int i=0; i<mProcessesToGc.size(); i++) {
11219                 ProcessRecord r = mProcessesToGc.get(i);
11220                 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11221                     continue;
11222                 }
11223                 final long token = proto.start(fieldId);
11224                 r.writeToProto(proto, ProcessToGcProto.PROC);
11225                 proto.write(ProcessToGcProto.REPORT_LOW_MEMORY, r.reportLowMemory);
11226                 proto.write(ProcessToGcProto.NOW_UPTIME_MS, now);
11227                 proto.write(ProcessToGcProto.LAST_GCED_MS, r.lastRequestedGc);
11228                 proto.write(ProcessToGcProto.LAST_LOW_MEMORY_MS, r.lastLowMemory);
11229                 proto.end(token);
11230             }
11231         }
11232     }
11233 
dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage)11234     boolean dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage) {
11235         if (mProcessesToGc.size() > 0) {
11236             boolean printed = false;
11237             long now = SystemClock.uptimeMillis();
11238             for (int i=0; i<mProcessesToGc.size(); i++) {
11239                 ProcessRecord proc = mProcessesToGc.get(i);
11240                 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
11241                     continue;
11242                 }
11243                 if (!printed) {
11244                     if (needSep) pw.println();
11245                     needSep = true;
11246                     pw.println("  Processes that are waiting to GC:");
11247                     printed = true;
11248                 }
11249                 pw.print("    Process "); pw.println(proc);
11250                 pw.print("      lowMem="); pw.print(proc.reportLowMemory);
11251                         pw.print(", last gced=");
11252                         pw.print(now-proc.lastRequestedGc);
11253                         pw.print(" ms ago, last lowMem=");
11254                         pw.print(now-proc.lastLowMemory);
11255                         pw.println(" ms ago");
11256 
11257             }
11258         }
11259         return needSep;
11260     }
11261 
printOomLevel(PrintWriter pw, String name, int adj)11262     void printOomLevel(PrintWriter pw, String name, int adj) {
11263         pw.print("    ");
11264         if (adj >= 0) {
11265             pw.print(' ');
11266             if (adj < 10) pw.print(' ');
11267         } else {
11268             if (adj > -10) pw.print(' ');
11269         }
11270         pw.print(adj);
11271         pw.print(": ");
11272         pw.print(name);
11273         pw.print(" (");
11274         pw.print(stringifySize(mProcessList.getMemLevel(adj), 1024));
11275         pw.println(")");
11276     }
11277 
dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll)11278     boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11279             int opti, boolean dumpAll) {
11280         boolean needSep = false;
11281 
11282         if (mProcessList.getLruSizeLocked() > 0) {
11283             if (needSep) pw.println();
11284             needSep = true;
11285             pw.println("  OOM levels:");
11286             printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ);
11287             printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ);
11288             printOomLevel(pw, "PERSISTENT_SERVICE_ADJ", ProcessList.PERSISTENT_SERVICE_ADJ);
11289             printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ);
11290             printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ);
11291             printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ);
11292             printOomLevel(pw, "PERCEPTIBLE_LOW_APP_ADJ", ProcessList.PERCEPTIBLE_LOW_APP_ADJ);
11293             printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ);
11294             printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ);
11295             printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ);
11296             printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ);
11297             printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ);
11298             printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ);
11299             printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ);
11300             printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ);
11301 
11302             if (needSep) pw.println();
11303             pw.print("  Process OOM control ("); pw.print(mProcessList.getLruSizeLocked());
11304                     pw.print(" total, non-act at ");
11305                     pw.print(mProcessList.getLruSizeLocked()
11306                             - mProcessList.mLruProcessActivityStart);
11307                     pw.print(", non-svc at ");
11308                     pw.print(mProcessList.getLruSizeLocked()
11309                             - mProcessList.mLruProcessServiceStart);
11310                     pw.println("):");
11311             dumpProcessOomList(pw, this, mProcessList.mLruProcesses, "    ", "Proc", "PERS", true,
11312                     null);
11313             needSep = true;
11314         }
11315 
11316         dumpProcessesToGc(pw, needSep, null);
11317 
11318         pw.println();
11319         mAtmInternal.dumpForOom(pw);
11320 
11321         return true;
11322     }
11323 
reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)11324     private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) {
11325         Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj);
11326         if (cnt != null) {
11327             pw.println("    kills at or below oom_adj " + oom_adj + ": " + cnt);
11328             return true;
11329         }
11330         return false;
11331     }
11332 
dumpLmkLocked(PrintWriter pw)11333     boolean dumpLmkLocked(PrintWriter pw) {
11334         pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)");
11335         Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ,
11336                 ProcessList.UNKNOWN_ADJ);
11337         if (cnt == null) {
11338             return false;
11339         }
11340         pw.println("  Total number of kills: " + cnt);
11341 
11342         return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) &&
11343                 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) &&
11344                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) &&
11345                 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) &&
11346                 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) &&
11347                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) &&
11348                 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) &&
11349                 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) &&
11350                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) &&
11351                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) &&
11352                 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) &&
11353                 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ);
11354     }
11355 
11356     /**
11357      * There are three ways to call this:
11358      *  - no provider specified: dump all the providers
11359      *  - a flattened component name that matched an existing provider was specified as the
11360      *    first arg: dump that one provider
11361      *  - the first arg isn't the flattened component name of an existing provider:
11362      *    dump all providers whose component contains the first arg as a substring
11363      */
dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)11364     protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
11365             int opti, boolean dumpAll) {
11366         return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
11367     }
11368 
11369     /**
11370      * Similar to the dumpProvider, but only dumps the first matching provider.
11371      * The provider is responsible for dumping as proto.
11372      */
dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, String[] args)11373     protected boolean dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name,
11374             String[] args) {
11375         return mProviderMap.dumpProviderProto(fd, pw, name, args);
11376     }
11377 
11378     public static class ItemMatcher {
11379         ArrayList<ComponentName> components;
11380         ArrayList<String> strings;
11381         ArrayList<Integer> objects;
11382         boolean all;
11383 
ItemMatcher()11384         public ItemMatcher() {
11385             all = true;
11386         }
11387 
build(String name)11388         public void build(String name) {
11389             ComponentName componentName = ComponentName.unflattenFromString(name);
11390             if (componentName != null) {
11391                 if (components == null) {
11392                     components = new ArrayList<ComponentName>();
11393                 }
11394                 components.add(componentName);
11395                 all = false;
11396             } else {
11397                 int objectId = 0;
11398                 // Not a '/' separated full component name; maybe an object ID?
11399                 try {
11400                     objectId = Integer.parseInt(name, 16);
11401                     if (objects == null) {
11402                         objects = new ArrayList<Integer>();
11403                     }
11404                     objects.add(objectId);
11405                     all = false;
11406                 } catch (RuntimeException e) {
11407                     // Not an integer; just do string match.
11408                     if (strings == null) {
11409                         strings = new ArrayList<String>();
11410                     }
11411                     strings.add(name);
11412                     all = false;
11413                 }
11414             }
11415         }
11416 
build(String[] args, int opti)11417         public int build(String[] args, int opti) {
11418             for (; opti<args.length; opti++) {
11419                 String name = args[opti];
11420                 if ("--".equals(name)) {
11421                     return opti+1;
11422                 }
11423                 build(name);
11424             }
11425             return opti;
11426         }
11427 
match(Object object, ComponentName comp)11428         public boolean match(Object object, ComponentName comp) {
11429             if (all) {
11430                 return true;
11431             }
11432             if (components != null) {
11433                 for (int i=0; i<components.size(); i++) {
11434                     if (components.get(i).equals(comp)) {
11435                         return true;
11436                     }
11437                 }
11438             }
11439             if (objects != null) {
11440                 for (int i=0; i<objects.size(); i++) {
11441                     if (System.identityHashCode(object) == objects.get(i)) {
11442                         return true;
11443                     }
11444                 }
11445             }
11446             if (strings != null) {
11447                 String flat = comp.flattenToString();
11448                 for (int i=0; i<strings.size(); i++) {
11449                     if (flat.contains(strings.get(i))) {
11450                         return true;
11451                     }
11452                 }
11453             }
11454             return false;
11455         }
11456     }
11457 
writeBroadcastsToProtoLocked(ProtoOutputStream proto)11458     void writeBroadcastsToProtoLocked(ProtoOutputStream proto) {
11459         if (mRegisteredReceivers.size() > 0) {
11460             Iterator it = mRegisteredReceivers.values().iterator();
11461             while (it.hasNext()) {
11462                 ReceiverList r = (ReceiverList)it.next();
11463                 r.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST);
11464             }
11465         }
11466         mReceiverResolver.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER);
11467         for (BroadcastQueue q : mBroadcastQueues) {
11468             q.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE);
11469         }
11470         for (int user=0; user<mStickyBroadcasts.size(); user++) {
11471             long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS);
11472             proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user));
11473             for (Map.Entry<String, ArrayList<Intent>> ent
11474                     : mStickyBroadcasts.valueAt(user).entrySet()) {
11475                 long actionToken = proto.start(StickyBroadcastProto.ACTIONS);
11476                 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey());
11477                 for (Intent intent : ent.getValue()) {
11478                     intent.writeToProto(proto, StickyBroadcastProto.StickyAction.INTENTS,
11479                             false, true, true, false);
11480                 }
11481                 proto.end(actionToken);
11482             }
11483             proto.end(token);
11484         }
11485 
11486         long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER);
11487         proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString());
11488         mHandler.getLooper().writeToProto(proto,
11489             ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER);
11490         proto.end(handlerToken);
11491     }
11492 
dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11493     void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11494             int opti, boolean dumpAll, String dumpPackage) {
11495         boolean needSep = false;
11496 
11497         pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)");
11498         boolean printed = false;
11499         if (mAllowedAssociations != null) {
11500             for (int i = 0; i < mAllowedAssociations.size(); i++) {
11501                 final String pkg = mAllowedAssociations.keyAt(i);
11502                 final ArraySet<String> asc =
11503                         mAllowedAssociations.valueAt(i).getAllowedPackageAssociations();
11504                 boolean printedHeader = false;
11505                 for (int j = 0; j < asc.size(); j++) {
11506                     if (dumpPackage == null || pkg.equals(dumpPackage)
11507                             || asc.valueAt(j).equals(dumpPackage)) {
11508                         if (!printed) {
11509                             pw.println("  Allowed associations (by restricted package):");
11510                             printed = true;
11511                             needSep = true;
11512                         }
11513                         if (!printedHeader) {
11514                             pw.print("  * ");
11515                             pw.print(pkg);
11516                             pw.println(":");
11517                             printedHeader = true;
11518                         }
11519                         pw.print("      Allow: ");
11520                         pw.println(asc.valueAt(j));
11521                     }
11522                 }
11523                 if (mAllowedAssociations.valueAt(i).isDebuggable()) {
11524                     pw.println("      (debuggable)");
11525                 }
11526             }
11527         }
11528         if (!printed) {
11529             pw.println("  (No association restrictions)");
11530         }
11531     }
11532 
dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11533     void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11534             int opti, boolean dumpAll, String dumpPackage) {
11535         boolean needSep = false;
11536         boolean onlyHistory = false;
11537         boolean printedAnything = false;
11538 
11539         if ("history".equals(dumpPackage)) {
11540             if (opti < args.length && "-s".equals(args[opti])) {
11541                 dumpAll = false;
11542             }
11543             onlyHistory = true;
11544             dumpPackage = null;
11545         }
11546 
11547         pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
11548         if (!onlyHistory && dumpAll) {
11549             if (mRegisteredReceivers.size() > 0) {
11550                 boolean printed = false;
11551                 Iterator it = mRegisteredReceivers.values().iterator();
11552                 while (it.hasNext()) {
11553                     ReceiverList r = (ReceiverList)it.next();
11554                     if (dumpPackage != null && (r.app == null ||
11555                             !dumpPackage.equals(r.app.info.packageName))) {
11556                         continue;
11557                     }
11558                     if (!printed) {
11559                         pw.println("  Registered Receivers:");
11560                         needSep = true;
11561                         printed = true;
11562                         printedAnything = true;
11563                     }
11564                     pw.print("  * "); pw.println(r);
11565                     r.dump(pw, "    ");
11566                 }
11567             }
11568 
11569             if (mReceiverResolver.dump(pw, needSep ?
11570                     "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
11571                     "    ", dumpPackage, false, false)) {
11572                 needSep = true;
11573                 printedAnything = true;
11574             }
11575         }
11576 
11577         for (BroadcastQueue q : mBroadcastQueues) {
11578             needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
11579             printedAnything |= needSep;
11580         }
11581 
11582         needSep = true;
11583 
11584         if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
11585             for (int user=0; user<mStickyBroadcasts.size(); user++) {
11586                 if (needSep) {
11587                     pw.println();
11588                 }
11589                 needSep = true;
11590                 printedAnything = true;
11591                 pw.print("  Sticky broadcasts for user ");
11592                         pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
11593                 StringBuilder sb = new StringBuilder(128);
11594                 for (Map.Entry<String, ArrayList<Intent>> ent
11595                         : mStickyBroadcasts.valueAt(user).entrySet()) {
11596                     pw.print("  * Sticky action "); pw.print(ent.getKey());
11597                     if (dumpAll) {
11598                         pw.println(":");
11599                         ArrayList<Intent> intents = ent.getValue();
11600                         final int N = intents.size();
11601                         for (int i=0; i<N; i++) {
11602                             sb.setLength(0);
11603                             sb.append("    Intent: ");
11604                             intents.get(i).toShortString(sb, false, true, false, false);
11605                             pw.println(sb.toString());
11606                             Bundle bundle = intents.get(i).getExtras();
11607                             if (bundle != null) {
11608                                 pw.print("      ");
11609                                 pw.println(bundle.toString());
11610                             }
11611                         }
11612                     } else {
11613                         pw.println("");
11614                     }
11615                 }
11616             }
11617         }
11618 
11619         if (!onlyHistory && dumpAll) {
11620             pw.println();
11621             for (BroadcastQueue queue : mBroadcastQueues) {
11622                 pw.println("  mBroadcastsScheduled [" + queue.mQueueName + "]="
11623                         + queue.mBroadcastsScheduled);
11624             }
11625             pw.println("  mHandler:");
11626             mHandler.dump(new PrintWriterPrinter(pw), "    ");
11627             needSep = true;
11628             printedAnything = true;
11629         }
11630 
11631         if (!printedAnything) {
11632             pw.println("  (nothing)");
11633         }
11634     }
11635 
dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11636     void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11637             int opti, boolean dumpAll, String dumpPackage) {
11638         if (mCurBroadcastStats == null) {
11639             return;
11640         }
11641 
11642         pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)");
11643         final long now = SystemClock.elapsedRealtime();
11644         if (mLastBroadcastStats != null) {
11645             pw.print("  Last stats (from ");
11646             TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw);
11647             pw.print(" to ");
11648             TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw);
11649             pw.print(", ");
11650             TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime
11651                     - mLastBroadcastStats.mStartUptime, pw);
11652             pw.println(" uptime):");
11653             if (!mLastBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11654                 pw.println("    (nothing)");
11655             }
11656             pw.println();
11657         }
11658         pw.print("  Current stats (from ");
11659         TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw);
11660         pw.print(" to now, ");
11661         TimeUtils.formatDuration(SystemClock.uptimeMillis()
11662                 - mCurBroadcastStats.mStartUptime, pw);
11663         pw.println(" uptime):");
11664         if (!mCurBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11665             pw.println("    (nothing)");
11666         }
11667     }
11668 
dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)11669     void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11670             int opti, boolean fullCheckin, String dumpPackage) {
11671         if (mCurBroadcastStats == null) {
11672             return;
11673         }
11674 
11675         if (mLastBroadcastStats != null) {
11676             mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11677             if (fullCheckin) {
11678                 mLastBroadcastStats = null;
11679                 return;
11680             }
11681         }
11682         mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11683         if (fullCheckin) {
11684             mCurBroadcastStats = null;
11685         }
11686     }
11687 
dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11688     void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11689             int opti, boolean dumpAll, String dumpPackage) {
11690         boolean needSep;
11691         boolean printedAnything = false;
11692 
11693         ItemMatcher matcher = new ItemMatcher();
11694         matcher.build(args, opti);
11695 
11696         pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
11697 
11698         needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage);
11699         printedAnything |= needSep;
11700 
11701         if (mLaunchingProviders.size() > 0) {
11702             boolean printed = false;
11703             for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
11704                 ContentProviderRecord r = mLaunchingProviders.get(i);
11705                 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
11706                     continue;
11707                 }
11708                 if (!printed) {
11709                     if (needSep) pw.println();
11710                     needSep = true;
11711                     pw.println("  Launching content providers:");
11712                     printed = true;
11713                     printedAnything = true;
11714                 }
11715                 pw.print("  Launching #"); pw.print(i); pw.print(": ");
11716                         pw.println(r);
11717             }
11718         }
11719 
11720         if (!printedAnything) {
11721             pw.println("  (nothing)");
11722         }
11723     }
11724 
11725     @GuardedBy("this")
dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11726     void dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11727             int opti, boolean dumpAll, String dumpPackage) {
11728 
11729         pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)");
11730 
11731         mUgmInternal.dump(pw, dumpAll, dumpPackage);
11732     }
11733 
dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)11734     private static final int dumpProcessList(PrintWriter pw,
11735             ActivityManagerService service, List list,
11736             String prefix, String normalLabel, String persistentLabel,
11737             String dumpPackage) {
11738         int numPers = 0;
11739         final int N = list.size()-1;
11740         for (int i=N; i>=0; i--) {
11741             ProcessRecord r = (ProcessRecord)list.get(i);
11742             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11743                 continue;
11744             }
11745             pw.println(String.format("%s%s #%2d: %s",
11746                     prefix, (r.isPersistent() ? persistentLabel : normalLabel),
11747                     i, r.toString()));
11748             if (r.isPersistent()) {
11749                 numPers++;
11750             }
11751         }
11752         return numPers;
11753     }
11754 
11755     private static final ArrayList<Pair<ProcessRecord, Integer>>
sortProcessOomList(List<ProcessRecord> origList, String dumpPackage)11756         sortProcessOomList(List<ProcessRecord> origList, String dumpPackage) {
11757         ArrayList<Pair<ProcessRecord, Integer>> list
11758                 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
11759         for (int i=0; i<origList.size(); i++) {
11760             ProcessRecord r = origList.get(i);
11761             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11762                 continue;
11763             }
11764             list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
11765         }
11766 
11767         Comparator<Pair<ProcessRecord, Integer>> comparator
11768                 = new Comparator<Pair<ProcessRecord, Integer>>() {
11769             @Override
11770             public int compare(Pair<ProcessRecord, Integer> object1,
11771                     Pair<ProcessRecord, Integer> object2) {
11772                 if (object1.first.setAdj != object2.first.setAdj) {
11773                     return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
11774                 }
11775                 if (object1.first.setProcState != object2.first.setProcState) {
11776                     return object1.first.setProcState > object2.first.setProcState ? -1 : 1;
11777                 }
11778                 if (object1.second.intValue() != object2.second.intValue()) {
11779                     return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
11780                 }
11781                 return 0;
11782             }
11783         };
11784 
11785         Collections.sort(list, comparator);
11786         return list;
11787     }
11788 
writeProcessOomListToProto(ProtoOutputStream proto, long fieldId, ActivityManagerService service, List<ProcessRecord> origList, boolean inclDetails, String dumpPackage)11789     private static final boolean writeProcessOomListToProto(ProtoOutputStream proto, long fieldId,
11790             ActivityManagerService service, List<ProcessRecord> origList,
11791             boolean inclDetails, String dumpPackage) {
11792         ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage);
11793         if (list.isEmpty()) return false;
11794 
11795         final long curUptime = SystemClock.uptimeMillis();
11796 
11797         for (int i = list.size() - 1; i >= 0; i--) {
11798             ProcessRecord r = list.get(i).first;
11799             long token = proto.start(fieldId);
11800             String oomAdj = ProcessList.makeOomAdjString(r.setAdj, true);
11801             proto.write(ProcessOomProto.PERSISTENT, r.isPersistent());
11802             proto.write(ProcessOomProto.NUM, (origList.size()-1)-list.get(i).second);
11803             proto.write(ProcessOomProto.OOM_ADJ, oomAdj);
11804             int schedGroup = ProcessOomProto.SCHED_GROUP_UNKNOWN;
11805             switch (r.setSchedGroup) {
11806                 case ProcessList.SCHED_GROUP_BACKGROUND:
11807                     schedGroup = ProcessOomProto.SCHED_GROUP_BACKGROUND;
11808                     break;
11809                 case ProcessList.SCHED_GROUP_DEFAULT:
11810                     schedGroup = ProcessOomProto.SCHED_GROUP_DEFAULT;
11811                     break;
11812                 case ProcessList.SCHED_GROUP_TOP_APP:
11813                     schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP;
11814                     break;
11815                 case ProcessList.SCHED_GROUP_TOP_APP_BOUND:
11816                     schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP_BOUND;
11817                     break;
11818             }
11819             if (schedGroup != ProcessOomProto.SCHED_GROUP_UNKNOWN) {
11820                 proto.write(ProcessOomProto.SCHED_GROUP, schedGroup);
11821             }
11822             if (r.hasForegroundActivities()) {
11823                 proto.write(ProcessOomProto.ACTIVITIES, true);
11824             } else if (r.hasForegroundServices()) {
11825                 proto.write(ProcessOomProto.SERVICES, true);
11826             }
11827             proto.write(ProcessOomProto.STATE,
11828                     ProcessList.makeProcStateProtoEnum(r.getCurProcState()));
11829             proto.write(ProcessOomProto.TRIM_MEMORY_LEVEL, r.trimMemoryLevel);
11830             r.writeToProto(proto, ProcessOomProto.PROC);
11831             proto.write(ProcessOomProto.ADJ_TYPE, r.adjType);
11832             if (r.adjSource != null || r.adjTarget != null) {
11833                 if (r.adjTarget instanceof  ComponentName) {
11834                     ComponentName cn = (ComponentName) r.adjTarget;
11835                     cn.writeToProto(proto, ProcessOomProto.ADJ_TARGET_COMPONENT_NAME);
11836                 } else if (r.adjTarget != null) {
11837                     proto.write(ProcessOomProto.ADJ_TARGET_OBJECT, r.adjTarget.toString());
11838                 }
11839                 if (r.adjSource instanceof ProcessRecord) {
11840                     ProcessRecord p = (ProcessRecord) r.adjSource;
11841                     p.writeToProto(proto, ProcessOomProto.ADJ_SOURCE_PROC);
11842                 } else if (r.adjSource != null) {
11843                     proto.write(ProcessOomProto.ADJ_SOURCE_OBJECT, r.adjSource.toString());
11844                 }
11845             }
11846             if (inclDetails) {
11847                 long detailToken = proto.start(ProcessOomProto.DETAIL);
11848                 proto.write(ProcessOomProto.Detail.MAX_ADJ, r.maxAdj);
11849                 proto.write(ProcessOomProto.Detail.CUR_RAW_ADJ, r.getCurRawAdj());
11850                 proto.write(ProcessOomProto.Detail.SET_RAW_ADJ, r.setRawAdj);
11851                 proto.write(ProcessOomProto.Detail.CUR_ADJ, r.curAdj);
11852                 proto.write(ProcessOomProto.Detail.SET_ADJ, r.setAdj);
11853                 proto.write(ProcessOomProto.Detail.CURRENT_STATE,
11854                         ProcessList.makeProcStateProtoEnum(r.getCurProcState()));
11855                 proto.write(ProcessOomProto.Detail.SET_STATE,
11856                         ProcessList.makeProcStateProtoEnum(r.setProcState));
11857                 proto.write(ProcessOomProto.Detail.LAST_PSS, DebugUtils.sizeValueToString(
11858                         r.lastPss*1024, new StringBuilder()));
11859                 proto.write(ProcessOomProto.Detail.LAST_SWAP_PSS, DebugUtils.sizeValueToString(
11860                         r.lastSwapPss*1024, new StringBuilder()));
11861                 proto.write(ProcessOomProto.Detail.LAST_CACHED_PSS, DebugUtils.sizeValueToString(
11862                         r.lastCachedPss*1024, new StringBuilder()));
11863                 proto.write(ProcessOomProto.Detail.CACHED, r.cached);
11864                 proto.write(ProcessOomProto.Detail.EMPTY, r.empty);
11865                 proto.write(ProcessOomProto.Detail.HAS_ABOVE_CLIENT, r.hasAboveClient);
11866 
11867                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
11868                     if (r.lastCpuTime != 0) {
11869                         long uptimeSince = curUptime - service.mLastPowerCheckUptime;
11870                         long timeUsed = r.curCpuTime - r.lastCpuTime;
11871                         long cpuTimeToken = proto.start(ProcessOomProto.Detail.SERVICE_RUN_TIME);
11872                         proto.write(ProcessOomProto.Detail.CpuRunTime.OVER_MS, uptimeSince);
11873                         proto.write(ProcessOomProto.Detail.CpuRunTime.USED_MS, timeUsed);
11874                         proto.write(ProcessOomProto.Detail.CpuRunTime.ULTILIZATION,
11875                                 (100.0*timeUsed)/uptimeSince);
11876                         proto.end(cpuTimeToken);
11877                     }
11878                 }
11879                 proto.end(detailToken);
11880             }
11881             proto.end(token);
11882         }
11883 
11884         return true;
11885     }
11886 
dumpProcessOomList(PrintWriter pw, ActivityManagerService service, List<ProcessRecord> origList, String prefix, String normalLabel, String persistentLabel, boolean inclDetails, String dumpPackage)11887     private static final boolean dumpProcessOomList(PrintWriter pw,
11888             ActivityManagerService service, List<ProcessRecord> origList,
11889             String prefix, String normalLabel, String persistentLabel,
11890             boolean inclDetails, String dumpPackage) {
11891 
11892         ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage);
11893         if (list.isEmpty()) return false;
11894 
11895         final long curUptime = SystemClock.uptimeMillis();
11896         final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
11897 
11898         for (int i=list.size()-1; i>=0; i--) {
11899             ProcessRecord r = list.get(i).first;
11900             String oomAdj = ProcessList.makeOomAdjString(r.setAdj, false);
11901             char schedGroup;
11902             switch (r.setSchedGroup) {
11903                 case ProcessList.SCHED_GROUP_BACKGROUND:
11904                     schedGroup = 'B';
11905                     break;
11906                 case ProcessList.SCHED_GROUP_DEFAULT:
11907                     schedGroup = 'F';
11908                     break;
11909                 case ProcessList.SCHED_GROUP_TOP_APP:
11910                     schedGroup = 'T';
11911                     break;
11912                 case ProcessList.SCHED_GROUP_RESTRICTED:
11913                     schedGroup = 'R';
11914                     break;
11915                 default:
11916                     schedGroup = '?';
11917                     break;
11918             }
11919             char foreground;
11920             if (r.hasForegroundActivities()) {
11921                 foreground = 'A';
11922             } else if (r.hasForegroundServices()) {
11923                 foreground = 'S';
11924             } else {
11925                 foreground = ' ';
11926             }
11927             String procState = ProcessList.makeProcStateString(r.getCurProcState());
11928             pw.print(prefix);
11929             pw.print(r.isPersistent() ? persistentLabel : normalLabel);
11930             pw.print(" #");
11931             int num = (origList.size()-1)-list.get(i).second;
11932             if (num < 10) pw.print(' ');
11933             pw.print(num);
11934             pw.print(": ");
11935             pw.print(oomAdj);
11936             pw.print(' ');
11937             pw.print(schedGroup);
11938             pw.print('/');
11939             pw.print(foreground);
11940             pw.print('/');
11941             pw.print(procState);
11942             pw.print(" trm:");
11943             if (r.trimMemoryLevel < 10) pw.print(' ');
11944             pw.print(r.trimMemoryLevel);
11945             pw.print(' ');
11946             pw.print(r.toShortString());
11947             pw.print(" (");
11948             pw.print(r.adjType);
11949             pw.println(')');
11950             if (r.adjSource != null || r.adjTarget != null) {
11951                 pw.print(prefix);
11952                 pw.print("    ");
11953                 if (r.adjTarget instanceof ComponentName) {
11954                     pw.print(((ComponentName)r.adjTarget).flattenToShortString());
11955                 } else if (r.adjTarget != null) {
11956                     pw.print(r.adjTarget.toString());
11957                 } else {
11958                     pw.print("{null}");
11959                 }
11960                 pw.print("<=");
11961                 if (r.adjSource instanceof ProcessRecord) {
11962                     pw.print("Proc{");
11963                     pw.print(((ProcessRecord)r.adjSource).toShortString());
11964                     pw.println("}");
11965                 } else if (r.adjSource != null) {
11966                     pw.println(r.adjSource.toString());
11967                 } else {
11968                     pw.println("{null}");
11969                 }
11970             }
11971             if (inclDetails) {
11972                 pw.print(prefix);
11973                 pw.print("    ");
11974                 pw.print("oom: max="); pw.print(r.maxAdj);
11975                 pw.print(" curRaw="); pw.print(r.getCurRawAdj());
11976                 pw.print(" setRaw="); pw.print(r.setRawAdj);
11977                 pw.print(" cur="); pw.print(r.curAdj);
11978                 pw.print(" set="); pw.println(r.setAdj);
11979                 pw.print(prefix);
11980                 pw.print("    ");
11981                 pw.print("state: cur="); pw.print(
11982                         ProcessList.makeProcStateString(r.getCurProcState()));
11983                 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState));
11984                 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, r.lastPss*1024);
11985                 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, r.lastSwapPss*1024);
11986                 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, r.lastCachedPss*1024);
11987                 pw.println();
11988                 pw.print(prefix);
11989                 pw.print("    ");
11990                 pw.print("cached="); pw.print(r.cached);
11991                 pw.print(" empty="); pw.print(r.empty);
11992                 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
11993 
11994                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
11995                     if (r.lastCpuTime != 0) {
11996                         long timeUsed = r.curCpuTime - r.lastCpuTime;
11997                         pw.print(prefix);
11998                         pw.print("    ");
11999                         pw.print("run cpu over ");
12000                         TimeUtils.formatDuration(uptimeSince, pw);
12001                         pw.print(" used ");
12002                         TimeUtils.formatDuration(timeUsed, pw);
12003                         pw.print(" (");
12004                         pw.print((timeUsed*100)/uptimeSince);
12005                         pw.println("%)");
12006                     }
12007                 }
12008             }
12009         }
12010         return true;
12011     }
12012 
collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)12013     ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs,
12014             String[] args) {
12015         synchronized (this) {
12016             return mProcessList.collectProcessesLocked(start, allPkgs, args);
12017         }
12018     }
12019 
dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)12020     final void dumpGraphicsHardwareUsage(FileDescriptor fd,
12021             PrintWriter pw, String[] args) {
12022         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
12023         if (procs == null) {
12024             pw.println("No process found for: " + args[0]);
12025             return;
12026         }
12027 
12028         long uptime = SystemClock.uptimeMillis();
12029         long realtime = SystemClock.elapsedRealtime();
12030         pw.println("Applications Graphics Acceleration Info:");
12031         pw.println("Uptime: " + uptime + " Realtime: " + realtime);
12032 
12033         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12034             ProcessRecord r = procs.get(i);
12035             if (r.thread != null) {
12036                 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
12037                 pw.flush();
12038                 try {
12039                     TransferPipe tp = new TransferPipe();
12040                     try {
12041                         r.thread.dumpGfxInfo(tp.getWriteFd(), args);
12042                         tp.go(fd);
12043                     } finally {
12044                         tp.kill();
12045                     }
12046                 } catch (IOException e) {
12047                     pw.println("Failure while dumping the app: " + r);
12048                     pw.flush();
12049                 } catch (RemoteException e) {
12050                     pw.println("Got a RemoteException while dumping the app " + r);
12051                     pw.flush();
12052                 }
12053             }
12054         }
12055     }
12056 
dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)12057     final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
12058         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
12059         if (procs == null) {
12060             pw.println("No process found for: " + args[0]);
12061             return;
12062         }
12063 
12064         pw.println("Applications Database Info:");
12065 
12066         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12067             ProcessRecord r = procs.get(i);
12068             if (r.thread != null) {
12069                 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
12070                 pw.flush();
12071                 try {
12072                     TransferPipe tp = new TransferPipe();
12073                     try {
12074                         r.thread.dumpDbInfo(tp.getWriteFd(), args);
12075                         tp.go(fd);
12076                     } finally {
12077                         tp.kill();
12078                     }
12079                 } catch (IOException e) {
12080                     pw.println("Failure while dumping the app: " + r);
12081                     pw.flush();
12082                 } catch (RemoteException e) {
12083                     pw.println("Got a RemoteException while dumping the app " + r);
12084                     pw.flush();
12085                 }
12086             }
12087         }
12088     }
12089 
12090     final static class MemItem {
12091         final boolean isProc;
12092         final String label;
12093         final String shortLabel;
12094         final long pss;
12095         final long swapPss;
12096         final int id;
12097         final boolean hasActivities;
12098         ArrayList<MemItem> subitems;
12099 
MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id, boolean _hasActivities)12100         public MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id,
12101                 boolean _hasActivities) {
12102             isProc = true;
12103             label = _label;
12104             shortLabel = _shortLabel;
12105             pss = _pss;
12106             swapPss = _swapPss;
12107             id = _id;
12108             hasActivities = _hasActivities;
12109         }
12110 
MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id)12111         public MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id) {
12112             isProc = false;
12113             label = _label;
12114             shortLabel = _shortLabel;
12115             pss = _pss;
12116             swapPss = _swapPss;
12117             id = _id;
12118             hasActivities = false;
12119         }
12120     }
12121 
sortMemItems(List<MemItem> items)12122     private static void sortMemItems(List<MemItem> items) {
12123         Collections.sort(items, new Comparator<MemItem>() {
12124             @Override
12125             public int compare(MemItem lhs, MemItem rhs) {
12126                 if (lhs.pss < rhs.pss) {
12127                     return 1;
12128                 } else if (lhs.pss > rhs.pss) {
12129                     return -1;
12130                 }
12131                 return 0;
12132             }
12133         });
12134     }
12135 
dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpSwapPss)12136     static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
12137             ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpSwapPss) {
12138         if (sort && !isCompact) {
12139             sortMemItems(items);
12140         }
12141 
12142         for (int i=0; i<items.size(); i++) {
12143             MemItem mi = items.get(i);
12144             if (!isCompact) {
12145                 if (dumpSwapPss) {
12146                     pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss),
12147                             mi.label, stringifyKBSize(mi.swapPss));
12148                 } else {
12149                     pw.printf("%s%s: %s\n", prefix, stringifyKBSize(mi.pss), mi.label);
12150                 }
12151             } else if (mi.isProc) {
12152                 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
12153                 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); pw.print(",");
12154                 pw.print(dumpSwapPss ? mi.swapPss : "N/A");
12155                 pw.println(mi.hasActivities ? ",a" : ",e");
12156             } else {
12157                 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
12158                 pw.print(mi.pss); pw.print(","); pw.println(dumpSwapPss ? mi.swapPss : "N/A");
12159             }
12160             if (mi.subitems != null) {
12161                 dumpMemItems(pw, prefix + "    ", mi.shortLabel, mi.subitems,
12162                         true, isCompact, dumpSwapPss);
12163             }
12164         }
12165     }
12166 
dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpSwapPss)12167     static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag,
12168             ArrayList<MemItem> items, boolean sort, boolean dumpSwapPss) {
12169         if (sort) {
12170             sortMemItems(items);
12171         }
12172 
12173         for (int i=0; i<items.size(); i++) {
12174             MemItem mi = items.get(i);
12175             final long token = proto.start(fieldId);
12176 
12177             proto.write(MemInfoDumpProto.MemItem.TAG, tag);
12178             proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel);
12179             proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc);
12180             proto.write(MemInfoDumpProto.MemItem.ID, mi.id);
12181             proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities);
12182             proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss);
12183             if (dumpSwapPss) {
12184                 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss);
12185             }
12186             if (mi.subitems != null) {
12187                 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems,
12188                         true, dumpSwapPss);
12189             }
12190             proto.end(token);
12191         }
12192     }
12193 
12194     // These are in KB.
12195     static final long[] DUMP_MEM_BUCKETS = new long[] {
12196         5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
12197         120*1024, 160*1024, 200*1024,
12198         250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
12199         1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
12200     };
12201 
appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)12202     static final void appendMemBucket(StringBuilder out, long memKB, String label,
12203             boolean stackLike) {
12204         int start = label.lastIndexOf('.');
12205         if (start >= 0) start++;
12206         else start = 0;
12207         int end = label.length();
12208         for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
12209             if (DUMP_MEM_BUCKETS[i] >= memKB) {
12210                 long bucket = DUMP_MEM_BUCKETS[i]/1024;
12211                 out.append(bucket);
12212                 out.append(stackLike ? "MB." : "MB ");
12213                 out.append(label, start, end);
12214                 return;
12215             }
12216         }
12217         out.append(memKB/1024);
12218         out.append(stackLike ? "MB." : "MB ");
12219         out.append(label, start, end);
12220     }
12221 
12222     static final int[] DUMP_MEM_OOM_ADJ = new int[] {
12223             ProcessList.NATIVE_ADJ,
12224             ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ,
12225             ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ,
12226             ProcessList.VISIBLE_APP_ADJ,
12227             ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ,
12228             ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
12229             ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
12230             ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ
12231     };
12232     static final String[] DUMP_MEM_OOM_LABEL = new String[] {
12233             "Native",
12234             "System", "Persistent", "Persistent Service", "Foreground",
12235             "Visible", "Perceptible", "Perceptible Low",
12236             "Heavy Weight", "Backup",
12237             "A Services", "Home",
12238             "Previous", "B Services", "Cached"
12239     };
12240     static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
12241             "native",
12242             "sys", "pers", "persvc", "fore",
12243             "vis", "percept", "perceptl",
12244             "heavy", "backup",
12245             "servicea", "home",
12246             "prev", "serviceb", "cached"
12247     };
12248 
dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)12249     private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
12250             long realtime, boolean isCheckinRequest, boolean isCompact) {
12251         if (isCompact) {
12252             pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION);
12253         }
12254         if (isCheckinRequest || isCompact) {
12255             // short checkin version
12256             pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
12257         } else {
12258             pw.println("Applications Memory Usage (in Kilobytes):");
12259             pw.println("Uptime: " + uptime + " Realtime: " + realtime);
12260         }
12261     }
12262 
12263     private static final int KSM_SHARED = 0;
12264     private static final int KSM_SHARING = 1;
12265     private static final int KSM_UNSHARED = 2;
12266     private static final int KSM_VOLATILE = 3;
12267 
getKsmInfo()12268     private final long[] getKsmInfo() {
12269         long[] longOut = new long[4];
12270         final int[] SINGLE_LONG_FORMAT = new int[] {
12271             PROC_SPACE_TERM| PROC_OUT_LONG
12272         };
12273         long[] longTmp = new long[1];
12274         readProcFile("/sys/kernel/mm/ksm/pages_shared",
12275                 SINGLE_LONG_FORMAT, null, longTmp, null);
12276         longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12277         longTmp[0] = 0;
12278         readProcFile("/sys/kernel/mm/ksm/pages_sharing",
12279                 SINGLE_LONG_FORMAT, null, longTmp, null);
12280         longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12281         longTmp[0] = 0;
12282         readProcFile("/sys/kernel/mm/ksm/pages_unshared",
12283                 SINGLE_LONG_FORMAT, null, longTmp, null);
12284         longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12285         longTmp[0] = 0;
12286         readProcFile("/sys/kernel/mm/ksm/pages_volatile",
12287                 SINGLE_LONG_FORMAT, null, longTmp, null);
12288         longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12289         return longOut;
12290     }
12291 
stringifySize(long size, int order)12292     private static String stringifySize(long size, int order) {
12293         Locale locale = Locale.US;
12294         switch (order) {
12295             case 1:
12296                 return String.format(locale, "%,13d", size);
12297             case 1024:
12298                 return String.format(locale, "%,9dK", size / 1024);
12299             case 1024 * 1024:
12300                 return String.format(locale, "%,5dM", size / 1024 / 1024);
12301             case 1024 * 1024 * 1024:
12302                 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024);
12303             default:
12304                 throw new IllegalArgumentException("Invalid size order");
12305         }
12306     }
12307 
stringifyKBSize(long size)12308     private static String stringifyKBSize(long size) {
12309         return stringifySize(size * 1024, 1024);
12310     }
12311 
12312     // Update this version number if you change the 'compact' format.
12313     private static final int MEMINFO_COMPACT_VERSION = 1;
12314 
12315     private static class MemoryUsageDumpOptions {
12316         boolean dumpDetails;
12317         boolean dumpFullDetails;
12318         boolean dumpDalvik;
12319         boolean dumpSummaryOnly;
12320         boolean dumpUnreachable;
12321         boolean oomOnly;
12322         boolean isCompact;
12323         boolean localOnly;
12324         boolean packages;
12325         boolean isCheckinRequest;
12326         boolean dumpSwapPss;
12327         boolean dumpProto;
12328     }
12329 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)12330     final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
12331             String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) {
12332         MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions();
12333         opts.dumpDetails = false;
12334         opts.dumpFullDetails = false;
12335         opts.dumpDalvik = false;
12336         opts.dumpSummaryOnly = false;
12337         opts.dumpUnreachable = false;
12338         opts.oomOnly = false;
12339         opts.isCompact = false;
12340         opts.localOnly = false;
12341         opts.packages = false;
12342         opts.isCheckinRequest = false;
12343         opts.dumpSwapPss = false;
12344         opts.dumpProto = asProto;
12345 
12346         int opti = 0;
12347         while (opti < args.length) {
12348             String opt = args[opti];
12349             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12350                 break;
12351             }
12352             opti++;
12353             if ("-a".equals(opt)) {
12354                 opts.dumpDetails = true;
12355                 opts.dumpFullDetails = true;
12356                 opts.dumpDalvik = true;
12357                 opts.dumpSwapPss = true;
12358             } else if ("-d".equals(opt)) {
12359                 opts.dumpDalvik = true;
12360             } else if ("-c".equals(opt)) {
12361                 opts.isCompact = true;
12362             } else if ("-s".equals(opt)) {
12363                 opts.dumpDetails = true;
12364                 opts.dumpSummaryOnly = true;
12365             } else if ("-S".equals(opt)) {
12366                 opts.dumpSwapPss = true;
12367             } else if ("--unreachable".equals(opt)) {
12368                 opts.dumpUnreachable = true;
12369             } else if ("--oom".equals(opt)) {
12370                 opts.oomOnly = true;
12371             } else if ("--local".equals(opt)) {
12372                 opts.localOnly = true;
12373             } else if ("--package".equals(opt)) {
12374                 opts.packages = true;
12375             } else if ("--checkin".equals(opt)) {
12376                 opts.isCheckinRequest = true;
12377             } else if ("--proto".equals(opt)) {
12378                 opts.dumpProto = true;
12379 
12380             } else if ("-h".equals(opt)) {
12381                 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
12382                 pw.println("  -a: include all available information for each process.");
12383                 pw.println("  -d: include dalvik details.");
12384                 pw.println("  -c: dump in a compact machine-parseable representation.");
12385                 pw.println("  -s: dump only summary of application memory usage.");
12386                 pw.println("  -S: dump also SwapPss.");
12387                 pw.println("  --oom: only show processes organized by oom adj.");
12388                 pw.println("  --local: only collect details locally, don't call process.");
12389                 pw.println("  --package: interpret process arg as package, dumping all");
12390                 pw.println("             processes that have loaded that package.");
12391                 pw.println("  --checkin: dump data for a checkin");
12392                 pw.println("  --proto: dump data to proto");
12393                 pw.println("If [process] is specified it can be the name or ");
12394                 pw.println("pid of a specific process to dump.");
12395                 return;
12396             } else {
12397                 pw.println("Unknown argument: " + opt + "; use -h for help");
12398             }
12399         }
12400 
12401         String[] innerArgs = new String[args.length-opti];
12402         System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
12403 
12404         ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args);
12405         if (opts.dumpProto) {
12406             dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs);
12407         } else {
12408             dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw);
12409         }
12410     }
12411 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)12412     private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
12413             MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief,
12414             ArrayList<ProcessRecord> procs, PrintWriter categoryPw) {
12415         long uptime = SystemClock.uptimeMillis();
12416         long realtime = SystemClock.elapsedRealtime();
12417         final long[] tmpLong = new long[1];
12418 
12419         if (procs == null) {
12420             // No Java processes.  Maybe they want to print a native process.
12421             String proc = "N/A";
12422             if (innerArgs.length > 0) {
12423                 proc = innerArgs[0];
12424                 if (proc.charAt(0) != '-') {
12425                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
12426                             = new ArrayList<ProcessCpuTracker.Stats>();
12427                     updateCpuStatsNow();
12428                     int findPid = -1;
12429                     try {
12430                         findPid = Integer.parseInt(innerArgs[0]);
12431                     } catch (NumberFormatException e) {
12432                     }
12433                     synchronized (mProcessCpuTracker) {
12434                         final int N = mProcessCpuTracker.countStats();
12435                         for (int i=0; i<N; i++) {
12436                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12437                             if (st.pid == findPid || (st.baseName != null
12438                                     && st.baseName.equals(innerArgs[0]))) {
12439                                 nativeProcs.add(st);
12440                             }
12441                         }
12442                     }
12443                     if (nativeProcs.size() > 0) {
12444                         dumpApplicationMemoryUsageHeader(pw, uptime, realtime,
12445                                 opts.isCheckinRequest, opts.isCompact);
12446                         Debug.MemoryInfo mi = null;
12447                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12448                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12449                             final int pid = r.pid;
12450                             if (!opts.isCheckinRequest && opts.dumpDetails) {
12451                                 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **");
12452                             }
12453                             if (mi == null) {
12454                                 mi = new Debug.MemoryInfo();
12455                             }
12456                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12457                                 Debug.getMemoryInfo(pid, mi);
12458                             } else {
12459                                 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null);
12460                                 mi.dalvikPrivateDirty = (int)tmpLong[0];
12461                             }
12462                             ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest,
12463                                     opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
12464                                     pid, r.baseName, 0, 0, 0, 0, 0, 0);
12465                             if (opts.isCheckinRequest) {
12466                                 pw.println();
12467                             }
12468                         }
12469                         return;
12470                     }
12471                 }
12472             }
12473             pw.println("No process found for: " + proc);
12474             return;
12475         }
12476 
12477         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
12478             opts.dumpDetails = true;
12479         }
12480 
12481         dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact);
12482 
12483         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
12484         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
12485         long nativePss = 0;
12486         long nativeSwapPss = 0;
12487         long dalvikPss = 0;
12488         long dalvikSwapPss = 0;
12489         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12490                 EmptyArray.LONG;
12491         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12492                 EmptyArray.LONG;
12493         long otherPss = 0;
12494         long otherSwapPss = 0;
12495         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12496         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12497 
12498         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
12499         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
12500         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
12501                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
12502 
12503         long totalPss = 0;
12504         long totalSwapPss = 0;
12505         long cachedPss = 0;
12506         long cachedSwapPss = 0;
12507         boolean hasSwapPss = false;
12508 
12509         Debug.MemoryInfo mi = null;
12510         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12511             final ProcessRecord r = procs.get(i);
12512             final IApplicationThread thread;
12513             final int pid;
12514             final int oomAdj;
12515             final boolean hasActivities;
12516             synchronized (this) {
12517                 thread = r.thread;
12518                 pid = r.pid;
12519                 oomAdj = r.getSetAdjWithServices();
12520                 hasActivities = r.hasActivities();
12521             }
12522             if (thread != null) {
12523                 if (!opts.isCheckinRequest && opts.dumpDetails) {
12524                     pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
12525                 }
12526                 if (mi == null) {
12527                     mi = new Debug.MemoryInfo();
12528                 }
12529                 final int reportType;
12530                 final long startTime;
12531                 final long endTime;
12532                 if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12533                     reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
12534                     startTime = SystemClock.currentThreadTimeMillis();
12535                     Debug.getMemoryInfo(pid, mi);
12536                     endTime = SystemClock.currentThreadTimeMillis();
12537                     hasSwapPss = mi.hasSwappedOutPss;
12538                 } else {
12539                     reportType = ProcessStats.ADD_PSS_EXTERNAL;
12540                     startTime = SystemClock.currentThreadTimeMillis();
12541                     mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null);
12542                     endTime = SystemClock.currentThreadTimeMillis();
12543                     mi.dalvikPrivateDirty = (int)tmpLong[0];
12544                 }
12545                 if (opts.dumpDetails) {
12546                     if (opts.localOnly) {
12547                         ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails,
12548                                 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
12549                         if (opts.isCheckinRequest) {
12550                             pw.println();
12551                         }
12552                     } else {
12553                         pw.flush();
12554                         try {
12555                             TransferPipe tp = new TransferPipe();
12556                             try {
12557                                 thread.dumpMemInfo(tp.getWriteFd(),
12558                                         mi, opts.isCheckinRequest, opts.dumpFullDetails,
12559                                         opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs);
12560                                 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000);
12561                             } finally {
12562                                 tp.kill();
12563                             }
12564                         } catch (IOException e) {
12565                             if (!opts.isCheckinRequest) {
12566                                 pw.println("Got IoException! " + e);
12567                                 pw.flush();
12568                             }
12569                         } catch (RemoteException e) {
12570                             if (!opts.isCheckinRequest) {
12571                                 pw.println("Got RemoteException! " + e);
12572                                 pw.flush();
12573                             }
12574                         }
12575                     }
12576                 }
12577 
12578                 final long myTotalPss = mi.getTotalPss();
12579                 final long myTotalUss = mi.getTotalUss();
12580                 final long myTotalRss = mi.getTotalRss();
12581                 final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12582 
12583                 synchronized (this) {
12584                     if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
12585                         // Record this for posterity if the process has been stable.
12586                         r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true,
12587                                 reportType, endTime-startTime, r.pkgList.mPkgList);
12588                         for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) {
12589                             ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg);
12590                             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
12591                                     r.info.uid,
12592                                     holder.state.getName(),
12593                                     holder.state.getPackage(),
12594                                     myTotalPss, myTotalUss, myTotalRss, reportType,
12595                                     endTime-startTime,
12596                                     holder.appVersion);
12597                         }
12598                     }
12599                 }
12600 
12601                 if (!opts.isCheckinRequest && mi != null) {
12602                     totalPss += myTotalPss;
12603                     totalSwapPss += myTotalSwapPss;
12604                     MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
12605                             (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
12606                             myTotalSwapPss, pid, hasActivities);
12607                     procMems.add(pssItem);
12608                     procMemsMap.put(pid, pssItem);
12609 
12610                     nativePss += mi.nativePss;
12611                     nativeSwapPss += mi.nativeSwappedOutPss;
12612                     dalvikPss += mi.dalvikPss;
12613                     dalvikSwapPss += mi.dalvikSwappedOutPss;
12614                     for (int j=0; j<dalvikSubitemPss.length; j++) {
12615                         dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12616                         dalvikSubitemSwapPss[j] +=
12617                                 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12618                     }
12619                     otherPss += mi.otherPss;
12620                     otherSwapPss += mi.otherSwappedOutPss;
12621                     for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12622                         long mem = mi.getOtherPss(j);
12623                         miscPss[j] += mem;
12624                         otherPss -= mem;
12625                         mem = mi.getOtherSwappedOutPss(j);
12626                         miscSwapPss[j] += mem;
12627                         otherSwapPss -= mem;
12628                     }
12629 
12630                     if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
12631                         cachedPss += myTotalPss;
12632                         cachedSwapPss += myTotalSwapPss;
12633                     }
12634 
12635                     for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
12636                         if (oomIndex == (oomPss.length - 1)
12637                                 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
12638                                         && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
12639                             oomPss[oomIndex] += myTotalPss;
12640                             oomSwapPss[oomIndex] += myTotalSwapPss;
12641                             if (oomProcs[oomIndex] == null) {
12642                                 oomProcs[oomIndex] = new ArrayList<MemItem>();
12643                             }
12644                             oomProcs[oomIndex].add(pssItem);
12645                             break;
12646                         }
12647                     }
12648                 }
12649             }
12650         }
12651 
12652         long nativeProcTotalPss = 0;
12653 
12654         if (!opts.isCheckinRequest && procs.size() > 1 && !opts.packages) {
12655             // If we are showing aggregations, also look for native processes to
12656             // include so that our aggregations are more accurate.
12657             updateCpuStatsNow();
12658             mi = null;
12659             synchronized (mProcessCpuTracker) {
12660                 final int N = mProcessCpuTracker.countStats();
12661                 for (int i=0; i<N; i++) {
12662                     ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12663                     if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
12664                         if (mi == null) {
12665                             mi = new Debug.MemoryInfo();
12666                         }
12667                         if (!brief && !opts.oomOnly) {
12668                             Debug.getMemoryInfo(st.pid, mi);
12669                         } else {
12670                             mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null);
12671                             mi.nativePrivateDirty = (int)tmpLong[0];
12672                         }
12673 
12674                         final long myTotalPss = mi.getTotalPss();
12675                         final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12676                         totalPss += myTotalPss;
12677                         totalSwapPss += myTotalSwapPss;
12678                         nativeProcTotalPss += myTotalPss;
12679 
12680                         MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
12681                                 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false);
12682                         procMems.add(pssItem);
12683 
12684                         nativePss += mi.nativePss;
12685                         nativeSwapPss += mi.nativeSwappedOutPss;
12686                         dalvikPss += mi.dalvikPss;
12687                         dalvikSwapPss += mi.dalvikSwappedOutPss;
12688                         for (int j=0; j<dalvikSubitemPss.length; j++) {
12689                             dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12690                             dalvikSubitemSwapPss[j] +=
12691                                     mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12692                         }
12693                         otherPss += mi.otherPss;
12694                         otherSwapPss += mi.otherSwappedOutPss;
12695                         for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12696                             long mem = mi.getOtherPss(j);
12697                             miscPss[j] += mem;
12698                             otherPss -= mem;
12699                             mem = mi.getOtherSwappedOutPss(j);
12700                             miscSwapPss[j] += mem;
12701                             otherSwapPss -= mem;
12702                         }
12703                         oomPss[0] += myTotalPss;
12704                         oomSwapPss[0] += myTotalSwapPss;
12705                         if (oomProcs[0] == null) {
12706                             oomProcs[0] = new ArrayList<MemItem>();
12707                         }
12708                         oomProcs[0].add(pssItem);
12709                     }
12710                 }
12711             }
12712 
12713             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
12714 
12715             catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1));
12716             final int dalvikId = -2;
12717             catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikId));
12718             catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3));
12719             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12720                 String label = Debug.MemoryInfo.getOtherLabel(j);
12721                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j));
12722             }
12723             if (dalvikSubitemPss.length > 0) {
12724                 // Add dalvik subitems.
12725                 for (MemItem memItem : catMems) {
12726                     int memItemStart = 0, memItemEnd = 0;
12727                     if (memItem.id == dalvikId) {
12728                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
12729                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
12730                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
12731                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
12732                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
12733                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
12734                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
12735                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
12736                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
12737                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
12738                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
12739                     } else {
12740                         continue;  // No subitems, continue.
12741                     }
12742                     memItem.subitems = new ArrayList<MemItem>();
12743                     for (int j=memItemStart; j<=memItemEnd; j++) {
12744                         final String name = Debug.MemoryInfo.getOtherLabel(
12745                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12746                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
12747                                 dalvikSubitemSwapPss[j], j));
12748                     }
12749                 }
12750             }
12751 
12752             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
12753             for (int j=0; j<oomPss.length; j++) {
12754                 if (oomPss[j] != 0) {
12755                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
12756                             : DUMP_MEM_OOM_LABEL[j];
12757                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j],
12758                             DUMP_MEM_OOM_ADJ[j]);
12759                     item.subitems = oomProcs[j];
12760                     oomMems.add(item);
12761                 }
12762             }
12763 
12764             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0;
12765             if (!brief && !opts.oomOnly && !opts.isCompact) {
12766                 pw.println();
12767                 pw.println("Total PSS by process:");
12768                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, opts.dumpSwapPss);
12769                 pw.println();
12770             }
12771             if (!opts.isCompact) {
12772                 pw.println("Total PSS by OOM adjustment:");
12773             }
12774             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, opts.dumpSwapPss);
12775             if (!brief && !opts.oomOnly) {
12776                 PrintWriter out = categoryPw != null ? categoryPw : pw;
12777                 if (!opts.isCompact) {
12778                     out.println();
12779                     out.println("Total PSS by category:");
12780                 }
12781                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, opts.dumpSwapPss);
12782             }
12783             if (!opts.isCompact) {
12784                 pw.println();
12785             }
12786             MemInfoReader memInfo = new MemInfoReader();
12787             memInfo.readMemInfo();
12788             if (nativeProcTotalPss > 0) {
12789                 synchronized (this) {
12790                     final long cachedKb = memInfo.getCachedSizeKb();
12791                     final long freeKb = memInfo.getFreeSizeKb();
12792                     final long zramKb = memInfo.getZramTotalSizeKb();
12793                     final long kernelKb = memInfo.getKernelUsedSizeKb();
12794                     EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
12795                             kernelKb*1024, nativeProcTotalPss*1024);
12796                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
12797                             nativeProcTotalPss);
12798                 }
12799             }
12800             if (!brief) {
12801                 if (!opts.isCompact) {
12802                     pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
12803                     pw.print(" (status ");
12804                     switch (mLastMemoryLevel) {
12805                         case ProcessStats.ADJ_MEM_FACTOR_NORMAL:
12806                             pw.println("normal)");
12807                             break;
12808                         case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
12809                             pw.println("moderate)");
12810                             break;
12811                         case ProcessStats.ADJ_MEM_FACTOR_LOW:
12812                             pw.println("low)");
12813                             break;
12814                         case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
12815                             pw.println("critical)");
12816                             break;
12817                         default:
12818                             pw.print(mLastMemoryLevel);
12819                             pw.println(")");
12820                             break;
12821                     }
12822                     pw.print(" Free RAM: ");
12823                     pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
12824                             + memInfo.getFreeSizeKb()));
12825                     pw.print(" (");
12826                     pw.print(stringifyKBSize(cachedPss));
12827                     pw.print(" cached pss + ");
12828                     pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
12829                     pw.print(" cached kernel + ");
12830                     pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
12831                     pw.println(" free)");
12832                 } else {
12833                     pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
12834                     pw.print(cachedPss + memInfo.getCachedSizeKb()
12835                             + memInfo.getFreeSizeKb()); pw.print(",");
12836                     pw.println(totalPss - cachedPss);
12837                 }
12838             }
12839             long kernelUsed = memInfo.getKernelUsedSizeKb();
12840             final long ionHeap = Debug.getIonHeapsSizeKb();
12841             if (ionHeap > 0) {
12842                 final long ionMapped = Debug.getIonMappedSizeKb();
12843                 final long ionUnmapped = ionHeap - ionMapped;
12844                 final long ionPool = Debug.getIonPoolsSizeKb();
12845                 pw.print("      ION: ");
12846                         pw.print(stringifyKBSize(ionHeap + ionPool));
12847                         pw.print(" (");
12848                         pw.print(stringifyKBSize(ionMapped));
12849                         pw.print(" mapped + ");
12850                         pw.print(stringifyKBSize(ionUnmapped));
12851                         pw.print(" unmapped + ");
12852                         pw.print(stringifyKBSize(ionPool));
12853                         pw.println(" pools)");
12854                 // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
12855                 // set on ION VMAs, therefore consider the entire ION heap as used kernel memory
12856                 kernelUsed += ionHeap;
12857             }
12858             final long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss)
12859                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
12860                     - kernelUsed - memInfo.getZramTotalSizeKb();
12861             if (!opts.isCompact) {
12862                 pw.print(" Used RAM: "); pw.print(stringifyKBSize(totalPss - cachedPss
12863                         + kernelUsed)); pw.print(" (");
12864                 pw.print(stringifyKBSize(totalPss - cachedPss)); pw.print(" used pss + ");
12865                 pw.print(stringifyKBSize(kernelUsed)); pw.print(" kernel)\n");
12866                 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM));
12867             } else {
12868                 pw.print("lostram,"); pw.println(lostRAM);
12869             }
12870             if (!brief) {
12871                 if (memInfo.getZramTotalSizeKb() != 0) {
12872                     if (!opts.isCompact) {
12873                         pw.print("     ZRAM: ");
12874                         pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
12875                                 pw.print(" physical used for ");
12876                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()
12877                                         - memInfo.getSwapFreeSizeKb()));
12878                                 pw.print(" in swap (");
12879                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
12880                                 pw.println(" total swap)");
12881                     } else {
12882                         pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
12883                                 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
12884                                 pw.println(memInfo.getSwapFreeSizeKb());
12885                     }
12886                 }
12887                 final long[] ksm = getKsmInfo();
12888                 if (!opts.isCompact) {
12889                     if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
12890                             || ksm[KSM_VOLATILE] != 0) {
12891                         pw.print("      KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING]));
12892                                 pw.print(" saved from shared ");
12893                                 pw.print(stringifyKBSize(ksm[KSM_SHARED]));
12894                         pw.print("           "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
12895                                 pw.print(" unshared; ");
12896                                 pw.print(stringifyKBSize(
12897                                              ksm[KSM_VOLATILE])); pw.println(" volatile");
12898                     }
12899                     pw.print("   Tuning: ");
12900                     pw.print(ActivityManager.staticGetMemoryClass());
12901                     pw.print(" (large ");
12902                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12903                     pw.print("), oom ");
12904                     pw.print(stringifySize(
12905                                 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
12906                     pw.print(", restore limit ");
12907                     pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
12908                     if (ActivityManager.isLowRamDeviceStatic()) {
12909                         pw.print(" (low-ram)");
12910                     }
12911                     if (ActivityManager.isHighEndGfx()) {
12912                         pw.print(" (high-end-gfx)");
12913                     }
12914                     pw.println();
12915                 } else {
12916                     pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(",");
12917                     pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]);
12918                     pw.print(","); pw.println(ksm[KSM_VOLATILE]);
12919                     pw.print("tuning,");
12920                     pw.print(ActivityManager.staticGetMemoryClass());
12921                     pw.print(',');
12922                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12923                     pw.print(',');
12924                     pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
12925                     if (ActivityManager.isLowRamDeviceStatic()) {
12926                         pw.print(",low-ram");
12927                     }
12928                     if (ActivityManager.isHighEndGfx()) {
12929                         pw.print(",high-end-gfx");
12930                     }
12931                     pw.println();
12932                 }
12933             }
12934         }
12935     }
12936 
dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)12937     private final void dumpApplicationMemoryUsage(FileDescriptor fd,
12938             MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief,
12939             ArrayList<ProcessRecord> procs) {
12940         final long uptimeMs = SystemClock.uptimeMillis();
12941         final long realtimeMs = SystemClock.elapsedRealtime();
12942         final long[] tmpLong = new long[1];
12943 
12944         if (procs == null) {
12945             // No Java processes.  Maybe they want to print a native process.
12946             String proc = "N/A";
12947             if (innerArgs.length > 0) {
12948                 proc = innerArgs[0];
12949                 if (proc.charAt(0) != '-') {
12950                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
12951                             = new ArrayList<ProcessCpuTracker.Stats>();
12952                     updateCpuStatsNow();
12953                     int findPid = -1;
12954                     try {
12955                         findPid = Integer.parseInt(innerArgs[0]);
12956                     } catch (NumberFormatException e) {
12957                     }
12958                     synchronized (mProcessCpuTracker) {
12959                         final int N = mProcessCpuTracker.countStats();
12960                         for (int i=0; i<N; i++) {
12961                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12962                             if (st.pid == findPid || (st.baseName != null
12963                                     && st.baseName.equals(innerArgs[0]))) {
12964                                 nativeProcs.add(st);
12965                             }
12966                         }
12967                     }
12968                     if (nativeProcs.size() > 0) {
12969                         ProtoOutputStream proto = new ProtoOutputStream(fd);
12970 
12971                         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12972                         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12973                         Debug.MemoryInfo mi = null;
12974                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12975                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12976                             final int pid = r.pid;
12977                             final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES);
12978 
12979                             proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
12980                             proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName);
12981 
12982                             if (mi == null) {
12983                                 mi = new Debug.MemoryInfo();
12984                             }
12985                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12986                                 Debug.getMemoryInfo(pid, mi);
12987                             } else {
12988                                 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null);
12989                                 mi.dalvikPrivateDirty = (int)tmpLong[0];
12990                             }
12991                             ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
12992                                     opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
12993 
12994                             proto.end(nToken);
12995                         }
12996 
12997                         proto.flush();
12998                         return;
12999                     }
13000                 }
13001             }
13002             Log.d(TAG, "No process found for: " + innerArgs[0]);
13003             return;
13004         }
13005 
13006         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
13007             opts.dumpDetails = true;
13008         }
13009 
13010         ProtoOutputStream proto = new ProtoOutputStream(fd);
13011 
13012         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
13013         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
13014 
13015         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
13016         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
13017         long nativePss = 0;
13018         long nativeSwapPss = 0;
13019         long dalvikPss = 0;
13020         long dalvikSwapPss = 0;
13021         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13022                 EmptyArray.LONG;
13023         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
13024                 EmptyArray.LONG;
13025         long otherPss = 0;
13026         long otherSwapPss = 0;
13027         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13028         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13029 
13030         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13031         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13032         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
13033                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
13034 
13035         long totalPss = 0;
13036         long totalSwapPss = 0;
13037         long cachedPss = 0;
13038         long cachedSwapPss = 0;
13039         boolean hasSwapPss = false;
13040 
13041         Debug.MemoryInfo mi = null;
13042         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
13043             final ProcessRecord r = procs.get(i);
13044             final IApplicationThread thread;
13045             final int pid;
13046             final int oomAdj;
13047             final boolean hasActivities;
13048             synchronized (this) {
13049                 thread = r.thread;
13050                 pid = r.pid;
13051                 oomAdj = r.getSetAdjWithServices();
13052                 hasActivities = r.hasActivities();
13053             }
13054             if (thread == null) {
13055                 continue;
13056             }
13057             if (mi == null) {
13058                 mi = new Debug.MemoryInfo();
13059             }
13060             final int reportType;
13061             final long startTime;
13062             final long endTime;
13063             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
13064                 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
13065                 startTime = SystemClock.currentThreadTimeMillis();
13066                 Debug.getMemoryInfo(pid, mi);
13067                 endTime = SystemClock.currentThreadTimeMillis();
13068                 hasSwapPss = mi.hasSwappedOutPss;
13069             } else {
13070                 reportType = ProcessStats.ADD_PSS_EXTERNAL;
13071                 startTime = SystemClock.currentThreadTimeMillis();
13072                 mi.dalvikPss = (int) Debug.getPss(pid, tmpLong, null);
13073                 endTime = SystemClock.currentThreadTimeMillis();
13074                 mi.dalvikPrivateDirty = (int) tmpLong[0];
13075             }
13076             if (opts.dumpDetails) {
13077                 if (opts.localOnly) {
13078                     final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES);
13079                     final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
13080                     proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
13081                     proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName);
13082                     ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
13083                             opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
13084                     proto.end(mToken);
13085                     proto.end(aToken);
13086                 } else {
13087                     try {
13088                         ByteTransferPipe tp = new ByteTransferPipe();
13089                         try {
13090                             thread.dumpMemInfoProto(tp.getWriteFd(),
13091                                 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
13092                                 opts.dumpUnreachable, innerArgs);
13093                             proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get());
13094                         } finally {
13095                             tp.kill();
13096                         }
13097                     } catch (IOException e) {
13098                         Log.e(TAG, "Got IOException!", e);
13099                     } catch (RemoteException e) {
13100                         Log.e(TAG, "Got RemoteException!", e);
13101                     }
13102                 }
13103             }
13104 
13105             final long myTotalPss = mi.getTotalPss();
13106             final long myTotalUss = mi.getTotalUss();
13107             final long myTotalRss = mi.getTotalRss();
13108             final long myTotalSwapPss = mi.getTotalSwappedOutPss();
13109 
13110             synchronized (this) {
13111                 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
13112                     // Record this for posterity if the process has been stable.
13113                     r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true,
13114                             reportType, endTime-startTime, r.pkgList.mPkgList);
13115                     for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) {
13116                         ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg);
13117                         StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
13118                                 r.info.uid,
13119                                 holder.state.getName(),
13120                                 holder.state.getPackage(),
13121                                 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
13122                                 holder.appVersion);
13123                     }
13124                 }
13125             }
13126 
13127             if (!opts.isCheckinRequest && mi != null) {
13128                 totalPss += myTotalPss;
13129                 totalSwapPss += myTotalSwapPss;
13130                 MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
13131                         (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
13132                         myTotalSwapPss, pid, hasActivities);
13133                 procMems.add(pssItem);
13134                 procMemsMap.put(pid, pssItem);
13135 
13136                 nativePss += mi.nativePss;
13137                 nativeSwapPss += mi.nativeSwappedOutPss;
13138                 dalvikPss += mi.dalvikPss;
13139                 dalvikSwapPss += mi.dalvikSwappedOutPss;
13140                 for (int j=0; j<dalvikSubitemPss.length; j++) {
13141                     dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13142                     dalvikSubitemSwapPss[j] +=
13143                             mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13144                 }
13145                 otherPss += mi.otherPss;
13146                 otherSwapPss += mi.otherSwappedOutPss;
13147                 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13148                     long mem = mi.getOtherPss(j);
13149                     miscPss[j] += mem;
13150                     otherPss -= mem;
13151                     mem = mi.getOtherSwappedOutPss(j);
13152                     miscSwapPss[j] += mem;
13153                     otherSwapPss -= mem;
13154                 }
13155 
13156                 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13157                     cachedPss += myTotalPss;
13158                     cachedSwapPss += myTotalSwapPss;
13159                 }
13160 
13161                 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
13162                     if (oomIndex == (oomPss.length - 1)
13163                             || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
13164                                     && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
13165                         oomPss[oomIndex] += myTotalPss;
13166                         oomSwapPss[oomIndex] += myTotalSwapPss;
13167                         if (oomProcs[oomIndex] == null) {
13168                             oomProcs[oomIndex] = new ArrayList<MemItem>();
13169                         }
13170                         oomProcs[oomIndex].add(pssItem);
13171                         break;
13172                     }
13173                 }
13174             }
13175         }
13176 
13177         long nativeProcTotalPss = 0;
13178 
13179         if (procs.size() > 1 && !opts.packages) {
13180             // If we are showing aggregations, also look for native processes to
13181             // include so that our aggregations are more accurate.
13182             updateCpuStatsNow();
13183             mi = null;
13184             synchronized (mProcessCpuTracker) {
13185                 final int N = mProcessCpuTracker.countStats();
13186                 for (int i=0; i<N; i++) {
13187                     ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13188                     if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
13189                         if (mi == null) {
13190                             mi = new Debug.MemoryInfo();
13191                         }
13192                         if (!brief && !opts.oomOnly) {
13193                             Debug.getMemoryInfo(st.pid, mi);
13194                         } else {
13195                             mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null);
13196                             mi.nativePrivateDirty = (int)tmpLong[0];
13197                         }
13198 
13199                         final long myTotalPss = mi.getTotalPss();
13200                         final long myTotalSwapPss = mi.getTotalSwappedOutPss();
13201                         totalPss += myTotalPss;
13202                         nativeProcTotalPss += myTotalPss;
13203 
13204                         MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
13205                                 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false);
13206                         procMems.add(pssItem);
13207 
13208                         nativePss += mi.nativePss;
13209                         nativeSwapPss += mi.nativeSwappedOutPss;
13210                         dalvikPss += mi.dalvikPss;
13211                         dalvikSwapPss += mi.dalvikSwappedOutPss;
13212                         for (int j=0; j<dalvikSubitemPss.length; j++) {
13213                             dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13214                             dalvikSubitemSwapPss[j] +=
13215                                     mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13216                         }
13217                         otherPss += mi.otherPss;
13218                         otherSwapPss += mi.otherSwappedOutPss;
13219                         for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13220                             long mem = mi.getOtherPss(j);
13221                             miscPss[j] += mem;
13222                             otherPss -= mem;
13223                             mem = mi.getOtherSwappedOutPss(j);
13224                             miscSwapPss[j] += mem;
13225                             otherSwapPss -= mem;
13226                         }
13227                         oomPss[0] += myTotalPss;
13228                         oomSwapPss[0] += myTotalSwapPss;
13229                         if (oomProcs[0] == null) {
13230                             oomProcs[0] = new ArrayList<MemItem>();
13231                         }
13232                         oomProcs[0].add(pssItem);
13233                     }
13234                 }
13235             }
13236 
13237             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
13238 
13239             catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1));
13240             final int dalvikId = -2;
13241             catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikId));
13242             catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3));
13243             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13244                 String label = Debug.MemoryInfo.getOtherLabel(j);
13245                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j));
13246             }
13247             if (dalvikSubitemPss.length > 0) {
13248                 // Add dalvik subitems.
13249                 for (MemItem memItem : catMems) {
13250                     int memItemStart = 0, memItemEnd = 0;
13251                     if (memItem.id == dalvikId) {
13252                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
13253                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
13254                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
13255                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
13256                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
13257                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
13258                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
13259                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
13260                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
13261                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
13262                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
13263                     } else {
13264                         continue;  // No subitems, continue.
13265                     }
13266                     memItem.subitems = new ArrayList<MemItem>();
13267                     for (int j=memItemStart; j<=memItemEnd; j++) {
13268                         final String name = Debug.MemoryInfo.getOtherLabel(
13269                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
13270                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
13271                                 dalvikSubitemSwapPss[j], j));
13272                     }
13273                 }
13274             }
13275 
13276             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
13277             for (int j=0; j<oomPss.length; j++) {
13278                 if (oomPss[j] != 0) {
13279                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
13280                             : DUMP_MEM_OOM_LABEL[j];
13281                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j],
13282                             DUMP_MEM_OOM_ADJ[j]);
13283                     item.subitems = oomProcs[j];
13284                     oomMems.add(item);
13285                 }
13286             }
13287 
13288             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0;
13289             if (!opts.oomOnly) {
13290                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc",
13291                         procMems, true, opts.dumpSwapPss);
13292             }
13293             dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom",
13294                     oomMems, false, opts.dumpSwapPss);
13295             if (!brief && !opts.oomOnly) {
13296                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat",
13297                         catMems, true, opts.dumpSwapPss);
13298             }
13299             MemInfoReader memInfo = new MemInfoReader();
13300             memInfo.readMemInfo();
13301             if (nativeProcTotalPss > 0) {
13302                 synchronized (this) {
13303                     final long cachedKb = memInfo.getCachedSizeKb();
13304                     final long freeKb = memInfo.getFreeSizeKb();
13305                     final long zramKb = memInfo.getZramTotalSizeKb();
13306                     final long kernelKb = memInfo.getKernelUsedSizeKb();
13307                     EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
13308                             kernelKb*1024, nativeProcTotalPss*1024);
13309                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
13310                             nativeProcTotalPss);
13311                 }
13312             }
13313             if (!brief) {
13314                 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb());
13315                 proto.write(MemInfoDumpProto.STATUS, mLastMemoryLevel);
13316                 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss);
13317                 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb());
13318                 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb());
13319             }
13320             long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss)
13321                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
13322                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
13323             proto.write(MemInfoDumpProto.USED_PSS_KB, totalPss - cachedPss);
13324             proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb());
13325             proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM);
13326             if (!brief) {
13327                 if (memInfo.getZramTotalSizeKb() != 0) {
13328                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb());
13329                     proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB,
13330                             memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb());
13331                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb());
13332                 }
13333                 final long[] ksm = getKsmInfo();
13334                 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]);
13335                 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]);
13336                 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]);
13337                 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]);
13338 
13339                 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass());
13340                 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass());
13341                 proto.write(MemInfoDumpProto.OOM_KB,
13342                         mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
13343                 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB,
13344                         mProcessList.getCachedRestoreThresholdKb());
13345 
13346                 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic());
13347                 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx());
13348             }
13349         }
13350 
13351         proto.flush();
13352     }
13353 
appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)13354     private void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss,
13355             long memtrack, String name) {
13356         sb.append("  ");
13357         sb.append(ProcessList.makeOomAdjString(oomAdj, false));
13358         sb.append(' ');
13359         sb.append(ProcessList.makeProcStateString(procState));
13360         sb.append(' ');
13361         ProcessList.appendRamKb(sb, pss);
13362         sb.append(": ");
13363         sb.append(name);
13364         if (memtrack > 0) {
13365             sb.append(" (");
13366             sb.append(stringifyKBSize(memtrack));
13367             sb.append(" memtrack)");
13368         }
13369     }
13370 
appendMemInfo(StringBuilder sb, ProcessMemInfo mi)13371     private void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) {
13372         appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name);
13373         sb.append(" (pid ");
13374         sb.append(mi.pid);
13375         sb.append(") ");
13376         sb.append(mi.adjType);
13377         sb.append('\n');
13378         if (mi.adjReason != null) {
13379             sb.append("                      ");
13380             sb.append(mi.adjReason);
13381             sb.append('\n');
13382         }
13383     }
13384 
reportMemUsage(ArrayList<ProcessMemInfo> memInfos)13385     void reportMemUsage(ArrayList<ProcessMemInfo> memInfos) {
13386         final SparseArray<ProcessMemInfo> infoMap = new SparseArray<>(memInfos.size());
13387         for (int i=0, N=memInfos.size(); i<N; i++) {
13388             ProcessMemInfo mi = memInfos.get(i);
13389             infoMap.put(mi.pid, mi);
13390         }
13391         updateCpuStatsNow();
13392         long[] memtrackTmp = new long[1];
13393         long[] swaptrackTmp = new long[2];
13394         final List<ProcessCpuTracker.Stats> stats;
13395         // Get a list of Stats that have vsize > 0
13396         synchronized (mProcessCpuTracker) {
13397             stats = mProcessCpuTracker.getStats((st) -> {
13398                 return st.vsize > 0;
13399             });
13400         }
13401         final int statsCount = stats.size();
13402         for (int i = 0; i < statsCount; i++) {
13403             ProcessCpuTracker.Stats st = stats.get(i);
13404             long pss = Debug.getPss(st.pid, swaptrackTmp, memtrackTmp);
13405             if (pss > 0) {
13406                 if (infoMap.indexOfKey(st.pid) < 0) {
13407                     ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid,
13408                             ProcessList.NATIVE_ADJ, -1, "native", null);
13409                     mi.pss = pss;
13410                     mi.swapPss = swaptrackTmp[1];
13411                     mi.memtrack = memtrackTmp[0];
13412                     memInfos.add(mi);
13413                 }
13414             }
13415         }
13416 
13417         long totalPss = 0;
13418         long totalSwapPss = 0;
13419         long totalMemtrack = 0;
13420         for (int i=0, N=memInfos.size(); i<N; i++) {
13421             ProcessMemInfo mi = memInfos.get(i);
13422             if (mi.pss == 0) {
13423                 mi.pss = Debug.getPss(mi.pid, swaptrackTmp, memtrackTmp);
13424                 mi.swapPss = swaptrackTmp[1];
13425                 mi.memtrack = memtrackTmp[0];
13426             }
13427             totalPss += mi.pss;
13428             totalSwapPss += mi.swapPss;
13429             totalMemtrack += mi.memtrack;
13430         }
13431         Collections.sort(memInfos, new Comparator<ProcessMemInfo>() {
13432             @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) {
13433                 if (lhs.oomAdj != rhs.oomAdj) {
13434                     return lhs.oomAdj < rhs.oomAdj ? -1 : 1;
13435                 }
13436                 if (lhs.pss != rhs.pss) {
13437                     return lhs.pss < rhs.pss ? 1 : -1;
13438                 }
13439                 return 0;
13440             }
13441         });
13442 
13443         StringBuilder tag = new StringBuilder(128);
13444         StringBuilder stack = new StringBuilder(128);
13445         tag.append("Low on memory -- ");
13446         appendMemBucket(tag, totalPss, "total", false);
13447         appendMemBucket(stack, totalPss, "total", true);
13448 
13449         StringBuilder fullNativeBuilder = new StringBuilder(1024);
13450         StringBuilder shortNativeBuilder = new StringBuilder(1024);
13451         StringBuilder fullJavaBuilder = new StringBuilder(1024);
13452 
13453         boolean firstLine = true;
13454         int lastOomAdj = Integer.MIN_VALUE;
13455         long extraNativeRam = 0;
13456         long extraNativeMemtrack = 0;
13457         long cachedPss = 0;
13458         for (int i=0, N=memInfos.size(); i<N; i++) {
13459             ProcessMemInfo mi = memInfos.get(i);
13460 
13461             if (mi.oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13462                 cachedPss += mi.pss;
13463             }
13464 
13465             if (mi.oomAdj != ProcessList.NATIVE_ADJ
13466                     && (mi.oomAdj < ProcessList.SERVICE_ADJ
13467                             || mi.oomAdj == ProcessList.HOME_APP_ADJ
13468                             || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) {
13469                 if (lastOomAdj != mi.oomAdj) {
13470                     lastOomAdj = mi.oomAdj;
13471                     if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13472                         tag.append(" / ");
13473                     }
13474                     if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13475                         if (firstLine) {
13476                             stack.append(":");
13477                             firstLine = false;
13478                         }
13479                         stack.append("\n\t at ");
13480                     } else {
13481                         stack.append("$");
13482                     }
13483                 } else {
13484                     tag.append(" ");
13485                     stack.append("$");
13486                 }
13487                 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13488                     appendMemBucket(tag, mi.pss, mi.name, false);
13489                 }
13490                 appendMemBucket(stack, mi.pss, mi.name, true);
13491                 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ
13492                         && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) {
13493                     stack.append("(");
13494                     for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
13495                         if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) {
13496                             stack.append(DUMP_MEM_OOM_LABEL[k]);
13497                             stack.append(":");
13498                             stack.append(DUMP_MEM_OOM_ADJ[k]);
13499                         }
13500                     }
13501                     stack.append(")");
13502                 }
13503             }
13504 
13505             appendMemInfo(fullNativeBuilder, mi);
13506             if (mi.oomAdj == ProcessList.NATIVE_ADJ) {
13507                 // The short form only has native processes that are >= 512K.
13508                 if (mi.pss >= 512) {
13509                     appendMemInfo(shortNativeBuilder, mi);
13510                 } else {
13511                     extraNativeRam += mi.pss;
13512                     extraNativeMemtrack += mi.memtrack;
13513                 }
13514             } else {
13515                 // Short form has all other details, but if we have collected RAM
13516                 // from smaller native processes let's dump a summary of that.
13517                 if (extraNativeRam > 0) {
13518                     appendBasicMemEntry(shortNativeBuilder, ProcessList.NATIVE_ADJ,
13519                             -1, extraNativeRam, extraNativeMemtrack, "(Other native)");
13520                     shortNativeBuilder.append('\n');
13521                     extraNativeRam = 0;
13522                 }
13523                 appendMemInfo(fullJavaBuilder, mi);
13524             }
13525         }
13526 
13527         fullJavaBuilder.append("           ");
13528         ProcessList.appendRamKb(fullJavaBuilder, totalPss);
13529         fullJavaBuilder.append(": TOTAL");
13530         if (totalMemtrack > 0) {
13531             fullJavaBuilder.append(" (");
13532             fullJavaBuilder.append(stringifyKBSize(totalMemtrack));
13533             fullJavaBuilder.append(" memtrack)");
13534         } else {
13535         }
13536         fullJavaBuilder.append("\n");
13537 
13538         MemInfoReader memInfo = new MemInfoReader();
13539         memInfo.readMemInfo();
13540         final long[] infos = memInfo.getRawInfo();
13541 
13542         StringBuilder memInfoBuilder = new StringBuilder(1024);
13543         Debug.getMemInfo(infos);
13544         memInfoBuilder.append("  MemInfo: ");
13545         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SLAB])).append(" slab, ");
13546         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SHMEM])).append(" shmem, ");
13547         memInfoBuilder.append(stringifyKBSize(
13548                                   infos[Debug.MEMINFO_VM_ALLOC_USED])).append(" vm alloc, ");
13549         memInfoBuilder.append(stringifyKBSize(
13550                                   infos[Debug.MEMINFO_PAGE_TABLES])).append(" page tables ");
13551         memInfoBuilder.append(stringifyKBSize(
13552                                   infos[Debug.MEMINFO_KERNEL_STACK])).append(" kernel stack\n");
13553         memInfoBuilder.append("           ");
13554         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_BUFFERS])).append(" buffers, ");
13555         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_CACHED])).append(" cached, ");
13556         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_MAPPED])).append(" mapped, ");
13557         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_FREE])).append(" free\n");
13558         if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) {
13559             memInfoBuilder.append("  ZRAM: ");
13560             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_ZRAM_TOTAL]));
13561             memInfoBuilder.append(" RAM, ");
13562             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_TOTAL]));
13563             memInfoBuilder.append(" swap total, ");
13564             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_FREE]));
13565             memInfoBuilder.append(" swap free\n");
13566         }
13567         final long[] ksm = getKsmInfo();
13568         if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
13569                 || ksm[KSM_VOLATILE] != 0) {
13570             memInfoBuilder.append("  KSM: ");
13571             memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARING]));
13572             memInfoBuilder.append(" saved from shared ");
13573             memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARED]));
13574             memInfoBuilder.append("\n       ");
13575             memInfoBuilder.append(stringifyKBSize(ksm[KSM_UNSHARED]));
13576             memInfoBuilder.append(" unshared; ");
13577             memInfoBuilder.append(stringifyKBSize(ksm[KSM_VOLATILE]));
13578             memInfoBuilder.append(" volatile\n");
13579         }
13580         memInfoBuilder.append("  Free RAM: ");
13581         memInfoBuilder.append(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
13582                 + memInfo.getFreeSizeKb()));
13583         memInfoBuilder.append("\n");
13584         long kernelUsed = memInfo.getKernelUsedSizeKb();
13585         final long ionHeap = Debug.getIonHeapsSizeKb();
13586         if (ionHeap > 0) {
13587             final long ionMapped = Debug.getIonMappedSizeKb();
13588             final long ionUnmapped = ionHeap - ionMapped;
13589             final long ionPool = Debug.getIonPoolsSizeKb();
13590             memInfoBuilder.append("       ION: ");
13591             memInfoBuilder.append(stringifyKBSize(ionHeap + ionPool));
13592             memInfoBuilder.append("\n");
13593             // Note: mapped ION memory is not accounted in PSS due to VM_PFNMAP flag being
13594             // set on ION VMAs, therefore consider the entire ION heap as used kernel memory
13595             kernelUsed += ionHeap;
13596         }
13597         memInfoBuilder.append("  Used RAM: ");
13598         memInfoBuilder.append(stringifyKBSize(
13599                                   totalPss - cachedPss + kernelUsed));
13600         memInfoBuilder.append("\n");
13601         memInfoBuilder.append("  Lost RAM: ");
13602         memInfoBuilder.append(stringifyKBSize(memInfo.getTotalSizeKb()
13603                 - (totalPss - totalSwapPss) - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
13604                 - kernelUsed - memInfo.getZramTotalSizeKb()));
13605         memInfoBuilder.append("\n");
13606         Slog.i(TAG, "Low on memory:");
13607         Slog.i(TAG, shortNativeBuilder.toString());
13608         Slog.i(TAG, fullJavaBuilder.toString());
13609         Slog.i(TAG, memInfoBuilder.toString());
13610 
13611         StringBuilder dropBuilder = new StringBuilder(1024);
13612         /*
13613         StringWriter oomSw = new StringWriter();
13614         PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256);
13615         StringWriter catSw = new StringWriter();
13616         PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
13617         String[] emptyArgs = new String[] { };
13618         dumpApplicationMemoryUsage(null, oomPw, "  ", emptyArgs, true, catPw);
13619         oomPw.flush();
13620         String oomString = oomSw.toString();
13621         */
13622         dropBuilder.append("Low on memory:");
13623         dropBuilder.append(stack);
13624         dropBuilder.append('\n');
13625         dropBuilder.append(fullNativeBuilder);
13626         dropBuilder.append(fullJavaBuilder);
13627         dropBuilder.append('\n');
13628         dropBuilder.append(memInfoBuilder);
13629         dropBuilder.append('\n');
13630         /*
13631         dropBuilder.append(oomString);
13632         dropBuilder.append('\n');
13633         */
13634         StringWriter catSw = new StringWriter();
13635         synchronized (ActivityManagerService.this) {
13636             PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
13637             String[] emptyArgs = new String[] { };
13638             catPw.println();
13639             dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null, -1);
13640             catPw.println();
13641             mServices.newServiceDumperLocked(null, catPw, emptyArgs, 0,
13642                     false, null).dumpLocked();
13643             catPw.println();
13644             mAtmInternal.dump(DUMP_ACTIVITIES_CMD, null, catPw, emptyArgs, 0, false, false, null);
13645             catPw.flush();
13646         }
13647         dropBuilder.append(catSw.toString());
13648         StatsLog.write(StatsLog.LOW_MEM_REPORTED);
13649         addErrorToDropBox("lowmem", null, "system_server", null,
13650                 null, null, tag.toString(), dropBuilder.toString(), null, null);
13651         //Slog.i(TAG, "Sent to dropbox:");
13652         //Slog.i(TAG, dropBuilder.toString());
13653         synchronized (ActivityManagerService.this) {
13654             long now = SystemClock.uptimeMillis();
13655             if (mLastMemUsageReportTime < now) {
13656                 mLastMemUsageReportTime = now;
13657             }
13658         }
13659     }
13660 
13661     /**
13662      * Searches array of arguments for the specified string
13663      * @param args array of argument strings
13664      * @param value value to search for
13665      * @return true if the value is contained in the array
13666      */
scanArgs(String[] args, String value)13667     private static boolean scanArgs(String[] args, String value) {
13668         if (args != null) {
13669             for (String arg : args) {
13670                 if (value.equals(arg)) {
13671                     return true;
13672                 }
13673             }
13674         }
13675         return false;
13676     }
13677 
removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, boolean always)13678     private final boolean removeDyingProviderLocked(ProcessRecord proc,
13679             ContentProviderRecord cpr, boolean always) {
13680         final boolean inLaunching = mLaunchingProviders.contains(cpr);
13681 
13682         if (!inLaunching || always) {
13683             synchronized (cpr) {
13684                 cpr.launchingApp = null;
13685                 cpr.notifyAll();
13686             }
13687             mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
13688             String names[] = cpr.info.authority.split(";");
13689             for (int j = 0; j < names.length; j++) {
13690                 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
13691             }
13692         }
13693 
13694         for (int i = cpr.connections.size() - 1; i >= 0; i--) {
13695             ContentProviderConnection conn = cpr.connections.get(i);
13696             if (conn.waiting) {
13697                 // If this connection is waiting for the provider, then we don't
13698                 // need to mess with its process unless we are always removing
13699                 // or for some reason the provider is not currently launching.
13700                 if (inLaunching && !always) {
13701                     continue;
13702                 }
13703             }
13704             ProcessRecord capp = conn.client;
13705             conn.dead = true;
13706             if (conn.stableCount > 0) {
13707                 if (!capp.isPersistent() && capp.thread != null
13708                         && capp.pid != 0
13709                         && capp.pid != MY_PID) {
13710                     capp.kill("depends on provider "
13711                             + cpr.name.flattenToShortString()
13712                             + " in dying proc " + (proc != null ? proc.processName : "??")
13713                             + " (adj " + (proc != null ? proc.setAdj : "??") + ")", true);
13714                 }
13715             } else if (capp.thread != null && conn.provider.provider != null) {
13716                 try {
13717                     capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
13718                 } catch (RemoteException e) {
13719                 }
13720                 // In the protocol here, we don't expect the client to correctly
13721                 // clean up this connection, we'll just remove it.
13722                 cpr.connections.remove(i);
13723                 if (conn.client.conProviders.remove(conn)) {
13724                     stopAssociationLocked(capp.uid, capp.processName, cpr.uid,
13725                             cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
13726                 }
13727             }
13728         }
13729 
13730         if (inLaunching && always) {
13731             mLaunchingProviders.remove(cpr);
13732         }
13733         return inLaunching;
13734     }
13735 
13736     /**
13737      * Main code for cleaning up a process when it has gone away.  This is
13738      * called both as a result of the process dying, or directly when stopping
13739      * a process when running in single process mode.
13740      *
13741      * @return Returns true if the given process has been restarted, so the
13742      * app that was passed in must remain on the process lists.
13743      */
13744     @GuardedBy("this")
cleanUpApplicationRecordLocked(ProcessRecord app, boolean restarting, boolean allowRestart, int index, boolean replacingPid)13745     final boolean cleanUpApplicationRecordLocked(ProcessRecord app,
13746             boolean restarting, boolean allowRestart, int index, boolean replacingPid) {
13747         if (index >= 0) {
13748             removeLruProcessLocked(app);
13749             ProcessList.remove(app.pid);
13750         }
13751 
13752         mProcessesToGc.remove(app);
13753         mPendingPssProcesses.remove(app);
13754         ProcessList.abortNextPssTime(app.procStateMemTracker);
13755 
13756         // Dismiss any open dialogs.
13757         if (app.crashDialog != null && !app.forceCrashReport) {
13758             app.crashDialog.dismiss();
13759             app.crashDialog = null;
13760         }
13761         if (app.anrDialog != null) {
13762             app.anrDialog.dismiss();
13763             app.anrDialog = null;
13764         }
13765         if (app.waitDialog != null) {
13766             app.waitDialog.dismiss();
13767             app.waitDialog = null;
13768         }
13769 
13770         app.setCrashing(false);
13771         app.setNotResponding(false);
13772 
13773         app.resetPackageList(mProcessStats);
13774         app.unlinkDeathRecipient();
13775         app.makeInactive(mProcessStats);
13776         app.waitingToKill = null;
13777         app.forcingToImportant = null;
13778         updateProcessForegroundLocked(app, false, 0, false);
13779         app.setHasForegroundActivities(false);
13780         app.hasShownUi = false;
13781         app.treatLikeActivity = false;
13782         app.hasAboveClient = false;
13783         app.setHasClientActivities(false);
13784 
13785         mServices.killServicesLocked(app, allowRestart);
13786 
13787         boolean restart = false;
13788 
13789         // Remove published content providers.
13790         for (int i = app.pubProviders.size() - 1; i >= 0; i--) {
13791             ContentProviderRecord cpr = app.pubProviders.valueAt(i);
13792             final boolean always = app.bad || !allowRestart;
13793             boolean inLaunching = removeDyingProviderLocked(app, cpr, always);
13794             if ((inLaunching || always) && cpr.hasConnectionOrHandle()) {
13795                 // We left the provider in the launching list, need to
13796                 // restart it.
13797                 restart = true;
13798             }
13799 
13800             cpr.provider = null;
13801             cpr.setProcess(null);
13802         }
13803         app.pubProviders.clear();
13804 
13805         // Take care of any launching providers waiting for this process.
13806         if (cleanupAppInLaunchingProvidersLocked(app, false)) {
13807             restart = true;
13808         }
13809 
13810         // Unregister from connected content providers.
13811         if (!app.conProviders.isEmpty()) {
13812             for (int i = app.conProviders.size() - 1; i >= 0; i--) {
13813                 ContentProviderConnection conn = app.conProviders.get(i);
13814                 conn.provider.connections.remove(conn);
13815                 stopAssociationLocked(app.uid, app.processName, conn.provider.uid,
13816                         conn.provider.appInfo.longVersionCode, conn.provider.name,
13817                         conn.provider.info.processName);
13818             }
13819             app.conProviders.clear();
13820         }
13821 
13822         // At this point there may be remaining entries in mLaunchingProviders
13823         // where we were the only one waiting, so they are no longer of use.
13824         // Look for these and clean up if found.
13825         // XXX Commented out for now.  Trying to figure out a way to reproduce
13826         // the actual situation to identify what is actually going on.
13827         if (false) {
13828             for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
13829                 ContentProviderRecord cpr = mLaunchingProviders.get(i);
13830                 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
13831                     synchronized (cpr) {
13832                         cpr.launchingApp = null;
13833                         cpr.notifyAll();
13834                     }
13835                 }
13836             }
13837         }
13838 
13839         skipCurrentReceiverLocked(app);
13840 
13841         // Unregister any receivers.
13842         for (int i = app.receivers.size() - 1; i >= 0; i--) {
13843             removeReceiverLocked(app.receivers.valueAt(i));
13844         }
13845         app.receivers.clear();
13846 
13847         // If the app is undergoing backup, tell the backup manager about it
13848         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
13849         if (backupTarget != null && app.pid == backupTarget.app.pid) {
13850             if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App "
13851                     + backupTarget.appInfo + " died during backup");
13852             mHandler.post(new Runnable() {
13853                 @Override
13854                 public void run(){
13855                     try {
13856                         IBackupManager bm = IBackupManager.Stub.asInterface(
13857                                 ServiceManager.getService(Context.BACKUP_SERVICE));
13858                         bm.agentDisconnectedForUser(app.userId, app.info.packageName);
13859                     } catch (RemoteException e) {
13860                         // can't happen; backup manager is local
13861                     }
13862                 }
13863             });
13864         }
13865 
13866         for (int i = mPendingProcessChanges.size() - 1; i >= 0; i--) {
13867             ProcessChangeItem item = mPendingProcessChanges.get(i);
13868             if (app.pid > 0 && item.pid == app.pid) {
13869                 mPendingProcessChanges.remove(i);
13870                 mAvailProcessChanges.add(item);
13871             }
13872         }
13873         mUiHandler.obtainMessage(DISPATCH_PROCESS_DIED_UI_MSG, app.pid, app.info.uid,
13874                 null).sendToTarget();
13875 
13876         // If the caller is restarting this app, then leave it in its
13877         // current lists and let the caller take care of it.
13878         if (restarting) {
13879             return false;
13880         }
13881 
13882         if (!app.isPersistent() || app.isolated) {
13883             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
13884                     "Removing non-persistent process during cleanup: " + app);
13885             if (!replacingPid) {
13886                 mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
13887             }
13888             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
13889         } else if (!app.removed) {
13890             // This app is persistent, so we need to keep its record around.
13891             // If it is not already on the pending app list, add it there
13892             // and start a new process for it.
13893             if (mPersistentStartingProcesses.indexOf(app) < 0) {
13894                 mPersistentStartingProcesses.add(app);
13895                 restart = true;
13896             }
13897         }
13898         if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(
13899                 TAG_CLEANUP, "Clean-up removing on hold: " + app);
13900         mProcessesOnHold.remove(app);
13901 
13902         mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController());
13903 
13904         if (restart && !app.isolated) {
13905             // We have components that still need to be running in the
13906             // process, so re-launch it.
13907             if (index < 0) {
13908                 ProcessList.remove(app.pid);
13909             }
13910             mProcessList.addProcessNameLocked(app);
13911             app.pendingStart = false;
13912             mProcessList.startProcessLocked(app,
13913                     new HostingRecord("restart", app.processName),
13914                     ZYGOTE_POLICY_FLAG_EMPTY);
13915             return true;
13916         } else if (app.pid > 0 && app.pid != MY_PID) {
13917             // Goodbye!
13918             mPidsSelfLocked.remove(app);
13919             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
13920             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
13921             if (app.isolated) {
13922                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
13923             }
13924             app.setPid(0);
13925         }
13926         return false;
13927     }
13928 
checkAppInLaunchingProvidersLocked(ProcessRecord app)13929     boolean checkAppInLaunchingProvidersLocked(ProcessRecord app) {
13930         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
13931             ContentProviderRecord cpr = mLaunchingProviders.get(i);
13932             if (cpr.launchingApp == app) {
13933                 return true;
13934             }
13935         }
13936         return false;
13937     }
13938 
cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad)13939     boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
13940         // Look through the content providers we are waiting to have launched,
13941         // and if any run in this process then either schedule a restart of
13942         // the process or kill the client waiting for it if this process has
13943         // gone bad.
13944         boolean restart = false;
13945         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
13946             ContentProviderRecord cpr = mLaunchingProviders.get(i);
13947             if (cpr.launchingApp == app) {
13948                 if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) {
13949                     restart = true;
13950                 } else {
13951                     removeDyingProviderLocked(app, cpr, true);
13952                 }
13953             }
13954         }
13955         return restart;
13956     }
13957 
13958     // =========================================================
13959     // SERVICES
13960     // =========================================================
13961 
13962     @Override
getServices(int maxNum, int flags)13963     public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) {
13964         enforceNotIsolatedCaller("getServices");
13965 
13966         final int callingUid = Binder.getCallingUid();
13967         final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission(
13968             INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED);
13969         final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices",
13970                 Binder.getCallingPid(), callingUid);
13971         synchronized (this) {
13972             return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid,
13973                 allowed, canInteractAcrossUsers);
13974         }
13975     }
13976 
13977     @Override
getRunningServiceControlPanel(ComponentName name)13978     public PendingIntent getRunningServiceControlPanel(ComponentName name) {
13979         enforceNotIsolatedCaller("getRunningServiceControlPanel");
13980         synchronized (this) {
13981             return mServices.getRunningServiceControlPanelLocked(name);
13982         }
13983     }
13984 
13985     @Override
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, int userId)13986     public ComponentName startService(IApplicationThread caller, Intent service,
13987             String resolvedType, boolean requireForeground, String callingPackage, int userId)
13988             throws TransactionTooLargeException {
13989         enforceNotIsolatedCaller("startService");
13990         // Refuse possible leaked file descriptors
13991         if (service != null && service.hasFileDescriptors() == true) {
13992             throw new IllegalArgumentException("File descriptors passed in Intent");
13993         }
13994 
13995         if (callingPackage == null) {
13996             throw new IllegalArgumentException("callingPackage cannot be null");
13997         }
13998 
13999         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
14000                 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
14001         synchronized(this) {
14002             final int callingPid = Binder.getCallingPid();
14003             final int callingUid = Binder.getCallingUid();
14004             final long origId = Binder.clearCallingIdentity();
14005             ComponentName res;
14006             try {
14007                 res = mServices.startServiceLocked(caller, service,
14008                         resolvedType, callingPid, callingUid,
14009                         requireForeground, callingPackage, userId);
14010             } finally {
14011                 Binder.restoreCallingIdentity(origId);
14012             }
14013             return res;
14014         }
14015     }
14016 
14017     @Override
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)14018     public int stopService(IApplicationThread caller, Intent service,
14019             String resolvedType, int userId) {
14020         enforceNotIsolatedCaller("stopService");
14021         // Refuse possible leaked file descriptors
14022         if (service != null && service.hasFileDescriptors() == true) {
14023             throw new IllegalArgumentException("File descriptors passed in Intent");
14024         }
14025 
14026         synchronized(this) {
14027             return mServices.stopServiceLocked(caller, service, resolvedType, userId);
14028         }
14029     }
14030 
14031     @Override
peekService(Intent service, String resolvedType, String callingPackage)14032     public IBinder peekService(Intent service, String resolvedType, String callingPackage) {
14033         enforceNotIsolatedCaller("peekService");
14034         // Refuse possible leaked file descriptors
14035         if (service != null && service.hasFileDescriptors() == true) {
14036             throw new IllegalArgumentException("File descriptors passed in Intent");
14037         }
14038 
14039         if (callingPackage == null) {
14040             throw new IllegalArgumentException("callingPackage cannot be null");
14041         }
14042 
14043         synchronized(this) {
14044             return mServices.peekServiceLocked(service, resolvedType, callingPackage);
14045         }
14046     }
14047 
14048     @Override
stopServiceToken(ComponentName className, IBinder token, int startId)14049     public boolean stopServiceToken(ComponentName className, IBinder token,
14050             int startId) {
14051         synchronized(this) {
14052             return mServices.stopServiceTokenLocked(className, token, startId);
14053         }
14054     }
14055 
14056     @Override
setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)14057     public void setServiceForeground(ComponentName className, IBinder token,
14058             int id, Notification notification, int flags, int foregroundServiceType) {
14059         synchronized(this) {
14060             mServices.setServiceForegroundLocked(className, token, id, notification, flags,
14061                     foregroundServiceType);
14062         }
14063     }
14064 
14065     @Override
getForegroundServiceType(ComponentName className, IBinder token)14066     public int getForegroundServiceType(ComponentName className, IBinder token) {
14067         synchronized (this) {
14068             return mServices.getForegroundServiceTypeLocked(className, token);
14069         }
14070     }
14071 
14072     @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)14073     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
14074             boolean requireFull, String name, String callerPackage) {
14075         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
14076                 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
14077     }
14078 
isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)14079     boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
14080             String className, int flags) {
14081         boolean result = false;
14082         // For apps that don't have pre-defined UIDs, check for permission
14083         if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) {
14084             if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
14085                 if (ActivityManager.checkUidPermission(
14086                         INTERACT_ACROSS_USERS,
14087                         aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
14088                     ComponentName comp = new ComponentName(aInfo.packageName, className);
14089                     String msg = "Permission Denial: Component " + comp.flattenToShortString()
14090                             + " requests FLAG_SINGLE_USER, but app does not hold "
14091                             + INTERACT_ACROSS_USERS;
14092                     Slog.w(TAG, msg);
14093                     throw new SecurityException(msg);
14094                 }
14095                 // Permission passed
14096                 result = true;
14097             }
14098         } else if ("system".equals(componentProcessName)) {
14099             result = true;
14100         } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
14101             // Phone app and persistent apps are allowed to export singleuser providers.
14102             result = UserHandle.isSameApp(aInfo.uid, PHONE_UID)
14103                     || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
14104         }
14105         if (DEBUG_MU) Slog.v(TAG_MU,
14106                 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x"
14107                 + Integer.toHexString(flags) + ") = " + result);
14108         return result;
14109     }
14110 
14111     /**
14112      * Checks to see if the caller is in the same app as the singleton
14113      * component, or the component is in a special app. It allows special apps
14114      * to export singleton components but prevents exporting singleton
14115      * components for regular apps.
14116      */
isValidSingletonCall(int callingUid, int componentUid)14117     boolean isValidSingletonCall(int callingUid, int componentUid) {
14118         int componentAppId = UserHandle.getAppId(componentUid);
14119         return UserHandle.isSameApp(callingUid, componentUid)
14120                 || componentAppId == SYSTEM_UID
14121                 || componentAppId == PHONE_UID
14122                 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
14123                         == PackageManager.PERMISSION_GRANTED;
14124     }
14125 
bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)14126     public int bindService(IApplicationThread caller, IBinder token, Intent service,
14127             String resolvedType, IServiceConnection connection, int flags,
14128             String callingPackage, int userId) throws TransactionTooLargeException {
14129         return bindIsolatedService(caller, token, service, resolvedType, connection, flags,
14130                 null, callingPackage, userId);
14131     }
14132 
bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)14133     public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
14134             String resolvedType, IServiceConnection connection, int flags, String instanceName,
14135             String callingPackage, int userId) throws TransactionTooLargeException {
14136         enforceNotIsolatedCaller("bindService");
14137 
14138         // Refuse possible leaked file descriptors
14139         if (service != null && service.hasFileDescriptors() == true) {
14140             throw new IllegalArgumentException("File descriptors passed in Intent");
14141         }
14142 
14143         if (callingPackage == null) {
14144             throw new IllegalArgumentException("callingPackage cannot be null");
14145         }
14146 
14147         // Ensure that instanceName, which is caller provided, does not contain
14148         // unusual characters.
14149         if (instanceName != null) {
14150             for (int i = 0; i < instanceName.length(); ++i) {
14151                 char c = instanceName.charAt(i);
14152                 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
14153                             || (c >= '0' && c <= '9') || c == '_' || c == '.')) {
14154                     throw new IllegalArgumentException("Illegal instanceName");
14155                 }
14156             }
14157         }
14158 
14159         synchronized(this) {
14160             return mServices.bindServiceLocked(caller, token, service,
14161                     resolvedType, connection, flags, instanceName, callingPackage, userId);
14162         }
14163     }
14164 
updateServiceGroup(IServiceConnection connection, int group, int importance)14165     public void updateServiceGroup(IServiceConnection connection, int group, int importance) {
14166         synchronized (this) {
14167             mServices.updateServiceGroupLocked(connection, group, importance);
14168         }
14169     }
14170 
unbindService(IServiceConnection connection)14171     public boolean unbindService(IServiceConnection connection) {
14172         synchronized (this) {
14173             return mServices.unbindServiceLocked(connection);
14174         }
14175     }
14176 
publishService(IBinder token, Intent intent, IBinder service)14177     public void publishService(IBinder token, Intent intent, IBinder service) {
14178         // Refuse possible leaked file descriptors
14179         if (intent != null && intent.hasFileDescriptors() == true) {
14180             throw new IllegalArgumentException("File descriptors passed in Intent");
14181         }
14182 
14183         synchronized(this) {
14184             if (!(token instanceof ServiceRecord)) {
14185                 throw new IllegalArgumentException("Invalid service token");
14186             }
14187             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
14188         }
14189     }
14190 
unbindFinished(IBinder token, Intent intent, boolean doRebind)14191     public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
14192         // Refuse possible leaked file descriptors
14193         if (intent != null && intent.hasFileDescriptors() == true) {
14194             throw new IllegalArgumentException("File descriptors passed in Intent");
14195         }
14196 
14197         synchronized(this) {
14198             mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
14199         }
14200     }
14201 
serviceDoneExecuting(IBinder token, int type, int startId, int res)14202     public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
14203         synchronized(this) {
14204             if (!(token instanceof ServiceRecord)) {
14205                 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
14206                 throw new IllegalArgumentException("Invalid service token");
14207             }
14208             mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
14209         }
14210     }
14211 
14212     // =========================================================
14213     // BACKUP AND RESTORE
14214     // =========================================================
14215 
14216     // Cause the target app to be launched if necessary and its backup agent
14217     // instantiated.  The backup agent will invoke backupAgentCreated() on the
14218     // activity manager to announce its creation.
bindBackupAgent(String packageName, int backupMode, int targetUserId)14219     public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId) {
14220         if (DEBUG_BACKUP) {
14221             Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
14222                     + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
14223                     + " uid = " + Process.myUid());
14224         }
14225         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
14226 
14227         // The instantiatedUserId is the user of the process the backup agent is started in. This is
14228         // different from the targetUserId which is the user whose data is to be backed up or
14229         // restored. This distinction is important for system-process packages that live in the
14230         // system user's process but backup/restore data for non-system users.
14231         // TODO (b/123688746): Handle all system-process packages with singleton check.
14232         final int instantiatedUserId =
14233                 PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId;
14234 
14235         IPackageManager pm = AppGlobals.getPackageManager();
14236         ApplicationInfo app = null;
14237         try {
14238             app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
14239         } catch (RemoteException e) {
14240             // can't happen; package manager is process-local
14241         }
14242         if (app == null) {
14243             Slog.w(TAG, "Unable to bind backup agent for " + packageName);
14244             return false;
14245         }
14246 
14247         int oldBackupUid;
14248         int newBackupUid;
14249 
14250         synchronized(this) {
14251             // !!! TODO: currently no check here that we're already bound
14252             // Backup agent is now in use, its package can't be stopped.
14253             try {
14254                 AppGlobals.getPackageManager().setPackageStoppedState(
14255                         app.packageName, false, UserHandle.getUserId(app.uid));
14256             } catch (RemoteException e) {
14257             } catch (IllegalArgumentException e) {
14258                 Slog.w(TAG, "Failed trying to unstop package "
14259                         + app.packageName + ": " + e);
14260             }
14261 
14262             BackupRecord r = new BackupRecord(app, backupMode, targetUserId);
14263             ComponentName hostingName =
14264                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL)
14265                             ? new ComponentName(app.packageName, app.backupAgentName)
14266                             : new ComponentName("android", "FullBackupAgent");
14267 
14268             // startProcessLocked() returns existing proc's record if it's already running
14269             ProcessRecord proc = startProcessLocked(app.processName, app,
14270                     false, 0,
14271                     new HostingRecord("backup", hostingName),
14272                     ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS, false, false, false);
14273             if (proc == null) {
14274                 Slog.e(TAG, "Unable to start backup agent process " + r);
14275                 return false;
14276             }
14277 
14278             // If the app is a regular app (uid >= 10000) and not the system server or phone
14279             // process, etc, then mark it as being in full backup so that certain calls to the
14280             // process can be blocked. This is not reset to false anywhere because we kill the
14281             // process after the full backup is done and the ProcessRecord will vaporize anyway.
14282             if (UserHandle.isApp(app.uid) &&
14283                     backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) {
14284                 proc.inFullBackup = true;
14285             }
14286             r.app = proc;
14287             final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
14288             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
14289             newBackupUid = proc.inFullBackup ? r.appInfo.uid : -1;
14290             mBackupTargets.put(targetUserId, r);
14291 
14292             // Try not to kill the process during backup
14293             updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE);
14294 
14295             // If the process is already attached, schedule the creation of the backup agent now.
14296             // If it is not yet live, this will be done when it attaches to the framework.
14297             if (proc.thread != null) {
14298                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
14299                 try {
14300                     proc.thread.scheduleCreateBackupAgent(app,
14301                             compatibilityInfoForPackage(app), backupMode, targetUserId);
14302                 } catch (RemoteException e) {
14303                     // Will time out on the backup manager side
14304                 }
14305             } else {
14306                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach");
14307             }
14308             // Invariants: at this point, the target app process exists and the application
14309             // is either already running or in the process of coming up.  mBackupTarget and
14310             // mBackupAppName describe the app, so that when it binds back to the AM we
14311             // know that it's scheduled for a backup-agent operation.
14312         }
14313 
14314         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
14315         if (oldBackupUid != -1) {
14316             js.removeBackingUpUid(oldBackupUid);
14317         }
14318         if (newBackupUid != -1) {
14319             js.addBackingUpUid(newBackupUid);
14320         }
14321 
14322         return true;
14323     }
14324 
clearPendingBackup(int userId)14325     private void clearPendingBackup(int userId) {
14326         if (DEBUG_BACKUP) {
14327             Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = "
14328                     + Binder.getCallingUid() + " uid = " + Process.myUid());
14329         }
14330 
14331         synchronized (this) {
14332             mBackupTargets.delete(userId);
14333         }
14334 
14335         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
14336         js.clearAllBackingUpUids();
14337     }
14338 
14339     // A backup agent has just come up
14340     @Override
backupAgentCreated(String agentPackageName, IBinder agent, int userId)14341     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
14342         // Resolve the target user id and enforce permissions.
14343         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
14344                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
14345         if (DEBUG_BACKUP) {
14346             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
14347                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
14348                     + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid());
14349         }
14350 
14351         synchronized(this) {
14352             final BackupRecord backupTarget = mBackupTargets.get(userId);
14353             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
14354             if (!agentPackageName.equals(backupAppName)) {
14355                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
14356                 return;
14357             }
14358         }
14359 
14360         long oldIdent = Binder.clearCallingIdentity();
14361         try {
14362             IBackupManager bm = IBackupManager.Stub.asInterface(
14363                     ServiceManager.getService(Context.BACKUP_SERVICE));
14364             bm.agentConnectedForUser(userId, agentPackageName, agent);
14365         } catch (RemoteException e) {
14366             // can't happen; the backup manager service is local
14367         } catch (Exception e) {
14368             Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
14369             e.printStackTrace();
14370         } finally {
14371             Binder.restoreCallingIdentity(oldIdent);
14372         }
14373     }
14374 
14375     // done with this agent
unbindBackupAgent(ApplicationInfo appInfo)14376     public void unbindBackupAgent(ApplicationInfo appInfo) {
14377         if (DEBUG_BACKUP) {
14378             Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = "
14379                     + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = "
14380                     + Process.myUid());
14381         }
14382 
14383         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent");
14384         if (appInfo == null) {
14385             Slog.w(TAG, "unbind backup agent for null app");
14386             return;
14387         }
14388 
14389         int oldBackupUid;
14390 
14391         final int userId = UserHandle.getUserId(appInfo.uid);
14392         synchronized(this) {
14393             final BackupRecord backupTarget = mBackupTargets.get(userId);
14394             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
14395             try {
14396                 if (backupAppName == null) {
14397                     Slog.w(TAG, "Unbinding backup agent with no active backup");
14398                     return;
14399                 }
14400 
14401                 if (!backupAppName.equals(appInfo.packageName)) {
14402                     Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
14403                     return;
14404                 }
14405 
14406                 // Not backing this app up any more; reset its OOM adjustment
14407                 final ProcessRecord proc = backupTarget.app;
14408                 updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE);
14409                 proc.inFullBackup = false;
14410 
14411                 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
14412 
14413                 // If the app crashed during backup, 'thread' will be null here
14414                 if (proc.thread != null) {
14415                     try {
14416                         proc.thread.scheduleDestroyBackupAgent(appInfo,
14417                                 compatibilityInfoForPackage(appInfo), userId);
14418                     } catch (Exception e) {
14419                         Slog.e(TAG, "Exception when unbinding backup agent:");
14420                         e.printStackTrace();
14421                     }
14422                 }
14423             } finally {
14424                 mBackupTargets.delete(userId);
14425             }
14426         }
14427 
14428         if (oldBackupUid != -1) {
14429             JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
14430             js.removeBackingUpUid(oldBackupUid);
14431         }
14432     }
14433 
14434     // =========================================================
14435     // BROADCASTS
14436     // =========================================================
14437 
isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)14438     private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) {
14439         if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) {
14440             return false;
14441         }
14442         // Easy case -- we have the app's ProcessRecord.
14443         if (record != null) {
14444             return record.info.isInstantApp();
14445         }
14446         // Otherwise check with PackageManager.
14447         IPackageManager pm = AppGlobals.getPackageManager();
14448         try {
14449             if (callerPackage == null) {
14450                 final String[] packageNames = pm.getPackagesForUid(uid);
14451                 if (packageNames == null || packageNames.length == 0) {
14452                     throw new IllegalArgumentException("Unable to determine caller package name");
14453                 }
14454                 // Instant Apps can't use shared uids, so its safe to only check the first package.
14455                 callerPackage = packageNames[0];
14456             }
14457             mAppOpsService.checkPackage(uid, callerPackage);
14458             return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid));
14459         } catch (RemoteException e) {
14460             Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e);
14461             return true;
14462         }
14463     }
14464 
isPendingBroadcastProcessLocked(int pid)14465     boolean isPendingBroadcastProcessLocked(int pid) {
14466         return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
14467                 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
14468                 || mOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid);
14469     }
14470 
skipPendingBroadcastLocked(int pid)14471     void skipPendingBroadcastLocked(int pid) {
14472             Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
14473             for (BroadcastQueue queue : mBroadcastQueues) {
14474                 queue.skipPendingBroadcastLocked(pid);
14475             }
14476     }
14477 
14478     // The app just attached; send any pending broadcasts that it should receive
sendPendingBroadcastsLocked(ProcessRecord app)14479     boolean sendPendingBroadcastsLocked(ProcessRecord app) {
14480         boolean didSomething = false;
14481         for (BroadcastQueue queue : mBroadcastQueues) {
14482             didSomething |= queue.sendPendingBroadcastsLocked(app);
14483         }
14484         return didSomething;
14485     }
14486 
registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14487     public Intent registerReceiver(IApplicationThread caller, String callerPackage,
14488             IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
14489             int flags) {
14490         enforceNotIsolatedCaller("registerReceiver");
14491         ArrayList<Intent> stickyIntents = null;
14492         ProcessRecord callerApp = null;
14493         final boolean visibleToInstantApps
14494                 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
14495         int callingUid;
14496         int callingPid;
14497         boolean instantApp;
14498         synchronized(this) {
14499             if (caller != null) {
14500                 callerApp = getRecordForAppLocked(caller);
14501                 if (callerApp == null) {
14502                     throw new SecurityException(
14503                             "Unable to find app for caller " + caller
14504                             + " (pid=" + Binder.getCallingPid()
14505                             + ") when registering receiver " + receiver);
14506                 }
14507                 if (callerApp.info.uid != SYSTEM_UID &&
14508                         !callerApp.pkgList.containsKey(callerPackage) &&
14509                         !"android".equals(callerPackage)) {
14510                     throw new SecurityException("Given caller package " + callerPackage
14511                             + " is not running in process " + callerApp);
14512                 }
14513                 callingUid = callerApp.info.uid;
14514                 callingPid = callerApp.pid;
14515             } else {
14516                 callerPackage = null;
14517                 callingUid = Binder.getCallingUid();
14518                 callingPid = Binder.getCallingPid();
14519             }
14520 
14521             instantApp = isInstantApp(callerApp, callerPackage, callingUid);
14522             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
14523                     ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
14524 
14525             Iterator<String> actions = filter.actionsIterator();
14526             if (actions == null) {
14527                 ArrayList<String> noAction = new ArrayList<String>(1);
14528                 noAction.add(null);
14529                 actions = noAction.iterator();
14530             }
14531 
14532             // Collect stickies of users
14533             int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) };
14534             while (actions.hasNext()) {
14535                 String action = actions.next();
14536                 for (int id : userIds) {
14537                     ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id);
14538                     if (stickies != null) {
14539                         ArrayList<Intent> intents = stickies.get(action);
14540                         if (intents != null) {
14541                             if (stickyIntents == null) {
14542                                 stickyIntents = new ArrayList<Intent>();
14543                             }
14544                             stickyIntents.addAll(intents);
14545                         }
14546                     }
14547                 }
14548             }
14549         }
14550 
14551         ArrayList<Intent> allSticky = null;
14552         if (stickyIntents != null) {
14553             final ContentResolver resolver = mContext.getContentResolver();
14554             // Look for any matching sticky broadcasts...
14555             for (int i = 0, N = stickyIntents.size(); i < N; i++) {
14556                 Intent intent = stickyIntents.get(i);
14557                 // Don't provided intents that aren't available to instant apps.
14558                 if (instantApp &&
14559                         (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) {
14560                     continue;
14561                 }
14562                 // If intent has scheme "content", it will need to acccess
14563                 // provider that needs to lock mProviderMap in ActivityThread
14564                 // and also it may need to wait application response, so we
14565                 // cannot lock ActivityManagerService here.
14566                 if (filter.match(resolver, intent, true, TAG) >= 0) {
14567                     if (allSticky == null) {
14568                         allSticky = new ArrayList<Intent>();
14569                     }
14570                     allSticky.add(intent);
14571                 }
14572             }
14573         }
14574 
14575         // The first sticky in the list is returned directly back to the client.
14576         Intent sticky = allSticky != null ? allSticky.get(0) : null;
14577         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky);
14578         if (receiver == null) {
14579             return sticky;
14580         }
14581 
14582         synchronized (this) {
14583             if (callerApp != null && (callerApp.thread == null
14584                     || callerApp.thread.asBinder() != caller.asBinder())) {
14585                 // Original caller already died
14586                 return null;
14587             }
14588             ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14589             if (rl == null) {
14590                 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
14591                         userId, receiver);
14592                 if (rl.app != null) {
14593                     final int totalReceiversForApp = rl.app.receivers.size();
14594                     if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) {
14595                         throw new IllegalStateException("Too many receivers, total of "
14596                                 + totalReceiversForApp + ", registered for pid: "
14597                                 + rl.pid + ", callerPackage: " + callerPackage);
14598                     }
14599                     rl.app.receivers.add(rl);
14600                 } else {
14601                     try {
14602                         receiver.asBinder().linkToDeath(rl, 0);
14603                     } catch (RemoteException e) {
14604                         return sticky;
14605                     }
14606                     rl.linkedToDeath = true;
14607                 }
14608                 mRegisteredReceivers.put(receiver.asBinder(), rl);
14609             } else if (rl.uid != callingUid) {
14610                 throw new IllegalArgumentException(
14611                         "Receiver requested to register for uid " + callingUid
14612                         + " was previously registered for uid " + rl.uid
14613                         + " callerPackage is " + callerPackage);
14614             } else if (rl.pid != callingPid) {
14615                 throw new IllegalArgumentException(
14616                         "Receiver requested to register for pid " + callingPid
14617                         + " was previously registered for pid " + rl.pid
14618                         + " callerPackage is " + callerPackage);
14619             } else if (rl.userId != userId) {
14620                 throw new IllegalArgumentException(
14621                         "Receiver requested to register for user " + userId
14622                         + " was previously registered for user " + rl.userId
14623                         + " callerPackage is " + callerPackage);
14624             }
14625             BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
14626                     permission, callingUid, userId, instantApp, visibleToInstantApps);
14627             if (rl.containsFilter(filter)) {
14628                 Slog.w(TAG, "Receiver with filter " + filter
14629                         + " already registered for pid " + rl.pid
14630                         + ", callerPackage is " + callerPackage);
14631             } else {
14632                 rl.add(bf);
14633                 if (!bf.debugCheck()) {
14634                     Slog.w(TAG, "==> For Dynamic broadcast");
14635                 }
14636                 mReceiverResolver.addFilter(bf);
14637             }
14638 
14639             // Enqueue broadcasts for all existing stickies that match
14640             // this filter.
14641             if (allSticky != null) {
14642                 ArrayList receivers = new ArrayList();
14643                 receivers.add(bf);
14644 
14645                 final int stickyCount = allSticky.size();
14646                 for (int i = 0; i < stickyCount; i++) {
14647                     Intent intent = allSticky.get(i);
14648                     BroadcastQueue queue = broadcastQueueForIntent(intent);
14649                     BroadcastRecord r = new BroadcastRecord(queue, intent, null,
14650                             null, -1, -1, false, null, null, OP_NONE, null, receivers,
14651                             null, 0, null, null, false, true, true, -1, false,
14652                             false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */);
14653                     queue.enqueueParallelBroadcastLocked(r);
14654                     queue.scheduleBroadcastsLocked();
14655                 }
14656             }
14657 
14658             return sticky;
14659         }
14660     }
14661 
unregisterReceiver(IIntentReceiver receiver)14662     public void unregisterReceiver(IIntentReceiver receiver) {
14663         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver);
14664 
14665         final long origId = Binder.clearCallingIdentity();
14666         try {
14667             boolean doTrim = false;
14668 
14669             synchronized(this) {
14670                 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14671                 if (rl != null) {
14672                     final BroadcastRecord r = rl.curBroadcast;
14673                     if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) {
14674                         final boolean doNext = r.queue.finishReceiverLocked(
14675                                 r, r.resultCode, r.resultData, r.resultExtras,
14676                                 r.resultAbort, false);
14677                         if (doNext) {
14678                             doTrim = true;
14679                             r.queue.processNextBroadcast(false);
14680                         }
14681                     }
14682 
14683                     if (rl.app != null) {
14684                         rl.app.receivers.remove(rl);
14685                     }
14686                     removeReceiverLocked(rl);
14687                     if (rl.linkedToDeath) {
14688                         rl.linkedToDeath = false;
14689                         rl.receiver.asBinder().unlinkToDeath(rl, 0);
14690                     }
14691                 }
14692             }
14693 
14694             // If we actually concluded any broadcasts, we might now be able
14695             // to trim the recipients' apps from our working set
14696             if (doTrim) {
14697                 trimApplications(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
14698                 return;
14699             }
14700 
14701         } finally {
14702             Binder.restoreCallingIdentity(origId);
14703         }
14704     }
14705 
removeReceiverLocked(ReceiverList rl)14706     void removeReceiverLocked(ReceiverList rl) {
14707         mRegisteredReceivers.remove(rl.receiver.asBinder());
14708         for (int i = rl.size() - 1; i >= 0; i--) {
14709             mReceiverResolver.removeFilter(rl.get(i));
14710         }
14711     }
14712 
sendPackageBroadcastLocked(int cmd, String[] packages, int userId)14713     private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
14714         mProcessList.sendPackageBroadcastLocked(cmd, packages, userId);
14715     }
14716 
collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users)14717     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
14718             int callingUid, int[] users) {
14719         // TODO: come back and remove this assumption to triage all broadcasts
14720         int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
14721 
14722         List<ResolveInfo> receivers = null;
14723         try {
14724             HashSet<ComponentName> singleUserReceivers = null;
14725             boolean scannedFirstReceivers = false;
14726             for (int user : users) {
14727                 // Skip users that have Shell restrictions, with exception of always permitted
14728                 // Shell broadcasts
14729                 if (callingUid == SHELL_UID
14730                         && mUserController.hasUserRestriction(
14731                                 UserManager.DISALLOW_DEBUGGING_FEATURES, user)
14732                         && !isPermittedShellBroadcast(intent)) {
14733                     continue;
14734                 }
14735                 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
14736                         .queryIntentReceivers(intent, resolvedType, pmFlags, user).getList();
14737                 if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
14738                     // If this is not the system user, we need to check for
14739                     // any receivers that should be filtered out.
14740                     for (int i=0; i<newReceivers.size(); i++) {
14741                         ResolveInfo ri = newReceivers.get(i);
14742                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
14743                             newReceivers.remove(i);
14744                             i--;
14745                         }
14746                     }
14747                 }
14748                 if (newReceivers != null && newReceivers.size() == 0) {
14749                     newReceivers = null;
14750                 }
14751                 if (receivers == null) {
14752                     receivers = newReceivers;
14753                 } else if (newReceivers != null) {
14754                     // We need to concatenate the additional receivers
14755                     // found with what we have do far.  This would be easy,
14756                     // but we also need to de-dup any receivers that are
14757                     // singleUser.
14758                     if (!scannedFirstReceivers) {
14759                         // Collect any single user receivers we had already retrieved.
14760                         scannedFirstReceivers = true;
14761                         for (int i=0; i<receivers.size(); i++) {
14762                             ResolveInfo ri = receivers.get(i);
14763                             if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14764                                 ComponentName cn = new ComponentName(
14765                                         ri.activityInfo.packageName, ri.activityInfo.name);
14766                                 if (singleUserReceivers == null) {
14767                                     singleUserReceivers = new HashSet<ComponentName>();
14768                                 }
14769                                 singleUserReceivers.add(cn);
14770                             }
14771                         }
14772                     }
14773                     // Add the new results to the existing results, tracking
14774                     // and de-dupping single user receivers.
14775                     for (int i=0; i<newReceivers.size(); i++) {
14776                         ResolveInfo ri = newReceivers.get(i);
14777                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14778                             ComponentName cn = new ComponentName(
14779                                     ri.activityInfo.packageName, ri.activityInfo.name);
14780                             if (singleUserReceivers == null) {
14781                                 singleUserReceivers = new HashSet<ComponentName>();
14782                             }
14783                             if (!singleUserReceivers.contains(cn)) {
14784                                 singleUserReceivers.add(cn);
14785                                 receivers.add(ri);
14786                             }
14787                         } else {
14788                             receivers.add(ri);
14789                         }
14790                     }
14791                 }
14792             }
14793         } catch (RemoteException ex) {
14794             // pm is in same process, this will never happen.
14795         }
14796         return receivers;
14797     }
14798 
isPermittedShellBroadcast(Intent intent)14799     private boolean isPermittedShellBroadcast(Intent intent) {
14800         // remote bugreport should always be allowed to be taken
14801         return INTENT_REMOTE_BUGREPORT_FINISHED.equals(intent.getAction());
14802     }
14803 
checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)14804     private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp,
14805             String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) {
14806         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
14807             // Don't yell about broadcasts sent via shell
14808             return;
14809         }
14810 
14811         final String action = intent.getAction();
14812         if (isProtectedBroadcast
14813                 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
14814                 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
14815                 || Intent.ACTION_MEDIA_BUTTON.equals(action)
14816                 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
14817                 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
14818                 || Intent.ACTION_MASTER_CLEAR.equals(action)
14819                 || Intent.ACTION_FACTORY_RESET.equals(action)
14820                 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14821                 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
14822                 || LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION.equals(action)
14823                 || TelephonyIntents.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action)
14824                 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action)
14825                 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action)
14826                 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) {
14827             // Broadcast is either protected, or it's a public action that
14828             // we've relaxed, so it's fine for system internals to send.
14829             return;
14830         }
14831 
14832         // This broadcast may be a problem...  but there are often system components that
14833         // want to send an internal broadcast to themselves, which is annoying to have to
14834         // explicitly list each action as a protected broadcast, so we will check for that
14835         // one safe case and allow it: an explicit broadcast, only being received by something
14836         // that has protected itself.
14837         if (intent.getPackage() != null || intent.getComponent() != null) {
14838             if (receivers == null || receivers.size() == 0) {
14839                 // Intent is explicit and there's no receivers.
14840                 // This happens, e.g. , when a system component sends a broadcast to
14841                 // its own runtime receiver, and there's no manifest receivers for it,
14842                 // because this method is called twice for each broadcast,
14843                 // for runtime receivers and manifest receivers and the later check would find
14844                 // no receivers.
14845                 return;
14846             }
14847             boolean allProtected = true;
14848             for (int i = receivers.size()-1; i >= 0; i--) {
14849                 Object target = receivers.get(i);
14850                 if (target instanceof ResolveInfo) {
14851                     ResolveInfo ri = (ResolveInfo)target;
14852                     if (ri.activityInfo.exported && ri.activityInfo.permission == null) {
14853                         allProtected = false;
14854                         break;
14855                     }
14856                 } else {
14857                     BroadcastFilter bf = (BroadcastFilter)target;
14858                     if (bf.requiredPermission == null) {
14859                         allProtected = false;
14860                         break;
14861                     }
14862                 }
14863             }
14864             if (allProtected) {
14865                 // All safe!
14866                 return;
14867             }
14868         }
14869 
14870         // The vast majority of broadcasts sent from system internals
14871         // should be protected to avoid security holes, so yell loudly
14872         // to ensure we examine these cases.
14873         if (callerApp != null) {
14874             Log.wtf(TAG, "Sending non-protected broadcast " + action
14875                             + " from system " + callerApp.toShortString() + " pkg " + callerPackage,
14876                     new Throwable());
14877         } else {
14878             Log.wtf(TAG, "Sending non-protected broadcast " + action
14879                             + " from system uid " + UserHandle.formatUid(callingUid)
14880                             + " pkg " + callerPackage,
14881                     new Throwable());
14882         }
14883     }
14884 
14885     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, 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)14886     final int broadcastIntentLocked(ProcessRecord callerApp,
14887             String callerPackage, Intent intent, String resolvedType,
14888             IIntentReceiver resultTo, int resultCode, String resultData,
14889             Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
14890             boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
14891             int realCallingPid, int userId) {
14892         return broadcastIntentLocked(callerApp, callerPackage, intent, resolvedType, resultTo,
14893             resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions, ordered,
14894             sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId,
14895             false /* allowBackgroundActivityStarts */);
14896     }
14897 
14898     @GuardedBy("this")
broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, 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)14899     final int broadcastIntentLocked(ProcessRecord callerApp,
14900             String callerPackage, Intent intent, String resolvedType,
14901             IIntentReceiver resultTo, int resultCode, String resultData,
14902             Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
14903             boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
14904             int realCallingPid, int userId, boolean allowBackgroundActivityStarts) {
14905         intent = new Intent(intent);
14906 
14907         final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
14908         // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
14909         if (callerInstantApp) {
14910             intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
14911         }
14912 
14913         // By default broadcasts do not go to stopped apps.
14914         intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
14915 
14916         // If we have not finished booting, don't allow this to launch new processes.
14917         if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
14918             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14919         }
14920 
14921         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
14922                 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
14923                 + " ordered=" + ordered + " userid=" + userId);
14924         if ((resultTo != null) && !ordered) {
14925             Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
14926         }
14927 
14928         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
14929                 ALLOW_NON_FULL, "broadcast", callerPackage);
14930 
14931         // Make sure that the user who is receiving this broadcast or its parent is running.
14932         // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
14933         if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
14934             if ((callingUid != SYSTEM_UID
14935                     || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)
14936                     && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
14937                 Slog.w(TAG, "Skipping broadcast of " + intent
14938                         + ": user " + userId + " and its parent (if any) are stopped");
14939                 return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
14940             }
14941         }
14942 
14943         final String action = intent.getAction();
14944         BroadcastOptions brOptions = null;
14945         if (bOptions != null) {
14946             brOptions = new BroadcastOptions(bOptions);
14947             if (brOptions.getTemporaryAppWhitelistDuration() > 0) {
14948                 // See if the caller is allowed to do this.  Note we are checking against
14949                 // the actual real caller (not whoever provided the operation as say a
14950                 // PendingIntent), because that who is actually supplied the arguments.
14951                 if (checkComponentPermission(
14952                         android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
14953                         realCallingPid, realCallingUid, -1, true)
14954                         != PackageManager.PERMISSION_GRANTED) {
14955                     String msg = "Permission Denial: " + intent.getAction()
14956                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14957                             + ", uid=" + callingUid + ")"
14958                             + " requires "
14959                             + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
14960                     Slog.w(TAG, msg);
14961                     throw new SecurityException(msg);
14962                 }
14963             }
14964             if (brOptions.isDontSendToRestrictedApps()
14965                     && !isUidActiveLocked(callingUid)
14966                     && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
14967                 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
14968                         + " has background restrictions");
14969                 return ActivityManager.START_CANCELED;
14970             }
14971             if (brOptions.allowsBackgroundActivityStarts()) {
14972                 // See if the caller is allowed to do this.  Note we are checking against
14973                 // the actual real caller (not whoever provided the operation as say a
14974                 // PendingIntent), because that who is actually supplied the arguments.
14975                 if (checkComponentPermission(
14976                         android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
14977                         realCallingPid, realCallingUid, -1, true)
14978                         != PackageManager.PERMISSION_GRANTED) {
14979                     String msg = "Permission Denial: " + intent.getAction()
14980                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14981                             + ", uid=" + callingUid + ")"
14982                             + " requires "
14983                             + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
14984                     Slog.w(TAG, msg);
14985                     throw new SecurityException(msg);
14986                 } else {
14987                     allowBackgroundActivityStarts = true;
14988                 }
14989             }
14990         }
14991 
14992         // Verify that protected broadcasts are only being sent by system code,
14993         // and that system code is only sending protected broadcasts.
14994         final boolean isProtectedBroadcast;
14995         try {
14996             isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
14997         } catch (RemoteException e) {
14998             Slog.w(TAG, "Remote exception", e);
14999             return ActivityManager.BROADCAST_SUCCESS;
15000         }
15001 
15002         final boolean isCallerSystem;
15003         switch (UserHandle.getAppId(callingUid)) {
15004             case ROOT_UID:
15005             case SYSTEM_UID:
15006             case PHONE_UID:
15007             case BLUETOOTH_UID:
15008             case NFC_UID:
15009             case SE_UID:
15010             case NETWORK_STACK_UID:
15011                 isCallerSystem = true;
15012                 break;
15013             default:
15014                 isCallerSystem = (callerApp != null) && callerApp.isPersistent();
15015                 break;
15016         }
15017 
15018         // First line security check before anything else: stop non-system apps from
15019         // sending protected broadcasts.
15020         if (!isCallerSystem) {
15021             if (isProtectedBroadcast) {
15022                 String msg = "Permission Denial: not allowed to send broadcast "
15023                         + action + " from pid="
15024                         + callingPid + ", uid=" + callingUid;
15025                 Slog.w(TAG, msg);
15026                 throw new SecurityException(msg);
15027 
15028             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
15029                     || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
15030                 // Special case for compatibility: we don't want apps to send this,
15031                 // but historically it has not been protected and apps may be using it
15032                 // to poke their own app widget.  So, instead of making it protected,
15033                 // just limit it to the caller.
15034                 if (callerPackage == null) {
15035                     String msg = "Permission Denial: not allowed to send broadcast "
15036                             + action + " from unknown caller.";
15037                     Slog.w(TAG, msg);
15038                     throw new SecurityException(msg);
15039                 } else if (intent.getComponent() != null) {
15040                     // They are good enough to send to an explicit component...  verify
15041                     // it is being sent to the calling app.
15042                     if (!intent.getComponent().getPackageName().equals(
15043                             callerPackage)) {
15044                         String msg = "Permission Denial: not allowed to send broadcast "
15045                                 + action + " to "
15046                                 + intent.getComponent().getPackageName() + " from "
15047                                 + callerPackage;
15048                         Slog.w(TAG, msg);
15049                         throw new SecurityException(msg);
15050                     }
15051                 } else {
15052                     // Limit broadcast to their own package.
15053                     intent.setPackage(callerPackage);
15054                 }
15055             }
15056         }
15057 
15058         boolean timeoutExempt = false;
15059 
15060         if (action != null) {
15061             if (getBackgroundLaunchBroadcasts().contains(action)) {
15062                 if (DEBUG_BACKGROUND_CHECK) {
15063                     Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
15064                 }
15065                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
15066             }
15067 
15068             switch (action) {
15069                 case Intent.ACTION_UID_REMOVED:
15070                 case Intent.ACTION_PACKAGE_REMOVED:
15071                 case Intent.ACTION_PACKAGE_CHANGED:
15072                 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
15073                 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
15074                 case Intent.ACTION_PACKAGES_SUSPENDED:
15075                 case Intent.ACTION_PACKAGES_UNSUSPENDED:
15076                     // Handle special intents: if this broadcast is from the package
15077                     // manager about a package being removed, we need to remove all of
15078                     // its activities from the history stack.
15079                     if (checkComponentPermission(
15080                             android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
15081                             callingPid, callingUid, -1, true)
15082                             != PackageManager.PERMISSION_GRANTED) {
15083                         String msg = "Permission Denial: " + intent.getAction()
15084                                 + " broadcast from " + callerPackage + " (pid=" + callingPid
15085                                 + ", uid=" + callingUid + ")"
15086                                 + " requires "
15087                                 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
15088                         Slog.w(TAG, msg);
15089                         throw new SecurityException(msg);
15090                     }
15091                     switch (action) {
15092                         case Intent.ACTION_UID_REMOVED:
15093                             final int uid = getUidFromIntent(intent);
15094                             if (uid >= 0) {
15095                                 mBatteryStatsService.removeUid(uid);
15096                                 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
15097                                     mAppOpsService.resetAllModes(UserHandle.getUserId(uid),
15098                                             intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME));
15099                                 } else {
15100                                     mAppOpsService.uidRemoved(uid);
15101                                 }
15102                             }
15103                             break;
15104                         case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
15105                             // If resources are unavailable just force stop all those packages
15106                             // and flush the attribute cache as well.
15107                             String list[] =
15108                                     intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15109                             if (list != null && list.length > 0) {
15110                                 for (int i = 0; i < list.length; i++) {
15111                                     forceStopPackageLocked(list[i], -1, false, true, true,
15112                                             false, false, userId, "storage unmount");
15113                                 }
15114                                 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
15115                                 sendPackageBroadcastLocked(
15116                                         ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
15117                                         list, userId);
15118                             }
15119                             break;
15120                         case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
15121                             mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
15122                             break;
15123                         case Intent.ACTION_PACKAGE_REMOVED:
15124                         case Intent.ACTION_PACKAGE_CHANGED:
15125                             Uri data = intent.getData();
15126                             String ssp;
15127                             if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
15128                                 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
15129                                 final boolean replacing =
15130                                         intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
15131                                 final boolean killProcess =
15132                                         !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
15133                                 final boolean fullUninstall = removed && !replacing;
15134                                 if (removed) {
15135                                     if (killProcess) {
15136                                         forceStopPackageLocked(ssp, UserHandle.getAppId(
15137                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
15138                                                 false, true, true, false, fullUninstall, userId,
15139                                                 removed ? "pkg removed" : "pkg changed");
15140                                     }
15141                                     final int cmd = killProcess
15142                                             ? ApplicationThreadConstants.PACKAGE_REMOVED
15143                                             : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
15144                                     sendPackageBroadcastLocked(cmd,
15145                                             new String[] {ssp}, userId);
15146                                     if (fullUninstall) {
15147                                         mAppOpsService.packageRemoved(
15148                                                 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
15149 
15150                                         // Remove all permissions granted from/to this package
15151                                         mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
15152                                                 true, false);
15153 
15154                                         mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
15155 
15156                                         mServices.forceStopPackageLocked(ssp, userId);
15157                                         mAtmInternal.onPackageUninstalled(ssp);
15158                                         mBatteryStatsService.notePackageUninstalled(ssp);
15159                                     }
15160                                 } else {
15161                                     if (killProcess) {
15162                                         final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
15163                                                 -1);
15164                                         mProcessList.killPackageProcessesLocked(ssp,
15165                                                 UserHandle.getAppId(extraUid),
15166                                                 userId, ProcessList.INVALID_ADJ, "change " + ssp);
15167                                     }
15168                                     cleanupDisabledPackageComponentsLocked(ssp, userId,
15169                                             intent.getStringArrayExtra(
15170                                                     Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
15171                                 }
15172                             }
15173                             break;
15174                         case Intent.ACTION_PACKAGES_SUSPENDED:
15175                         case Intent.ACTION_PACKAGES_UNSUSPENDED:
15176                             final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
15177                                     intent.getAction());
15178                             final String[] packageNames = intent.getStringArrayExtra(
15179                                     Intent.EXTRA_CHANGED_PACKAGE_LIST);
15180                             final int userHandle = intent.getIntExtra(
15181                                     Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
15182 
15183                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
15184                                     userHandle);
15185                             break;
15186                     }
15187                     break;
15188                 case Intent.ACTION_PACKAGE_REPLACED:
15189                 {
15190                     final Uri data = intent.getData();
15191                     final String ssp;
15192                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
15193                         ApplicationInfo aInfo = null;
15194                         try {
15195                             aInfo = AppGlobals.getPackageManager()
15196                                     .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
15197                         } catch (RemoteException ignore) {}
15198                         if (aInfo == null) {
15199                             Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
15200                                     + " ssp=" + ssp + " data=" + data);
15201                             return ActivityManager.BROADCAST_SUCCESS;
15202                         }
15203                         updateAssociationForApp(aInfo);
15204                         mAtmInternal.onPackageReplaced(aInfo);
15205                         mServices.updateServiceApplicationInfoLocked(aInfo);
15206                         sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
15207                                 new String[] {ssp}, userId);
15208                     }
15209                     break;
15210                 }
15211                 case Intent.ACTION_PACKAGE_ADDED:
15212                 {
15213                     // Special case for adding a package: by default turn on compatibility mode.
15214                     Uri data = intent.getData();
15215                     String ssp;
15216                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
15217                         final boolean replacing =
15218                                 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
15219                         mAtmInternal.onPackageAdded(ssp, replacing);
15220 
15221                         try {
15222                             ApplicationInfo ai = AppGlobals.getPackageManager().
15223                                     getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
15224                             mBatteryStatsService.notePackageInstalled(ssp,
15225                                     ai != null ? ai.longVersionCode : 0);
15226                         } catch (RemoteException e) {
15227                         }
15228                     }
15229                     break;
15230                 }
15231                 case Intent.ACTION_PACKAGE_DATA_CLEARED:
15232                 {
15233                     Uri data = intent.getData();
15234                     String ssp;
15235                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
15236                         mAtmInternal.onPackageDataCleared(ssp);
15237                     }
15238                     break;
15239                 }
15240                 case Intent.ACTION_TIMEZONE_CHANGED:
15241                     // If this is the time zone changed action, queue up a message that will reset
15242                     // the timezone of all currently running processes. This message will get
15243                     // queued up before the broadcast happens.
15244                     mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
15245                     break;
15246                 case Intent.ACTION_TIME_CHANGED:
15247                     // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
15248                     // the tri-state value it may contain and "unknown".
15249                     // For convenience we re-use the Intent extra values.
15250                     final int NO_EXTRA_VALUE_FOUND = -1;
15251                     final int timeFormatPreferenceMsgValue = intent.getIntExtra(
15252                             Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
15253                             NO_EXTRA_VALUE_FOUND /* defaultValue */);
15254                     // Only send a message if the time preference is available.
15255                     if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
15256                         Message updateTimePreferenceMsg =
15257                                 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
15258                                         timeFormatPreferenceMsgValue, 0);
15259                         mHandler.sendMessage(updateTimePreferenceMsg);
15260                     }
15261                     BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
15262                     synchronized (stats) {
15263                         stats.noteCurrentTimeChangedLocked();
15264                     }
15265                     break;
15266                 case Intent.ACTION_CLEAR_DNS_CACHE:
15267                     mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
15268                     break;
15269                 case Proxy.PROXY_CHANGE_ACTION:
15270                     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
15271                     break;
15272                 case android.hardware.Camera.ACTION_NEW_PICTURE:
15273                 case android.hardware.Camera.ACTION_NEW_VIDEO:
15274                     // In N we just turned these off; in O we are turing them back on partly,
15275                     // only for registered receivers.  This will still address the main problem
15276                     // (a spam of apps waking up when a picture is taken putting significant
15277                     // memory pressure on the system at a bad point), while still allowing apps
15278                     // that are already actively running to know about this happening.
15279                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15280                     break;
15281                 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
15282                     mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
15283                     break;
15284                 case "com.android.launcher.action.INSTALL_SHORTCUT":
15285                     // As of O, we no longer support this broadcasts, even for pre-O apps.
15286                     // Apps should now be using ShortcutManager.pinRequestShortcut().
15287                     Log.w(TAG, "Broadcast " + action
15288                             + " no longer supported. It will not be delivered.");
15289                     return ActivityManager.BROADCAST_SUCCESS;
15290                 case Intent.ACTION_PRE_BOOT_COMPLETED:
15291                     timeoutExempt = true;
15292                     break;
15293             }
15294 
15295             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
15296                     Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
15297                     Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
15298                 final int uid = getUidFromIntent(intent);
15299                 if (uid != -1) {
15300                     final UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
15301                     if (uidRec != null) {
15302                         uidRec.updateHasInternetPermission();
15303                     }
15304                 }
15305             }
15306         }
15307 
15308         // Add to the sticky list if requested.
15309         if (sticky) {
15310             if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
15311                     callingPid, callingUid)
15312                     != PackageManager.PERMISSION_GRANTED) {
15313                 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
15314                         + callingPid + ", uid=" + callingUid
15315                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15316                 Slog.w(TAG, msg);
15317                 throw new SecurityException(msg);
15318             }
15319             if (requiredPermissions != null && requiredPermissions.length > 0) {
15320                 Slog.w(TAG, "Can't broadcast sticky intent " + intent
15321                         + " and enforce permissions " + Arrays.toString(requiredPermissions));
15322                 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
15323             }
15324             if (intent.getComponent() != null) {
15325                 throw new SecurityException(
15326                         "Sticky broadcasts can't target a specific component");
15327             }
15328             // We use userId directly here, since the "all" target is maintained
15329             // as a separate set of sticky broadcasts.
15330             if (userId != UserHandle.USER_ALL) {
15331                 // But first, if this is not a broadcast to all users, then
15332                 // make sure it doesn't conflict with an existing broadcast to
15333                 // all users.
15334                 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
15335                         UserHandle.USER_ALL);
15336                 if (stickies != null) {
15337                     ArrayList<Intent> list = stickies.get(intent.getAction());
15338                     if (list != null) {
15339                         int N = list.size();
15340                         int i;
15341                         for (i=0; i<N; i++) {
15342                             if (intent.filterEquals(list.get(i))) {
15343                                 throw new IllegalArgumentException(
15344                                         "Sticky broadcast " + intent + " for user "
15345                                         + userId + " conflicts with existing global broadcast");
15346                             }
15347                         }
15348                     }
15349                 }
15350             }
15351             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
15352             if (stickies == null) {
15353                 stickies = new ArrayMap<>();
15354                 mStickyBroadcasts.put(userId, stickies);
15355             }
15356             ArrayList<Intent> list = stickies.get(intent.getAction());
15357             if (list == null) {
15358                 list = new ArrayList<>();
15359                 stickies.put(intent.getAction(), list);
15360             }
15361             final int stickiesCount = list.size();
15362             int i;
15363             for (i = 0; i < stickiesCount; i++) {
15364                 if (intent.filterEquals(list.get(i))) {
15365                     // This sticky already exists, replace it.
15366                     list.set(i, new Intent(intent));
15367                     break;
15368                 }
15369             }
15370             if (i >= stickiesCount) {
15371                 list.add(new Intent(intent));
15372             }
15373         }
15374 
15375         int[] users;
15376         if (userId == UserHandle.USER_ALL) {
15377             // Caller wants broadcast to go to all started users.
15378             users = mUserController.getStartedUserArray();
15379         } else {
15380             // Caller wants broadcast to go to one specific user.
15381             users = new int[] {userId};
15382         }
15383 
15384         // Figure out who all will receive this broadcast.
15385         List receivers = null;
15386         List<BroadcastFilter> registeredReceivers = null;
15387         // Need to resolve the intent to interested receivers...
15388         if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
15389                  == 0) {
15390             receivers = collectReceiverComponents(intent, resolvedType, callingUid, users);
15391         }
15392         if (intent.getComponent() == null) {
15393             if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
15394                 // Query one target user at a time, excluding shell-restricted users
15395                 for (int i = 0; i < users.length; i++) {
15396                     if (mUserController.hasUserRestriction(
15397                             UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
15398                         continue;
15399                     }
15400                     List<BroadcastFilter> registeredReceiversForUser =
15401                             mReceiverResolver.queryIntent(intent,
15402                                     resolvedType, false /*defaultOnly*/, users[i]);
15403                     if (registeredReceivers == null) {
15404                         registeredReceivers = registeredReceiversForUser;
15405                     } else if (registeredReceiversForUser != null) {
15406                         registeredReceivers.addAll(registeredReceiversForUser);
15407                     }
15408                 }
15409             } else {
15410                 registeredReceivers = mReceiverResolver.queryIntent(intent,
15411                         resolvedType, false /*defaultOnly*/, userId);
15412             }
15413         }
15414 
15415         final boolean replacePending =
15416                 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
15417 
15418         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
15419                 + " replacePending=" + replacePending);
15420 
15421         int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
15422         if (!ordered && NR > 0) {
15423             // If we are not serializing this broadcast, then send the
15424             // registered receivers separately so they don't wait for the
15425             // components to be launched.
15426             if (isCallerSystem) {
15427                 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15428                         isProtectedBroadcast, registeredReceivers);
15429             }
15430             final BroadcastQueue queue = broadcastQueueForIntent(intent);
15431             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
15432                     callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
15433                     requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
15434                     resultCode, resultData, resultExtras, ordered, sticky, false, userId,
15435                     allowBackgroundActivityStarts, timeoutExempt);
15436             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
15437             final boolean replaced = replacePending
15438                     && (queue.replaceParallelBroadcastLocked(r) != null);
15439             // Note: We assume resultTo is null for non-ordered broadcasts.
15440             if (!replaced) {
15441                 queue.enqueueParallelBroadcastLocked(r);
15442                 queue.scheduleBroadcastsLocked();
15443             }
15444             registeredReceivers = null;
15445             NR = 0;
15446         }
15447 
15448         // Merge into one list.
15449         int ir = 0;
15450         if (receivers != null) {
15451             // A special case for PACKAGE_ADDED: do not allow the package
15452             // being added to see this broadcast.  This prevents them from
15453             // using this as a back door to get run as soon as they are
15454             // installed.  Maybe in the future we want to have a special install
15455             // broadcast or such for apps, but we'd like to deliberately make
15456             // this decision.
15457             String skipPackages[] = null;
15458             if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
15459                     || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
15460                     || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
15461                 Uri data = intent.getData();
15462                 if (data != null) {
15463                     String pkgName = data.getSchemeSpecificPart();
15464                     if (pkgName != null) {
15465                         skipPackages = new String[] { pkgName };
15466                     }
15467                 }
15468             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
15469                 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15470             }
15471             if (skipPackages != null && (skipPackages.length > 0)) {
15472                 for (String skipPackage : skipPackages) {
15473                     if (skipPackage != null) {
15474                         int NT = receivers.size();
15475                         for (int it=0; it<NT; it++) {
15476                             ResolveInfo curt = (ResolveInfo)receivers.get(it);
15477                             if (curt.activityInfo.packageName.equals(skipPackage)) {
15478                                 receivers.remove(it);
15479                                 it--;
15480                                 NT--;
15481                             }
15482                         }
15483                     }
15484                 }
15485             }
15486 
15487             int NT = receivers != null ? receivers.size() : 0;
15488             int it = 0;
15489             ResolveInfo curt = null;
15490             BroadcastFilter curr = null;
15491             while (it < NT && ir < NR) {
15492                 if (curt == null) {
15493                     curt = (ResolveInfo)receivers.get(it);
15494                 }
15495                 if (curr == null) {
15496                     curr = registeredReceivers.get(ir);
15497                 }
15498                 if (curr.getPriority() >= curt.priority) {
15499                     // Insert this broadcast record into the final list.
15500                     receivers.add(it, curr);
15501                     ir++;
15502                     curr = null;
15503                     it++;
15504                     NT++;
15505                 } else {
15506                     // Skip to the next ResolveInfo in the final list.
15507                     it++;
15508                     curt = null;
15509                 }
15510             }
15511         }
15512         while (ir < NR) {
15513             if (receivers == null) {
15514                 receivers = new ArrayList();
15515             }
15516             receivers.add(registeredReceivers.get(ir));
15517             ir++;
15518         }
15519 
15520         if (isCallerSystem) {
15521             checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15522                     isProtectedBroadcast, receivers);
15523         }
15524 
15525         if ((receivers != null && receivers.size() > 0)
15526                 || resultTo != null) {
15527             BroadcastQueue queue = broadcastQueueForIntent(intent);
15528             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
15529                     callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
15530                     requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
15531                     resultData, resultExtras, ordered, sticky, false, userId,
15532                     allowBackgroundActivityStarts, timeoutExempt);
15533 
15534             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
15535 
15536             final BroadcastRecord oldRecord =
15537                     replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
15538             if (oldRecord != null) {
15539                 // Replaced, fire the result-to receiver.
15540                 if (oldRecord.resultTo != null) {
15541                     final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
15542                     try {
15543                         oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
15544                                 oldRecord.intent,
15545                                 Activity.RESULT_CANCELED, null, null,
15546                                 false, false, oldRecord.userId);
15547                     } catch (RemoteException e) {
15548                         Slog.w(TAG, "Failure ["
15549                                 + queue.mQueueName + "] sending broadcast result of "
15550                                 + intent, e);
15551 
15552                     }
15553                 }
15554             } else {
15555                 queue.enqueueOrderedBroadcastLocked(r);
15556                 queue.scheduleBroadcastsLocked();
15557             }
15558         } else {
15559             // There was nobody interested in the broadcast, but we still want to record
15560             // that it happened.
15561             if (intent.getComponent() == null && intent.getPackage() == null
15562                     && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15563                 // This was an implicit broadcast... let's record it for posterity.
15564                 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
15565             }
15566         }
15567 
15568         return ActivityManager.BROADCAST_SUCCESS;
15569     }
15570 
15571     /**
15572      * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1
15573      */
getUidFromIntent(Intent intent)15574     private int getUidFromIntent(Intent intent) {
15575         if (intent == null) {
15576             return -1;
15577         }
15578         final Bundle intentExtras = intent.getExtras();
15579         return intent.hasExtra(Intent.EXTRA_UID)
15580                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
15581     }
15582 
rotateBroadcastStatsIfNeededLocked()15583     final void rotateBroadcastStatsIfNeededLocked() {
15584         final long now = SystemClock.elapsedRealtime();
15585         if (mCurBroadcastStats == null ||
15586                 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) {
15587             mLastBroadcastStats = mCurBroadcastStats;
15588             if (mLastBroadcastStats != null) {
15589                 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime();
15590                 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis();
15591             }
15592             mCurBroadcastStats = new BroadcastStats();
15593         }
15594     }
15595 
addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)15596     final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount,
15597             int skipCount, long dispatchTime) {
15598         rotateBroadcastStatsIfNeededLocked();
15599         mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime);
15600     }
15601 
addBackgroundCheckViolationLocked(String action, String targetPackage)15602     final void addBackgroundCheckViolationLocked(String action, String targetPackage) {
15603         rotateBroadcastStatsIfNeededLocked();
15604         mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage);
15605     }
15606 
verifyBroadcastLocked(Intent intent)15607     final Intent verifyBroadcastLocked(Intent intent) {
15608         // Refuse possible leaked file descriptors
15609         if (intent != null && intent.hasFileDescriptors() == true) {
15610             throw new IllegalArgumentException("File descriptors passed in Intent");
15611         }
15612 
15613         int flags = intent.getFlags();
15614 
15615         if (!mProcessesReady) {
15616             // if the caller really truly claims to know what they're doing, go
15617             // ahead and allow the broadcast without launching any receivers
15618             if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
15619                 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
15620             } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15621                 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
15622                         + " before boot completion");
15623                 throw new IllegalStateException("Cannot broadcast before boot completed");
15624             }
15625         }
15626 
15627         if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
15628             throw new IllegalArgumentException(
15629                     "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
15630         }
15631 
15632         if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
15633             switch (Binder.getCallingUid()) {
15634                 case ROOT_UID:
15635                 case SHELL_UID:
15636                     break;
15637                 default:
15638                     Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
15639                             + Binder.getCallingUid());
15640                     intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
15641                     break;
15642             }
15643         }
15644 
15645         return intent;
15646     }
15647 
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)15648     public final int broadcastIntent(IApplicationThread caller,
15649             Intent intent, String resolvedType, IIntentReceiver resultTo,
15650             int resultCode, String resultData, Bundle resultExtras,
15651             String[] requiredPermissions, int appOp, Bundle bOptions,
15652             boolean serialized, boolean sticky, int userId) {
15653         enforceNotIsolatedCaller("broadcastIntent");
15654         synchronized(this) {
15655             intent = verifyBroadcastLocked(intent);
15656 
15657             final ProcessRecord callerApp = getRecordForAppLocked(caller);
15658             final int callingPid = Binder.getCallingPid();
15659             final int callingUid = Binder.getCallingUid();
15660 
15661             final long origId = Binder.clearCallingIdentity();
15662             try {
15663                 return broadcastIntentLocked(callerApp,
15664                         callerApp != null ? callerApp.info.packageName : null,
15665                         intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
15666                         requiredPermissions, appOp, bOptions, serialized, sticky,
15667                         callingPid, callingUid, callingUid, callingPid, userId);
15668             } finally {
15669                 Binder.restoreCallingIdentity(origId);
15670             }
15671         }
15672     }
15673 
broadcastIntentInPackage(String packageName, 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)15674     int broadcastIntentInPackage(String packageName, int uid, int realCallingUid,
15675             int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo,
15676             int resultCode, String resultData, Bundle resultExtras,
15677             String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky,
15678             int userId, boolean allowBackgroundActivityStarts) {
15679         synchronized(this) {
15680             intent = verifyBroadcastLocked(intent);
15681 
15682             final long origId = Binder.clearCallingIdentity();
15683             String[] requiredPermissions = requiredPermission == null ? null
15684                     : new String[] {requiredPermission};
15685             try {
15686                 return broadcastIntentLocked(null, packageName, intent, resolvedType,
15687                         resultTo, resultCode, resultData, resultExtras,
15688                         requiredPermissions, OP_NONE, bOptions, serialized,
15689                         sticky, -1, uid, realCallingUid, realCallingPid, userId,
15690                         allowBackgroundActivityStarts);
15691             } finally {
15692                 Binder.restoreCallingIdentity(origId);
15693             }
15694         }
15695     }
15696 
unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)15697     public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
15698         // Refuse possible leaked file descriptors
15699         if (intent != null && intent.hasFileDescriptors() == true) {
15700             throw new IllegalArgumentException("File descriptors passed in Intent");
15701         }
15702 
15703         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15704                 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
15705 
15706         synchronized(this) {
15707             if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
15708                     != PackageManager.PERMISSION_GRANTED) {
15709                 String msg = "Permission Denial: unbroadcastIntent() from pid="
15710                         + Binder.getCallingPid()
15711                         + ", uid=" + Binder.getCallingUid()
15712                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15713                 Slog.w(TAG, msg);
15714                 throw new SecurityException(msg);
15715             }
15716             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
15717             if (stickies != null) {
15718                 ArrayList<Intent> list = stickies.get(intent.getAction());
15719                 if (list != null) {
15720                     int N = list.size();
15721                     int i;
15722                     for (i=0; i<N; i++) {
15723                         if (intent.filterEquals(list.get(i))) {
15724                             list.remove(i);
15725                             break;
15726                         }
15727                     }
15728                     if (list.size() <= 0) {
15729                         stickies.remove(intent.getAction());
15730                     }
15731                 }
15732                 if (stickies.size() <= 0) {
15733                     mStickyBroadcasts.remove(userId);
15734                 }
15735             }
15736         }
15737     }
15738 
backgroundServicesFinishedLocked(int userId)15739     void backgroundServicesFinishedLocked(int userId) {
15740         for (BroadcastQueue queue : mBroadcastQueues) {
15741             queue.backgroundServicesFinishedLocked(userId);
15742         }
15743     }
15744 
finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)15745     public void finishReceiver(IBinder who, int resultCode, String resultData,
15746             Bundle resultExtras, boolean resultAbort, int flags) {
15747         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who);
15748 
15749         // Refuse possible leaked file descriptors
15750         if (resultExtras != null && resultExtras.hasFileDescriptors()) {
15751             throw new IllegalArgumentException("File descriptors passed in Bundle");
15752         }
15753 
15754         final long origId = Binder.clearCallingIdentity();
15755         try {
15756             boolean doNext = false;
15757             BroadcastRecord r;
15758             BroadcastQueue queue;
15759 
15760             synchronized(this) {
15761                 if (isOnOffloadQueue(flags)) {
15762                     queue = mOffloadBroadcastQueue;
15763                 } else {
15764                     queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0
15765                             ? mFgBroadcastQueue : mBgBroadcastQueue;
15766                 }
15767 
15768                 r = queue.getMatchingOrderedReceiver(who);
15769                 if (r != null) {
15770                     doNext = r.queue.finishReceiverLocked(r, resultCode,
15771                         resultData, resultExtras, resultAbort, true);
15772                 }
15773                 if (doNext) {
15774                     r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true);
15775                 }
15776                 // updateOomAdjLocked() will be done here
15777                 trimApplicationsLocked(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
15778             }
15779 
15780         } finally {
15781             Binder.restoreCallingIdentity(origId);
15782         }
15783     }
15784 
15785     // =========================================================
15786     // INSTRUMENTATION
15787     // =========================================================
15788 
startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)15789     public boolean startInstrumentation(ComponentName className,
15790             String profileFile, int flags, Bundle arguments,
15791             IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
15792             int userId, String abiOverride) {
15793         enforceNotIsolatedCaller("startInstrumentation");
15794         final int callingUid = Binder.getCallingUid();
15795         final int callingPid = Binder.getCallingPid();
15796         userId = mUserController.handleIncomingUser(callingPid, callingUid,
15797                 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
15798         // Refuse possible leaked file descriptors
15799         if (arguments != null && arguments.hasFileDescriptors()) {
15800             throw new IllegalArgumentException("File descriptors passed in Bundle");
15801         }
15802 
15803         synchronized(this) {
15804             InstrumentationInfo ii = null;
15805             ApplicationInfo ai = null;
15806             try {
15807                 ii = mContext.getPackageManager().getInstrumentationInfo(
15808                     className, STOCK_PM_FLAGS);
15809                 ai = AppGlobals.getPackageManager().getApplicationInfo(
15810                         ii.targetPackage, STOCK_PM_FLAGS, userId);
15811             } catch (PackageManager.NameNotFoundException e) {
15812             } catch (RemoteException e) {
15813             }
15814             if (ii == null) {
15815                 reportStartInstrumentationFailureLocked(watcher, className,
15816                         "Unable to find instrumentation info for: " + className);
15817                 return false;
15818             }
15819             if (ai == null) {
15820                 reportStartInstrumentationFailureLocked(watcher, className,
15821                         "Unable to find instrumentation target package: " + ii.targetPackage);
15822                 return false;
15823             }
15824             if (!ai.hasCode()) {
15825                 reportStartInstrumentationFailureLocked(watcher, className,
15826                         "Instrumentation target has no code: " + ii.targetPackage);
15827                 return false;
15828             }
15829 
15830             int match = mContext.getPackageManager().checkSignatures(
15831                     ii.targetPackage, ii.packageName);
15832             if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
15833                 String msg = "Permission Denial: starting instrumentation "
15834                         + className + " from pid="
15835                         + Binder.getCallingPid()
15836                         + ", uid=" + Binder.getCallingPid()
15837                         + " not allowed because package " + ii.packageName
15838                         + " does not have a signature matching the target "
15839                         + ii.targetPackage;
15840                 reportStartInstrumentationFailureLocked(watcher, className, msg);
15841                 throw new SecurityException(msg);
15842             }
15843 
15844             ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
15845             activeInstr.mClass = className;
15846             String defProcess = ai.processName;;
15847             if (ii.targetProcesses == null) {
15848                 activeInstr.mTargetProcesses = new String[]{ai.processName};
15849             } else if (ii.targetProcesses.equals("*")) {
15850                 activeInstr.mTargetProcesses = new String[0];
15851             } else {
15852                 activeInstr.mTargetProcesses = ii.targetProcesses.split(",");
15853                 defProcess = activeInstr.mTargetProcesses[0];
15854             }
15855             activeInstr.mTargetInfo = ai;
15856             activeInstr.mProfileFile = profileFile;
15857             activeInstr.mArguments = arguments;
15858             activeInstr.mWatcher = watcher;
15859             activeInstr.mUiAutomationConnection = uiAutomationConnection;
15860             activeInstr.mResultClass = className;
15861             activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
15862                     START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
15863                             == PackageManager.PERMISSION_GRANTED;
15864 
15865             boolean disableHiddenApiChecks = ai.usesNonSdkApi()
15866                     || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
15867             boolean disableTestApiChecks = disableHiddenApiChecks
15868                     || (flags & INSTR_FLAG_DISABLE_TEST_API_CHECKS) != 0;
15869             if (disableHiddenApiChecks || disableTestApiChecks) {
15870                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
15871                         "disable hidden API checks");
15872             }
15873 
15874             final boolean mountExtStorageFull = isCallerShell()
15875                     && (flags & INSTR_FLAG_MOUNT_EXTERNAL_STORAGE_FULL) != 0;
15876 
15877             final long origId = Binder.clearCallingIdentity();
15878             // Instrumentation can kill and relaunch even persistent processes
15879             forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId,
15880                     "start instr");
15881             // Inform usage stats to make the target package active
15882             if (mUsageStatsService != null) {
15883                 mUsageStatsService.reportEvent(ii.targetPackage, userId,
15884                         UsageEvents.Event.SYSTEM_INTERACTION);
15885             }
15886 
15887             ProcessRecord app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks,
15888                     disableTestApiChecks, mountExtStorageFull, abiOverride,
15889                     ZYGOTE_POLICY_FLAG_EMPTY);
15890             app.setActiveInstrumentation(activeInstr);
15891             activeInstr.mFinished = false;
15892             activeInstr.mRunningProcesses.add(app);
15893             if (!mActiveInstrumentation.contains(activeInstr)) {
15894                 mActiveInstrumentation.add(activeInstr);
15895             }
15896             Binder.restoreCallingIdentity(origId);
15897         }
15898 
15899         return true;
15900     }
15901 
isCallerShell()15902     private boolean isCallerShell() {
15903         final int callingUid = Binder.getCallingUid();
15904         return callingUid == SHELL_UID || callingUid == ROOT_UID;
15905     }
15906 
15907     /**
15908      * Report errors that occur while attempting to start Instrumentation.  Always writes the
15909      * error to the logs, but if somebody is watching, send the report there too.  This enables
15910      * the "am" command to report errors with more information.
15911      *
15912      * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
15913      * @param cn The component name of the instrumentation.
15914      * @param report The error report.
15915      */
reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)15916     private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher,
15917             ComponentName cn, String report) {
15918         Slog.w(TAG, report);
15919         if (watcher != null) {
15920             Bundle results = new Bundle();
15921             results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
15922             results.putString("Error", report);
15923             mInstrumentationReporter.reportStatus(watcher, cn, -1, results);
15924         }
15925     }
15926 
addInstrumentationResultsLocked(ProcessRecord app, Bundle results)15927     void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) {
15928         final ActiveInstrumentation instr = app.getActiveInstrumentation();
15929         if (instr == null) {
15930             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15931             return;
15932         }
15933 
15934         if (!instr.mFinished && results != null) {
15935             if (instr.mCurResults == null) {
15936                 instr.mCurResults = new Bundle(results);
15937             } else {
15938                 instr.mCurResults.putAll(results);
15939             }
15940         }
15941     }
15942 
addInstrumentationResults(IApplicationThread target, Bundle results)15943     public void addInstrumentationResults(IApplicationThread target, Bundle results) {
15944         int userId = UserHandle.getCallingUserId();
15945         // Refuse possible leaked file descriptors
15946         if (results != null && results.hasFileDescriptors()) {
15947             throw new IllegalArgumentException("File descriptors passed in Intent");
15948         }
15949 
15950         synchronized(this) {
15951             ProcessRecord app = getRecordForAppLocked(target);
15952             if (app == null) {
15953                 Slog.w(TAG, "addInstrumentationResults: no app for " + target);
15954                 return;
15955             }
15956             final long origId = Binder.clearCallingIdentity();
15957             addInstrumentationResultsLocked(app, results);
15958             Binder.restoreCallingIdentity(origId);
15959         }
15960     }
15961 
15962     @GuardedBy("this")
finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)15963     void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
15964         final ActiveInstrumentation instr = app.getActiveInstrumentation();
15965         if (instr == null) {
15966             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15967             return;
15968         }
15969 
15970         if (!instr.mFinished) {
15971             if (instr.mWatcher != null) {
15972                 Bundle finalResults = instr.mCurResults;
15973                 if (finalResults != null) {
15974                     if (instr.mCurResults != null && results != null) {
15975                         finalResults.putAll(results);
15976                     }
15977                 } else {
15978                     finalResults = results;
15979                 }
15980                 mInstrumentationReporter.reportFinished(instr.mWatcher,
15981                         instr.mClass, resultCode, finalResults);
15982             }
15983 
15984             // Can't call out of the system process with a lock held, so post a message.
15985             if (instr.mUiAutomationConnection != null) {
15986                 mAppOpsService.setAppOpsServiceDelegate(null);
15987                 getPackageManagerInternalLocked().setCheckPermissionDelegate(null);
15988                 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
15989                         instr.mUiAutomationConnection).sendToTarget();
15990             }
15991             instr.mFinished = true;
15992         }
15993 
15994         instr.removeProcess(app);
15995         app.setActiveInstrumentation(null);
15996 
15997         forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId,
15998                 "finished inst");
15999     }
16000 
finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)16001     public void finishInstrumentation(IApplicationThread target,
16002             int resultCode, Bundle results) {
16003         int userId = UserHandle.getCallingUserId();
16004         // Refuse possible leaked file descriptors
16005         if (results != null && results.hasFileDescriptors()) {
16006             throw new IllegalArgumentException("File descriptors passed in Intent");
16007         }
16008 
16009         synchronized(this) {
16010             ProcessRecord app = getRecordForAppLocked(target);
16011             if (app == null) {
16012                 Slog.w(TAG, "finishInstrumentation: no app for " + target);
16013                 return;
16014             }
16015             final long origId = Binder.clearCallingIdentity();
16016             finishInstrumentationLocked(app, resultCode, results);
16017             Binder.restoreCallingIdentity(origId);
16018         }
16019     }
16020 
16021     @Override
getFocusedStackInfo()16022     public StackInfo getFocusedStackInfo() throws RemoteException {
16023         return mActivityTaskManager.getFocusedStackInfo();
16024     }
16025 
16026     @Override
getConfiguration()16027     public Configuration getConfiguration() {
16028         return mActivityTaskManager.getConfiguration();
16029     }
16030 
16031     @Override
suppressResizeConfigChanges(boolean suppress)16032     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
16033         mActivityTaskManager.suppressResizeConfigChanges(suppress);
16034     }
16035 
16036     @Override
updatePersistentConfiguration(Configuration values)16037     public void updatePersistentConfiguration(Configuration values) {
16038         enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
16039         enforceWriteSettingsPermission("updatePersistentConfiguration()");
16040         if (values == null) {
16041             throw new NullPointerException("Configuration must not be null");
16042         }
16043 
16044         int userId = UserHandle.getCallingUserId();
16045 
16046         mActivityTaskManager.updatePersistentConfiguration(values, userId);
16047     }
16048 
enforceWriteSettingsPermission(String func)16049     private void enforceWriteSettingsPermission(String func) {
16050         int uid = Binder.getCallingUid();
16051         if (uid == ROOT_UID) {
16052             return;
16053         }
16054 
16055         if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
16056                 Settings.getPackageNameForUid(mContext, uid), false)) {
16057             return;
16058         }
16059 
16060         String msg = "Permission Denial: " + func + " from pid="
16061                 + Binder.getCallingPid()
16062                 + ", uid=" + uid
16063                 + " requires " + android.Manifest.permission.WRITE_SETTINGS;
16064         Slog.w(TAG, msg);
16065         throw new SecurityException(msg);
16066     }
16067 
16068     @Override
updateConfiguration(Configuration values)16069     public boolean updateConfiguration(Configuration values) {
16070         return mActivityTaskManager.updateConfiguration(values);
16071     }
16072 
16073     @Override
updateMccMncConfiguration(String mcc, String mnc)16074     public boolean updateMccMncConfiguration(String mcc, String mnc) {
16075         int mccInt, mncInt;
16076         try {
16077             mccInt = Integer.parseInt(mcc);
16078             mncInt = Integer.parseInt(mnc);
16079         } catch (NumberFormatException | StringIndexOutOfBoundsException ex) {
16080             Slog.e(TAG, "Error parsing mcc: " + mcc + " mnc: " + mnc + ". ex=" + ex);
16081             return false;
16082         }
16083         Configuration config = new Configuration();
16084         config.mcc = mccInt;
16085         config.mnc = mncInt == 0 ? Configuration.MNC_ZERO : mncInt;
16086         return mActivityTaskManager.updateConfiguration(config);
16087     }
16088 
16089     @Override
getLaunchedFromUid(IBinder activityToken)16090     public int getLaunchedFromUid(IBinder activityToken) {
16091         return mActivityTaskManager.getLaunchedFromUid(activityToken);
16092     }
16093 
getLaunchedFromPackage(IBinder activityToken)16094     public String getLaunchedFromPackage(IBinder activityToken) {
16095         return mActivityTaskManager.getLaunchedFromPackage(activityToken);
16096     }
16097 
16098     // =========================================================
16099     // LIFETIME MANAGEMENT
16100     // =========================================================
16101 
16102     // Returns whether the app is receiving broadcast.
16103     // If receiving, fetch all broadcast queues which the app is
16104     // the current [or imminent] receiver on.
isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)16105     boolean isReceivingBroadcastLocked(ProcessRecord app,
16106             ArraySet<BroadcastQueue> receivingQueues) {
16107         final int N = app.curReceivers.size();
16108         if (N > 0) {
16109             for (int i = 0; i < N; i++) {
16110                 receivingQueues.add(app.curReceivers.valueAt(i).queue);
16111             }
16112             return true;
16113         }
16114 
16115         // It's not the current receiver, but it might be starting up to become one
16116         for (BroadcastQueue queue : mBroadcastQueues) {
16117             final BroadcastRecord r = queue.mPendingBroadcast;
16118             if (r != null && r.curApp == app) {
16119                 // found it; report which queue it's in
16120                 receivingQueues.add(queue);
16121             }
16122         }
16123 
16124         return !receivingQueues.isEmpty();
16125     }
16126 
startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16127     Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState,
16128             int targetUid, long targetVersionCode, ComponentName targetComponent,
16129             String targetProcess) {
16130         if (!mTrackingAssociations) {
16131             return null;
16132         }
16133         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16134                 = mAssociations.get(targetUid);
16135         if (components == null) {
16136             components = new ArrayMap<>();
16137             mAssociations.put(targetUid, components);
16138         }
16139         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16140         if (sourceUids == null) {
16141             sourceUids = new SparseArray<>();
16142             components.put(targetComponent, sourceUids);
16143         }
16144         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16145         if (sourceProcesses == null) {
16146             sourceProcesses = new ArrayMap<>();
16147             sourceUids.put(sourceUid, sourceProcesses);
16148         }
16149         Association ass = sourceProcesses.get(sourceProcess);
16150         if (ass == null) {
16151             ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent,
16152                     targetProcess);
16153             sourceProcesses.put(sourceProcess, ass);
16154         }
16155         ass.mCount++;
16156         ass.mNesting++;
16157         if (ass.mNesting == 1) {
16158             ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis();
16159             ass.mLastState = sourceState;
16160         }
16161         return ass;
16162     }
16163 
stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16164     void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid,
16165             long targetVersionCode, ComponentName targetComponent, String targetProcess) {
16166         if (!mTrackingAssociations) {
16167             return;
16168         }
16169         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16170                 = mAssociations.get(targetUid);
16171         if (components == null) {
16172             return;
16173         }
16174         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16175         if (sourceUids == null) {
16176             return;
16177         }
16178         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16179         if (sourceProcesses == null) {
16180             return;
16181         }
16182         Association ass = sourceProcesses.get(sourceProcess);
16183         if (ass == null || ass.mNesting <= 0) {
16184             return;
16185         }
16186         ass.mNesting--;
16187         if (ass.mNesting == 0) {
16188             long uptime = SystemClock.uptimeMillis();
16189             ass.mTime += uptime - ass.mStartTime;
16190             ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16191                     += uptime - ass.mLastStateUptime;
16192             ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2;
16193         }
16194     }
16195 
noteUidProcessState(final int uid, final int state)16196     void noteUidProcessState(final int uid, final int state) {
16197         mBatteryStatsService.noteUidProcessState(uid, state);
16198         mAppOpsService.updateUidProcState(uid, state);
16199         if (mTrackingAssociations) {
16200             for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
16201                 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
16202                         = mAssociations.valueAt(i1);
16203                 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
16204                     SparseArray<ArrayMap<String, Association>> sourceUids
16205                             = targetComponents.valueAt(i2);
16206                     ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid);
16207                     if (sourceProcesses != null) {
16208                         for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
16209                             Association ass = sourceProcesses.valueAt(i4);
16210                             if (ass.mNesting >= 1) {
16211                                 // currently associated
16212                                 long uptime = SystemClock.uptimeMillis();
16213                                 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16214                                         += uptime - ass.mLastStateUptime;
16215                                 ass.mLastState = state;
16216                                 ass.mLastStateUptime = uptime;
16217                             }
16218                         }
16219                     }
16220                 }
16221             }
16222         }
16223     }
16224 
16225     private static final class RecordPssRunnable implements Runnable {
16226         private final ActivityManagerService mService;
16227         private final ProcessRecord mProc;
16228         private final File mHeapdumpFile;
16229 
RecordPssRunnable(ActivityManagerService service, ProcessRecord proc, File heapdumpFile)16230         RecordPssRunnable(ActivityManagerService service, ProcessRecord proc, File heapdumpFile) {
16231             this.mService = service;
16232             this.mProc = proc;
16233             this.mHeapdumpFile = heapdumpFile;
16234         }
16235 
16236         @Override
run()16237         public void run() {
16238             mService.revokeUriPermission(ActivityThread.currentActivityThread()
16239                             .getApplicationThread(),
16240                     null, DumpHeapActivity.JAVA_URI,
16241                     Intent.FLAG_GRANT_READ_URI_PERMISSION
16242                             | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
16243                     UserHandle.myUserId());
16244             ParcelFileDescriptor fd = null;
16245             try {
16246                 mHeapdumpFile.delete();
16247                 fd = ParcelFileDescriptor.open(mHeapdumpFile,
16248                         ParcelFileDescriptor.MODE_CREATE
16249                         | ParcelFileDescriptor.MODE_TRUNCATE
16250                         | ParcelFileDescriptor.MODE_WRITE_ONLY
16251                         | ParcelFileDescriptor.MODE_APPEND);
16252                 IApplicationThread thread = mProc.thread;
16253                 if (thread != null) {
16254                     try {
16255                         if (DEBUG_PSS) {
16256                             Slog.d(TAG_PSS, "Requesting dump heap from "
16257                                     + mProc + " to " + mHeapdumpFile);
16258                         }
16259                         thread.dumpHeap(/* managed= */ true,
16260                                 /* mallocInfo= */ false, /* runGc= */ false,
16261                                 mHeapdumpFile.toString(), fd,
16262                                 /* finishCallback= */ null);
16263                     } catch (RemoteException e) {
16264                     }
16265                 }
16266             } catch (FileNotFoundException e) {
16267                 e.printStackTrace();
16268             } finally {
16269                 if (fd != null) {
16270                     try {
16271                         fd.close();
16272                     } catch (IOException e) {
16273                     }
16274                 }
16275             }
16276         }
16277     }
16278 
16279     /**
16280      * Record new PSS sample for a process.
16281      */
recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss, long rss, int statType, long pssDuration, long now)16282     void recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss,
16283             long rss, int statType, long pssDuration, long now) {
16284         EventLogTags.writeAmPss(proc.pid, proc.uid, proc.processName, pss * 1024, uss * 1024,
16285                 swapPss * 1024, rss * 1024, statType, procState, pssDuration);
16286         proc.lastPssTime = now;
16287         proc.baseProcessTracker.addPss(
16288                 pss, uss, rss, true, statType, pssDuration, proc.pkgList.mPkgList);
16289         for (int ipkg = proc.pkgList.mPkgList.size() - 1; ipkg >= 0; ipkg--) {
16290             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
16291             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
16292                     proc.info.uid,
16293                     holder.state.getName(),
16294                     holder.state.getPackage(),
16295                     pss, uss, rss, statType, pssDuration,
16296                     holder.appVersion);
16297         }
16298         if (DEBUG_PSS) Slog.d(TAG_PSS,
16299                 "pss of " + proc.toShortString() + ": " + pss + " lastPss=" + proc.lastPss
16300                 + " state=" + ProcessList.makeProcStateString(procState));
16301         if (proc.initialIdlePss == 0) {
16302             proc.initialIdlePss = pss;
16303         }
16304         proc.lastPss = pss;
16305         proc.lastSwapPss = swapPss;
16306         if (procState >= ActivityManager.PROCESS_STATE_HOME) {
16307             proc.lastCachedPss = pss;
16308             proc.lastCachedSwapPss = swapPss;
16309         }
16310 
16311         final SparseArray<Pair<Long, String>> watchUids
16312                 = mMemWatchProcesses.getMap().get(proc.processName);
16313         Long check = null;
16314         if (watchUids != null) {
16315             Pair<Long, String> val = watchUids.get(proc.uid);
16316             if (val == null) {
16317                 val = watchUids.get(0);
16318             }
16319             if (val != null) {
16320                 check = val.first;
16321             }
16322         }
16323         if (check != null) {
16324             if ((pss * 1024) >= check && proc.thread != null && mMemWatchDumpProcName == null) {
16325                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
16326                 if (!isDebuggable) {
16327                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
16328                         isDebuggable = true;
16329                     }
16330                 }
16331                 if (isDebuggable) {
16332                     Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting");
16333                     startHeapDumpLocked(proc, false);
16334                 } else {
16335                     Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check
16336                             + ", but debugging not enabled");
16337                 }
16338             }
16339         }
16340     }
16341 
startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated)16342     private void startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated) {
16343         final File heapdumpFile = DumpHeapProvider.getJavaFile();
16344         mMemWatchDumpProcName = proc.processName;
16345         mMemWatchDumpFile = heapdumpFile.toString();
16346         mMemWatchDumpPid = proc.pid;
16347         mMemWatchDumpUid = proc.uid;
16348         mMemWatchIsUserInitiated = isUserInitiated;
16349         BackgroundThread.getHandler().post(new RecordPssRunnable(this, proc, heapdumpFile));
16350     }
16351 
16352     /**
16353      * Schedule PSS collection of a process.
16354      */
requestPssLocked(ProcessRecord proc, int procState)16355     boolean requestPssLocked(ProcessRecord proc, int procState) {
16356         if (mPendingPssProcesses.contains(proc)) {
16357             return false;
16358         }
16359         if (mPendingPssProcesses.size() == 0) {
16360             final long deferral = (mPssDeferralTime > 0 && mActivityStartingNesting.get() > 0)
16361                     ? mPssDeferralTime : 0;
16362             if (DEBUG_PSS && deferral > 0) {
16363                 Slog.d(TAG_PSS, "requestPssLocked() deferring PSS request by "
16364                         + deferral + " ms");
16365             }
16366             mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, deferral);
16367         }
16368         if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of: " + proc);
16369         proc.pssProcState = procState;
16370         proc.pssStatType = ProcessStats.ADD_PSS_INTERNAL_SINGLE;
16371         mPendingPssProcesses.add(proc);
16372         return true;
16373     }
16374 
16375     /**
16376      * Re-defer a posted PSS collection pass, if one exists.  Assumes deferral is
16377      * currently active policy when called.
16378      */
deferPssIfNeededLocked()16379     private void deferPssIfNeededLocked() {
16380         if (mPendingPssProcesses.size() > 0) {
16381             mBgHandler.removeMessages(COLLECT_PSS_BG_MSG);
16382             mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, mPssDeferralTime);
16383         }
16384     }
16385 
deferPssForActivityStart()16386     private void deferPssForActivityStart() {
16387         synchronized (ActivityManagerService.this) {
16388             if (mPssDeferralTime > 0) {
16389                 if (DEBUG_PSS) {
16390                     Slog.d(TAG_PSS, "Deferring PSS collection for activity start");
16391                 }
16392                 deferPssIfNeededLocked();
16393                 mActivityStartingNesting.getAndIncrement();
16394                 mBgHandler.sendEmptyMessageDelayed(STOP_DEFERRING_PSS_MSG, mPssDeferralTime);
16395             }
16396         }
16397     }
16398 
16399     /**
16400      * Schedule PSS collection of all processes.
16401      */
requestPssAllProcsLocked(long now, boolean always, boolean memLowered)16402     void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) {
16403         if (!always) {
16404             if (now < (mLastFullPssTime +
16405                     (memLowered ? mConstants.FULL_PSS_LOWERED_INTERVAL
16406                             : mConstants.FULL_PSS_MIN_INTERVAL))) {
16407                 return;
16408             }
16409         }
16410         if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of all procs!  memLowered=" + memLowered);
16411         mLastFullPssTime = now;
16412         mFullPssPending = true;
16413         for (int i = mPendingPssProcesses.size() - 1; i >= 0; i--) {
16414             ProcessList.abortNextPssTime(mPendingPssProcesses.get(i).procStateMemTracker);;
16415         }
16416         mPendingPssProcesses.ensureCapacity(mProcessList.getLruSizeLocked());
16417         mPendingPssProcesses.clear();
16418         for (int i = mProcessList.getLruSizeLocked() - 1; i >= 0; i--) {
16419             ProcessRecord app = mProcessList.mLruProcesses.get(i);
16420             if (app.thread == null || app.getCurProcState() == PROCESS_STATE_NONEXISTENT) {
16421                 continue;
16422             }
16423             if (memLowered || (always && now >
16424                             app.lastStateTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
16425                     || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) {
16426                 app.pssProcState = app.setProcState;
16427                 app.pssStatType = always ? ProcessStats.ADD_PSS_INTERNAL_ALL_POLL
16428                         : ProcessStats.ADD_PSS_INTERNAL_ALL_MEM;
16429                 app.nextPssTime = ProcessList.computeNextPssTime(app.getCurProcState(),
16430                         app.procStateMemTracker, mTestPssMode, mAtmInternal.isSleeping(), now);
16431                 mPendingPssProcesses.add(app);
16432             }
16433         }
16434         if (!mBgHandler.hasMessages(COLLECT_PSS_BG_MSG)) {
16435             mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
16436         }
16437     }
16438 
setTestPssMode(boolean enabled)16439     public void setTestPssMode(boolean enabled) {
16440         synchronized (this) {
16441             mTestPssMode = enabled;
16442             if (enabled) {
16443                 // Whenever we enable the mode, we want to take a snapshot all of current
16444                 // process mem use.
16445                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, true);
16446             }
16447         }
16448     }
16449 
16450     /**
16451      * Ask a given process to GC right now.
16452      */
performAppGcLocked(ProcessRecord app)16453     final void performAppGcLocked(ProcessRecord app) {
16454         try {
16455             app.lastRequestedGc = SystemClock.uptimeMillis();
16456             if (app.thread != null) {
16457                 if (app.reportLowMemory) {
16458                     app.reportLowMemory = false;
16459                     app.thread.scheduleLowMemory();
16460                 } else {
16461                     app.thread.processInBackground();
16462                 }
16463             }
16464         } catch (Exception e) {
16465             // whatever.
16466         }
16467     }
16468 
16469     /**
16470      * Returns true if things are idle enough to perform GCs.
16471      */
canGcNowLocked()16472     private final boolean canGcNowLocked() {
16473         for (BroadcastQueue q : mBroadcastQueues) {
16474             if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isEmpty()) {
16475                 return false;
16476             }
16477         }
16478         return mAtmInternal.canGcNow();
16479     }
16480 
16481     /**
16482      * Perform GCs on all processes that are waiting for it, but only
16483      * if things are idle.
16484      */
performAppGcsLocked()16485     final void performAppGcsLocked() {
16486         final int N = mProcessesToGc.size();
16487         if (N <= 0) {
16488             return;
16489         }
16490         if (canGcNowLocked()) {
16491             while (mProcessesToGc.size() > 0) {
16492                 ProcessRecord proc = mProcessesToGc.remove(0);
16493                 if (proc.getCurRawAdj() > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
16494                     if ((proc.lastRequestedGc+mConstants.GC_MIN_INTERVAL)
16495                             <= SystemClock.uptimeMillis()) {
16496                         // To avoid spamming the system, we will GC processes one
16497                         // at a time, waiting a few seconds between each.
16498                         performAppGcLocked(proc);
16499                         scheduleAppGcsLocked();
16500                         return;
16501                     } else {
16502                         // It hasn't been long enough since we last GCed this
16503                         // process...  put it in the list to wait for its time.
16504                         addProcessToGcListLocked(proc);
16505                         break;
16506                     }
16507                 }
16508             }
16509 
16510             scheduleAppGcsLocked();
16511         }
16512     }
16513 
16514     /**
16515      * If all looks good, perform GCs on all processes waiting for them.
16516      */
performAppGcsIfAppropriateLocked()16517     final void performAppGcsIfAppropriateLocked() {
16518         if (canGcNowLocked()) {
16519             performAppGcsLocked();
16520             return;
16521         }
16522         // Still not idle, wait some more.
16523         scheduleAppGcsLocked();
16524     }
16525 
16526     /**
16527      * Schedule the execution of all pending app GCs.
16528      */
scheduleAppGcsLocked()16529     final void scheduleAppGcsLocked() {
16530         mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
16531 
16532         if (mProcessesToGc.size() > 0) {
16533             // Schedule a GC for the time to the next process.
16534             ProcessRecord proc = mProcessesToGc.get(0);
16535             Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
16536 
16537             long when = proc.lastRequestedGc + mConstants.GC_MIN_INTERVAL;
16538             long now = SystemClock.uptimeMillis();
16539             if (when < (now+mConstants.GC_TIMEOUT)) {
16540                 when = now + mConstants.GC_TIMEOUT;
16541             }
16542             mHandler.sendMessageAtTime(msg, when);
16543         }
16544     }
16545 
16546     /**
16547      * Add a process to the array of processes waiting to be GCed.  Keeps the
16548      * list in sorted order by the last GC time.  The process can't already be
16549      * on the list.
16550      */
addProcessToGcListLocked(ProcessRecord proc)16551     final void addProcessToGcListLocked(ProcessRecord proc) {
16552         boolean added = false;
16553         for (int i=mProcessesToGc.size()-1; i>=0; i--) {
16554             if (mProcessesToGc.get(i).lastRequestedGc <
16555                     proc.lastRequestedGc) {
16556                 added = true;
16557                 mProcessesToGc.add(i+1, proc);
16558                 break;
16559             }
16560         }
16561         if (!added) {
16562             mProcessesToGc.add(0, proc);
16563         }
16564     }
16565 
16566     /**
16567      * Set up to ask a process to GC itself.  This will either do it
16568      * immediately, or put it on the list of processes to gc the next
16569      * time things are idle.
16570      */
scheduleAppGcLocked(ProcessRecord app)16571     final void scheduleAppGcLocked(ProcessRecord app) {
16572         long now = SystemClock.uptimeMillis();
16573         if ((app.lastRequestedGc+mConstants.GC_MIN_INTERVAL) > now) {
16574             return;
16575         }
16576         if (!mProcessesToGc.contains(app)) {
16577             addProcessToGcListLocked(app);
16578             scheduleAppGcsLocked();
16579         }
16580     }
16581 
checkExcessivePowerUsageLocked()16582     final void checkExcessivePowerUsageLocked() {
16583         updateCpuStatsNow();
16584 
16585         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
16586         boolean doCpuKills = true;
16587         if (mLastPowerCheckUptime == 0) {
16588             doCpuKills = false;
16589         }
16590         final long curUptime = SystemClock.uptimeMillis();
16591         final long uptimeSince = curUptime - mLastPowerCheckUptime;
16592         mLastPowerCheckUptime = curUptime;
16593         int i = mProcessList.mLruProcesses.size();
16594         while (i > 0) {
16595             i--;
16596             ProcessRecord app = mProcessList.mLruProcesses.get(i);
16597             if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
16598                 if (app.lastCpuTime <= 0) {
16599                     continue;
16600                 }
16601                 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
16602                 if (DEBUG_POWER) {
16603                     StringBuilder sb = new StringBuilder(128);
16604                     sb.append("CPU for ");
16605                     app.toShortString(sb);
16606                     sb.append(": over ");
16607                     TimeUtils.formatDuration(uptimeSince, sb);
16608                     sb.append(" used ");
16609                     TimeUtils.formatDuration(cputimeUsed, sb);
16610                     sb.append(" (");
16611                     sb.append((cputimeUsed*100)/uptimeSince);
16612                     sb.append("%)");
16613                     Slog.i(TAG_POWER, sb.toString());
16614                 }
16615                 // If the process has used too much CPU over the last duration, the
16616                 // user probably doesn't want this, so kill!
16617                 if (doCpuKills && uptimeSince > 0) {
16618                     // What is the limit for this process?
16619                     int cpuLimit;
16620                     long checkDur = curUptime - app.getWhenUnimportant();
16621                     if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
16622                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
16623                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*2)
16624                             || app.setProcState <= ActivityManager.PROCESS_STATE_HOME) {
16625                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
16626                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*3)) {
16627                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
16628                     } else {
16629                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
16630                     }
16631                     if (((cputimeUsed*100)/uptimeSince) >= cpuLimit) {
16632                         synchronized (stats) {
16633                             stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
16634                                     uptimeSince, cputimeUsed);
16635                         }
16636                         app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince
16637                                 + " dur=" + checkDur + " limit=" + cpuLimit, true);
16638                         app.baseProcessTracker.reportExcessiveCpu(app.pkgList.mPkgList);
16639                         for (int ipkg = app.pkgList.size() - 1; ipkg >= 0; ipkg--) {
16640                             ProcessStats.ProcessStateHolder holder = app.pkgList.valueAt(ipkg);
16641                             StatsLog.write(StatsLog.EXCESSIVE_CPU_USAGE_REPORTED,
16642                                     app.info.uid,
16643                                     holder.state.getName(),
16644                                     holder.state.getPackage(),
16645                                     holder.appVersion);
16646                         }
16647                     }
16648                 }
16649                 app.lastCpuTime = app.curCpuTime;
16650             }
16651         }
16652     }
16653 
isEphemeralLocked(int uid)16654     private boolean isEphemeralLocked(int uid) {
16655         String packages[] = mContext.getPackageManager().getPackagesForUid(uid);
16656         if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid
16657             return false;
16658         }
16659         return getPackageManagerInternalLocked().isPackageEphemeral(UserHandle.getUserId(uid),
16660                 packages[0]);
16661     }
16662 
16663     @VisibleForTesting
enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)16664     final void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) {
16665         final UidRecord.ChangeItem pendingChange;
16666         if (uidRec == null || uidRec.pendingChange == null) {
16667             if (mPendingUidChanges.size() == 0) {
16668                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
16669                         "*** Enqueueing dispatch uid changed!");
16670                 mUiHandler.obtainMessage(DISPATCH_UIDS_CHANGED_UI_MSG).sendToTarget();
16671             }
16672             final int NA = mAvailUidChanges.size();
16673             if (NA > 0) {
16674                 pendingChange = mAvailUidChanges.remove(NA-1);
16675                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
16676                         "Retrieving available item: " + pendingChange);
16677             } else {
16678                 pendingChange = new UidRecord.ChangeItem();
16679                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
16680                         "Allocating new item: " + pendingChange);
16681             }
16682             if (uidRec != null) {
16683                 uidRec.pendingChange = pendingChange;
16684                 if ((change & UidRecord.CHANGE_GONE) != 0 && !uidRec.idle) {
16685                     // If this uid is going away, and we haven't yet reported it is gone,
16686                     // then do so now.
16687                     change |= UidRecord.CHANGE_IDLE;
16688                 }
16689             } else if (uid < 0) {
16690                 throw new IllegalArgumentException("No UidRecord or uid");
16691             }
16692             pendingChange.uidRecord = uidRec;
16693             pendingChange.uid = uidRec != null ? uidRec.uid : uid;
16694             mPendingUidChanges.add(pendingChange);
16695         } else {
16696             pendingChange = uidRec.pendingChange;
16697             // If there is no change in idle or active state, then keep whatever was pending.
16698             if ((change & (UidRecord.CHANGE_IDLE | UidRecord.CHANGE_ACTIVE)) == 0) {
16699                 change |= (pendingChange.change & (UidRecord.CHANGE_IDLE
16700                         | UidRecord.CHANGE_ACTIVE));
16701             }
16702             // If there is no change in cached or uncached state, then keep whatever was pending.
16703             if ((change & (UidRecord.CHANGE_CACHED | UidRecord.CHANGE_UNCACHED)) == 0) {
16704                 change |= (pendingChange.change & (UidRecord.CHANGE_CACHED
16705                         | UidRecord.CHANGE_UNCACHED));
16706             }
16707             // If this is a report of the UID being gone, then we shouldn't keep any previous
16708             // report of it being active or cached.  (That is, a gone uid is never active,
16709             // and never cached.)
16710             if ((change & UidRecord.CHANGE_GONE) != 0) {
16711                 change &= ~(UidRecord.CHANGE_ACTIVE | UidRecord.CHANGE_CACHED);
16712                 if (!uidRec.idle) {
16713                     // If this uid is going away, and we haven't yet reported it is gone,
16714                     // then do so now.
16715                     change |= UidRecord.CHANGE_IDLE;
16716                 }
16717             }
16718         }
16719         pendingChange.change = change;
16720         pendingChange.processState = uidRec != null ? uidRec.setProcState : PROCESS_STATE_NONEXISTENT;
16721         pendingChange.ephemeral = uidRec != null ? uidRec.ephemeral : isEphemeralLocked(uid);
16722         pendingChange.procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0;
16723         if (uidRec != null) {
16724             uidRec.lastReportedChange = change;
16725             uidRec.updateLastDispatchedProcStateSeq(change);
16726         }
16727 
16728         // Directly update the power manager, since we sit on top of it and it is critical
16729         // it be kept in sync (so wake locks will be held as soon as appropriate).
16730         if (mLocalPowerManager != null) {
16731             // TO DO: dispatch cached/uncached changes here, so we don't need to report
16732             // all proc state changes.
16733             if ((change & UidRecord.CHANGE_ACTIVE) != 0) {
16734                 mLocalPowerManager.uidActive(pendingChange.uid);
16735             }
16736             if ((change & UidRecord.CHANGE_IDLE) != 0) {
16737                 mLocalPowerManager.uidIdle(pendingChange.uid);
16738             }
16739             if ((change & UidRecord.CHANGE_GONE) != 0) {
16740                 mLocalPowerManager.uidGone(pendingChange.uid);
16741             } else {
16742                 mLocalPowerManager.updateUidProcState(pendingChange.uid,
16743                         pendingChange.processState);
16744             }
16745         }
16746     }
16747 
maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, String authority)16748     private void maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName,
16749             String authority) {
16750         if (app == null) return;
16751         if (app.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
16752             UserState userState = mUserController.getStartedUserState(app.userId);
16753             if (userState == null) return;
16754             final long now = SystemClock.elapsedRealtime();
16755             Long lastReported = userState.mProviderLastReportedFg.get(authority);
16756             if (lastReported == null || lastReported < now - 60 * 1000L) {
16757                 if (mSystemReady) {
16758                     // Cannot touch the user stats if not system ready
16759                     mUsageStatsService.reportContentProviderUsage(
16760                             authority, providerPkgName, app.userId);
16761                 }
16762                 userState.mProviderLastReportedFg.put(authority, now);
16763             }
16764         }
16765     }
16766 
setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now)16767     final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) {
16768         if (proc.thread != null && proc.baseProcessTracker != null) {
16769             proc.baseProcessTracker.setState(
16770                     proc.getReportedProcState(), memFactor, now, proc.pkgList.mPkgList);
16771         }
16772     }
16773 
16774     @GuardedBy("this")
updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)16775     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
16776             int fgServiceTypes, boolean oomAdj) {
16777 
16778         if (isForeground != proc.hasForegroundServices()
16779                 || proc.getForegroundServiceTypes() != fgServiceTypes) {
16780             proc.setHasForegroundServices(isForeground, fgServiceTypes);
16781             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
16782                     proc.info.uid);
16783             if (isForeground) {
16784                 if (curProcs == null) {
16785                     curProcs = new ArrayList<ProcessRecord>();
16786                     mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
16787                 }
16788                 if (!curProcs.contains(proc)) {
16789                     curProcs.add(proc);
16790                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
16791                             proc.info.packageName, proc.info.uid);
16792                 }
16793             } else {
16794                 if (curProcs != null) {
16795                     if (curProcs.remove(proc)) {
16796                         mBatteryStatsService.noteEvent(
16797                                 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
16798                                 proc.info.packageName, proc.info.uid);
16799                         if (curProcs.size() <= 0) {
16800                             mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
16801                         }
16802                     }
16803                 }
16804             }
16805 
16806             proc.setReportedForegroundServiceTypes(fgServiceTypes);
16807             ProcessChangeItem item = enqueueProcessChangeItemLocked(proc.pid, proc.info.uid);
16808             item.changes = ProcessChangeItem.CHANGE_FOREGROUND_SERVICES;
16809             item.foregroundServiceTypes = fgServiceTypes;
16810 
16811             if (oomAdj) {
16812                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
16813             }
16814         }
16815     }
16816 
16817     // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update
16818     // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities
getTopAppLocked()16819     ProcessRecord getTopAppLocked() {
16820         final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null;
16821         final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null;
16822         String pkg;
16823         int uid;
16824         if (r != null) {
16825             pkg = r.processName;
16826             uid = r.info.uid;
16827         } else {
16828             pkg = null;
16829             uid = -1;
16830         }
16831         // Has the UID or resumed package name changed?
16832         if (uid != mCurResumedUid || (pkg != mCurResumedPackage
16833                 && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
16834 
16835             final long identity = Binder.clearCallingIdentity();
16836             try {
16837                 if (mCurResumedPackage != null) {
16838                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
16839                             mCurResumedPackage, mCurResumedUid);
16840                 }
16841                 mCurResumedPackage = pkg;
16842                 mCurResumedUid = uid;
16843                 if (mCurResumedPackage != null) {
16844                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
16845                             mCurResumedPackage, mCurResumedUid);
16846                 }
16847             } finally {
16848                 Binder.restoreCallingIdentity(identity);
16849             }
16850 
16851         }
16852         return r;
16853     }
16854 
16855     /**
16856      * Update OomAdj for a specific process.
16857      * @param app The process to update
16858      * @param oomAdjAll If it's ok to call updateOomAdjLocked() for all running apps
16859      *                  if necessary, or skip.
16860      * @param oomAdjReason
16861      * @return whether updateOomAdjLocked(app) was successful.
16862      */
16863     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll, String oomAdjReason)16864     final boolean updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll,
16865             String oomAdjReason) {
16866         return mOomAdjuster.updateOomAdjLocked(app, oomAdjAll, oomAdjReason);
16867     }
16868 
16869     static final class ProcStatsRunnable implements Runnable {
16870         private final ActivityManagerService mService;
16871         private final ProcessStatsService mProcessStats;
16872 
ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)16873         ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) {
16874             this.mService = service;
16875             this.mProcessStats = mProcessStats;
16876         }
16877 
run()16878         @Override public void run() {
16879             synchronized (mService) {
16880                 mProcessStats.writeStateAsyncLocked();
16881             }
16882         }
16883     }
16884 
16885     @GuardedBy("this")
updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming)16886     final boolean updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming) {
16887         final int N = mProcessList.getLruSizeLocked();
16888         final long now = SystemClock.uptimeMillis();
16889         int memFactor;
16890         if (mLowMemDetector != null && mLowMemDetector.isAvailable()) {
16891             memFactor = mLowMemDetector.getMemFactor();
16892         } else {
16893             // Now determine the memory trimming level of background processes.
16894             // Unfortunately we need to start at the back of the list to do this
16895             // properly.  We only do this if the number of background apps we
16896             // are managing to keep around is less than half the maximum we desire;
16897             // if we are keeping a good number around, we'll let them use whatever
16898             // memory they want.
16899             if (numCached <= mConstants.CUR_TRIM_CACHED_PROCESSES
16900                 && numEmpty <= mConstants.CUR_TRIM_EMPTY_PROCESSES) {
16901                 final int numCachedAndEmpty = numCached + numEmpty;
16902                 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
16903                     memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL;
16904                 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
16905                     memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW;
16906                 } else {
16907                     memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE;
16908                 }
16909             } else {
16910                 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
16911             }
16912         }
16913         // We always allow the memory level to go up (better).  We only allow it to go
16914         // down if we are in a state where that is allowed, *and* the total number of processes
16915         // has gone down since last time.
16916         if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "oom: memFactor=" + memFactor
16917                 + " last=" + mLastMemoryLevel + " allowLow=" + mAllowLowerMemLevel
16918                 + " numProcs=" + mProcessList.getLruSizeLocked() + " last=" + mLastNumProcesses);
16919         if (memFactor > mLastMemoryLevel) {
16920             if (!mAllowLowerMemLevel || mProcessList.getLruSizeLocked() >= mLastNumProcesses) {
16921                 memFactor = mLastMemoryLevel;
16922                 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "Keeping last mem factor!");
16923             }
16924         }
16925         if (memFactor != mLastMemoryLevel) {
16926             EventLogTags.writeAmMemFactor(memFactor, mLastMemoryLevel);
16927             StatsLog.write(StatsLog.MEMORY_FACTOR_STATE_CHANGED, memFactor);
16928         }
16929         mLastMemoryLevel = memFactor;
16930         mLastNumProcesses = mProcessList.getLruSizeLocked();
16931         boolean allChanged = mProcessStats.setMemFactorLocked(
16932                 memFactor, mAtmInternal != null ? !mAtmInternal.isSleeping() : true, now);
16933         final int trackerMemFactor = mProcessStats.getMemFactorLocked();
16934         if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) {
16935             if (mLowRamStartTime == 0) {
16936                 mLowRamStartTime = now;
16937             }
16938             int step = 0;
16939             int fgTrimLevel;
16940             switch (memFactor) {
16941                 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
16942                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
16943                     break;
16944                 case ProcessStats.ADJ_MEM_FACTOR_LOW:
16945                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
16946                     break;
16947                 default:
16948                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
16949                     break;
16950             }
16951             int factor = numTrimming/3;
16952             int minFactor = 2;
16953             if (mAtmInternal.getHomeProcess() != null) minFactor++;
16954             if (mAtmInternal.getPreviousProcess() != null) minFactor++;
16955             if (factor < minFactor) factor = minFactor;
16956             int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
16957             for (int i=N-1; i>=0; i--) {
16958                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
16959                 if (allChanged || app.procStateChanged) {
16960                     setProcessTrackerStateLocked(app, trackerMemFactor, now);
16961                     app.procStateChanged = false;
16962                 }
16963                 if (app.getCurProcState() >= ActivityManager.PROCESS_STATE_HOME
16964                         && !app.killedByAm) {
16965                     if (app.trimMemoryLevel < curLevel && app.thread != null) {
16966                         try {
16967                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16968                                     "Trimming memory of " + app.processName + " to " + curLevel);
16969                             app.thread.scheduleTrimMemory(curLevel);
16970                         } catch (RemoteException e) {
16971                         }
16972                     }
16973                     app.trimMemoryLevel = curLevel;
16974                     step++;
16975                     if (step >= factor) {
16976                         step = 0;
16977                         switch (curLevel) {
16978                             case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
16979                                 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
16980                                 break;
16981                             case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
16982                                 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
16983                                 break;
16984                         }
16985                     }
16986                 } else if (app.getCurProcState() == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
16987                         && !app.killedByAm) {
16988                     if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
16989                             && app.thread != null) {
16990                         try {
16991                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16992                                     "Trimming memory of heavy-weight " + app.processName
16993                                     + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
16994                             app.thread.scheduleTrimMemory(
16995                                     ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
16996                         } catch (RemoteException e) {
16997                         }
16998                     }
16999                     app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
17000                 } else {
17001                     if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
17002                             || app.systemNoUi) && app.hasPendingUiClean()) {
17003                         // If this application is now in the background and it
17004                         // had done UI, then give it the special trim level to
17005                         // have it free UI resources.
17006                         final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
17007                         if (app.trimMemoryLevel < level && app.thread != null) {
17008                             try {
17009                                 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
17010                                         "Trimming memory of bg-ui " + app.processName
17011                                         + " to " + level);
17012                                 app.thread.scheduleTrimMemory(level);
17013                             } catch (RemoteException e) {
17014                             }
17015                         }
17016                         app.setPendingUiClean(false);
17017                     }
17018                     if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
17019                         try {
17020                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
17021                                     "Trimming memory of fg " + app.processName
17022                                     + " to " + fgTrimLevel);
17023                             app.thread.scheduleTrimMemory(fgTrimLevel);
17024                         } catch (RemoteException e) {
17025                         }
17026                     }
17027                     app.trimMemoryLevel = fgTrimLevel;
17028                 }
17029             }
17030         } else {
17031             if (mLowRamStartTime != 0) {
17032                 mLowRamTimeSinceLastIdle += now - mLowRamStartTime;
17033                 mLowRamStartTime = 0;
17034             }
17035             for (int i=N-1; i>=0; i--) {
17036                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
17037                 if (allChanged || app.procStateChanged) {
17038                     setProcessTrackerStateLocked(app, trackerMemFactor, now);
17039                     app.procStateChanged = false;
17040                 }
17041                 if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
17042                         || app.systemNoUi) && app.hasPendingUiClean()) {
17043                     if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
17044                             && app.thread != null) {
17045                         try {
17046                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
17047                                     "Trimming memory of ui hidden " + app.processName
17048                                     + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
17049                             app.thread.scheduleTrimMemory(
17050                                     ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
17051                         } catch (RemoteException e) {
17052                         }
17053                     }
17054                     app.setPendingUiClean(false);
17055                 }
17056                 app.trimMemoryLevel = 0;
17057             }
17058         }
17059         return allChanged;
17060     }
17061 
17062     @GuardedBy("this")
updateOomAdjLocked(String oomAdjReason)17063     final void updateOomAdjLocked(String oomAdjReason) {
17064         mOomAdjuster.updateOomAdjLocked(oomAdjReason);
17065     }
17066 
17067     @Override
makePackageIdle(String packageName, int userId)17068     public void makePackageIdle(String packageName, int userId) {
17069         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
17070                 != PackageManager.PERMISSION_GRANTED) {
17071             String msg = "Permission Denial: makePackageIdle() from pid="
17072                     + Binder.getCallingPid()
17073                     + ", uid=" + Binder.getCallingUid()
17074                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
17075             Slog.w(TAG, msg);
17076             throw new SecurityException(msg);
17077         }
17078         final int callingPid = Binder.getCallingPid();
17079         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
17080                 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null);
17081         long callingId = Binder.clearCallingIdentity();
17082         synchronized(this) {
17083             try {
17084                 IPackageManager pm = AppGlobals.getPackageManager();
17085                 int pkgUid = -1;
17086                 try {
17087                     pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES
17088                             | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM);
17089                 } catch (RemoteException e) {
17090                 }
17091                 if (pkgUid == -1) {
17092                     throw new IllegalArgumentException("Unknown package name " + packageName);
17093                 }
17094 
17095                 if (mLocalPowerManager != null) {
17096                     mLocalPowerManager.startUidChanges();
17097                 }
17098                 final int appId = UserHandle.getAppId(pkgUid);
17099                 final int N = mProcessList.mActiveUids.size();
17100                 for (int i = N - 1; i >= 0; i--) {
17101                     final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
17102                     final long bgTime = uidRec.lastBackgroundTime;
17103                     if (bgTime > 0 && !uidRec.idle) {
17104                         if (UserHandle.getAppId(uidRec.uid) == appId) {
17105                             if (userId == UserHandle.USER_ALL ||
17106                                     userId == UserHandle.getUserId(uidRec.uid)) {
17107                                 EventLogTags.writeAmUidIdle(uidRec.uid);
17108                                 uidRec.idle = true;
17109                                 uidRec.setIdle = true;
17110                                 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uidRec.uid)
17111                                         + " from package " + packageName + " user " + userId);
17112                                 doStopUidLocked(uidRec.uid, uidRec);
17113                             }
17114                         }
17115                     }
17116                 }
17117             } finally {
17118                 if (mLocalPowerManager != null) {
17119                     mLocalPowerManager.finishUidChanges();
17120                 }
17121                 Binder.restoreCallingIdentity(callingId);
17122             }
17123         }
17124     }
17125 
17126     /** Make the currently active UIDs idle after a certain grace period. */
idleUids()17127     final void idleUids() {
17128         synchronized (this) {
17129             mOomAdjuster.idleUidsLocked();
17130         }
17131     }
17132 
17133     /**
17134      * Checks if any uid is coming from background to foreground or vice versa and if so, increments
17135      * the {@link UidRecord#curProcStateSeq} corresponding to that uid using global seq counter
17136      * {@link ProcessList#mProcStateSeqCounter} and notifies the app if it needs to block.
17137      */
17138     @VisibleForTesting
17139     @GuardedBy("this")
incrementProcStateSeqAndNotifyAppsLocked()17140     void incrementProcStateSeqAndNotifyAppsLocked() {
17141         if (mWaitForNetworkTimeoutMs <= 0) {
17142             return;
17143         }
17144         // Used for identifying which uids need to block for network.
17145         ArrayList<Integer> blockingUids = null;
17146         for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; --i) {
17147             final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
17148             // If the network is not restricted for uid, then nothing to do here.
17149             if (!mInjector.isNetworkRestrictedForUid(uidRec.uid)) {
17150                 continue;
17151             }
17152             if (!UserHandle.isApp(uidRec.uid) || !uidRec.hasInternetPermission) {
17153                 continue;
17154             }
17155             // If process state is not changed, then there's nothing to do.
17156             if (uidRec.setProcState == uidRec.getCurProcState()) {
17157                 continue;
17158             }
17159             final int blockState = getBlockStateForUid(uidRec);
17160             // No need to inform the app when the blockState is NETWORK_STATE_NO_CHANGE as
17161             // there's nothing the app needs to do in this scenario.
17162             if (blockState == NETWORK_STATE_NO_CHANGE) {
17163                 continue;
17164             }
17165             synchronized (uidRec.networkStateLock) {
17166                 uidRec.curProcStateSeq = ++mProcessList.mProcStateSeqCounter; // TODO: use method
17167                 if (blockState == NETWORK_STATE_BLOCK) {
17168                     if (blockingUids == null) {
17169                         blockingUids = new ArrayList<>();
17170                     }
17171                     blockingUids.add(uidRec.uid);
17172                 } else {
17173                     if (DEBUG_NETWORK) {
17174                         Slog.d(TAG_NETWORK, "uid going to background, notifying all blocking"
17175                                 + " threads for uid: " + uidRec);
17176                     }
17177                     if (uidRec.waitingForNetwork) {
17178                         uidRec.networkStateLock.notifyAll();
17179                     }
17180                 }
17181             }
17182         }
17183 
17184         // There are no uids that need to block, so nothing more to do.
17185         if (blockingUids == null) {
17186             return;
17187         }
17188 
17189         for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; --i) {
17190             final ProcessRecord app = mProcessList.mLruProcesses.get(i);
17191             if (!blockingUids.contains(app.uid)) {
17192                 continue;
17193             }
17194             if (!app.killedByAm && app.thread != null) {
17195                 final UidRecord uidRec = mProcessList.getUidRecordLocked(app.uid);
17196                 try {
17197                     if (DEBUG_NETWORK) {
17198                         Slog.d(TAG_NETWORK, "Informing app thread that it needs to block: "
17199                                 + uidRec);
17200                     }
17201                     if (uidRec != null) {
17202                         app.thread.setNetworkBlockSeq(uidRec.curProcStateSeq);
17203                     }
17204                 } catch (RemoteException ignored) {
17205                 }
17206             }
17207         }
17208     }
17209 
17210     /**
17211      * Checks if the uid is coming from background to foreground or vice versa and returns
17212      * appropriate block state based on this.
17213      *
17214      * @return blockState based on whether the uid is coming from background to foreground or
17215      *         vice versa. If bg->fg or fg->bg, then {@link #NETWORK_STATE_BLOCK} or
17216      *         {@link #NETWORK_STATE_UNBLOCK} respectively, otherwise
17217      *         {@link #NETWORK_STATE_NO_CHANGE}.
17218      */
17219     @VisibleForTesting
getBlockStateForUid(UidRecord uidRec)17220     int getBlockStateForUid(UidRecord uidRec) {
17221         // Denotes whether uid's process state is currently allowed network access.
17222         final boolean isAllowed =
17223                 isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.getCurProcState())
17224                 || isProcStateAllowedWhileOnRestrictBackground(uidRec.getCurProcState());
17225         // Denotes whether uid's process state was previously allowed network access.
17226         final boolean wasAllowed = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.setProcState)
17227                 || isProcStateAllowedWhileOnRestrictBackground(uidRec.setProcState);
17228 
17229         // When the uid is coming to foreground, AMS should inform the app thread that it should
17230         // block for the network rules to get updated before launching an activity.
17231         if (!wasAllowed && isAllowed) {
17232             return NETWORK_STATE_BLOCK;
17233         }
17234         // When the uid is going to background, AMS should inform the app thread that if an
17235         // activity launch is blocked for the network rules to get updated, it should be unblocked.
17236         if (wasAllowed && !isAllowed) {
17237             return NETWORK_STATE_UNBLOCK;
17238         }
17239         return NETWORK_STATE_NO_CHANGE;
17240     }
17241 
runInBackgroundDisabled(int uid)17242     final void runInBackgroundDisabled(int uid) {
17243         synchronized (this) {
17244             UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
17245             if (uidRec != null) {
17246                 // This uid is actually running...  should it be considered background now?
17247                 if (uidRec.idle) {
17248                     doStopUidLocked(uidRec.uid, uidRec);
17249                 }
17250             } else {
17251                 // This uid isn't actually running...  still send a report about it being "stopped".
17252                 doStopUidLocked(uid, null);
17253             }
17254         }
17255     }
17256 
17257     @GuardedBy("this")
doStopUidLocked(int uid, final UidRecord uidRec)17258     final void doStopUidLocked(int uid, final UidRecord uidRec) {
17259         mServices.stopInBackgroundLocked(uid);
17260         enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE);
17261     }
17262 
17263     /**
17264      * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
17265      */
17266     @GuardedBy("this")
tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, String tag)17267     void tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid,
17268             long duration, String tag) {
17269         if (DEBUG_WHITELISTS) {
17270             Slog.d(TAG, "tempWhitelistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", "
17271                     + targetUid + ", " + duration + ")");
17272         }
17273 
17274         synchronized (mPidsSelfLocked) {
17275             final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
17276             if (pr == null) {
17277                 Slog.w(TAG, "tempWhitelistForPendingIntentLocked() no ProcessRecord for pid "
17278                         + callerPid);
17279                 return;
17280             }
17281             if (!pr.whitelistManager) {
17282                 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid)
17283                         != PackageManager.PERMISSION_GRANTED) {
17284                     if (DEBUG_WHITELISTS) {
17285                         Slog.d(TAG, "tempWhitelistForPendingIntentLocked() for target " + targetUid
17286                                 + ": pid " + callerPid + " is not allowed");
17287                     }
17288                     return;
17289                 }
17290             }
17291         }
17292 
17293         tempWhitelistUidLocked(targetUid, duration, tag);
17294     }
17295 
17296     /**
17297      * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
17298      */
17299     @GuardedBy("this")
tempWhitelistUidLocked(int targetUid, long duration, String tag)17300     void tempWhitelistUidLocked(int targetUid, long duration, String tag) {
17301         mPendingTempWhitelist.put(targetUid, new PendingTempWhitelist(targetUid, duration, tag));
17302         setUidTempWhitelistStateLocked(targetUid, true);
17303         mUiHandler.obtainMessage(PUSH_TEMP_WHITELIST_UI_MSG).sendToTarget();
17304     }
17305 
pushTempWhitelist()17306     void pushTempWhitelist() {
17307         final int N;
17308         final PendingTempWhitelist[] list;
17309 
17310         // First copy out the pending changes...  we need to leave them in the map for now,
17311         // in case someone needs to check what is coming up while we don't have the lock held.
17312         synchronized(this) {
17313             N = mPendingTempWhitelist.size();
17314             list = new PendingTempWhitelist[N];
17315             for (int i = 0; i < N; i++) {
17316                 list[i] = mPendingTempWhitelist.valueAt(i);
17317             }
17318         }
17319 
17320         // Now safely dispatch changes to device idle controller.
17321         for (int i = 0; i < N; i++) {
17322             PendingTempWhitelist ptw = list[i];
17323             mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid,
17324                     ptw.duration, true, ptw.tag);
17325         }
17326 
17327         // And now we can safely remove them from the map.
17328         synchronized(this) {
17329             for (int i = 0; i < N; i++) {
17330                 PendingTempWhitelist ptw = list[i];
17331                 int index = mPendingTempWhitelist.indexOfKey(ptw.targetUid);
17332                 if (index >= 0 && mPendingTempWhitelist.valueAt(index) == ptw) {
17333                     mPendingTempWhitelist.removeAt(index);
17334                 }
17335             }
17336         }
17337     }
17338 
17339     @GuardedBy("this")
setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist)17340     final void setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist) {
17341         mOomAdjuster.setAppIdTempWhitelistStateLocked(appId, onWhitelist);
17342     }
17343 
17344     @GuardedBy("this")
setUidTempWhitelistStateLocked(int uid, boolean onWhitelist)17345     final void setUidTempWhitelistStateLocked(int uid, boolean onWhitelist) {
17346         mOomAdjuster.setUidTempWhitelistStateLocked(uid, onWhitelist);
17347     }
17348 
trimApplications(String oomAdjReason)17349     final void trimApplications(String oomAdjReason) {
17350         synchronized (this) {
17351             trimApplicationsLocked(oomAdjReason);
17352         }
17353     }
17354 
17355     @GuardedBy("this")
trimApplicationsLocked(String oomAdjReason)17356     final void trimApplicationsLocked(String oomAdjReason) {
17357         // First remove any unused application processes whose package
17358         // has been removed.
17359         for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) {
17360             final ProcessRecord app = mProcessList.mRemovedProcesses.get(i);
17361             if (!app.hasActivitiesOrRecentTasks()
17362                     && app.curReceivers.isEmpty() && app.services.size() == 0) {
17363                 Slog.i(
17364                     TAG, "Exiting empty application process "
17365                     + app.toShortString() + " ("
17366                     + (app.thread != null ? app.thread.asBinder() : null)
17367                     + ")\n");
17368                 if (app.pid > 0 && app.pid != MY_PID) {
17369                     app.kill("empty", false);
17370                 } else if (app.thread != null) {
17371                     try {
17372                         app.thread.scheduleExit();
17373                     } catch (Exception e) {
17374                         // Ignore exceptions.
17375                     }
17376                 }
17377                 cleanUpApplicationRecordLocked(app, false, true, -1, false /*replacingPid*/);
17378                 mProcessList.mRemovedProcesses.remove(i);
17379 
17380                 if (app.isPersistent()) {
17381                     addAppLocked(app.info, null, false, null /* ABI override */,
17382                             ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
17383                 }
17384             }
17385         }
17386 
17387         // Now update the oom adj for all processes. Don't skip this, since other callers
17388         // might be depending on it.
17389         updateOomAdjLocked(oomAdjReason);
17390     }
17391 
17392     /** This method sends the specified signal to each of the persistent apps */
signalPersistentProcesses(int sig)17393     public void signalPersistentProcesses(int sig) throws RemoteException {
17394         if (sig != SIGNAL_USR1) {
17395             throw new SecurityException("Only SIGNAL_USR1 is allowed");
17396         }
17397 
17398         synchronized (this) {
17399             if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
17400                     != PackageManager.PERMISSION_GRANTED) {
17401                 throw new SecurityException("Requires permission "
17402                         + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
17403             }
17404 
17405             for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) {
17406                 ProcessRecord r = mProcessList.mLruProcesses.get(i);
17407                 if (r.thread != null && r.isPersistent()) {
17408                     sendSignal(r.pid, sig);
17409                 }
17410             }
17411         }
17412     }
17413 
stopProfilerLocked(ProcessRecord proc, int profileType)17414     private void stopProfilerLocked(ProcessRecord proc, int profileType) {
17415         if (proc == null || proc == mProfileData.getProfileProc()) {
17416             proc = mProfileData.getProfileProc();
17417             profileType = mProfileType;
17418             clearProfilerLocked();
17419         }
17420         if (proc == null) {
17421             return;
17422         }
17423         try {
17424             proc.thread.profilerControl(false, null, profileType);
17425         } catch (RemoteException e) {
17426             throw new IllegalStateException("Process disappeared");
17427         }
17428     }
17429 
clearProfilerLocked()17430     void clearProfilerLocked() {
17431         if (mProfileData.getProfilerInfo() != null
17432                 && mProfileData.getProfilerInfo().profileFd != null) {
17433             try {
17434                 mProfileData.getProfilerInfo().profileFd.close();
17435             } catch (IOException e) {
17436             }
17437         }
17438         mProfileData.setProfileApp(null);
17439         mProfileData.setProfileProc(null);
17440         mProfileData.setProfilerInfo(null);
17441     }
17442 
profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)17443     public boolean profileControl(String process, int userId, boolean start,
17444             ProfilerInfo profilerInfo, int profileType) throws RemoteException {
17445 
17446         try {
17447             synchronized (this) {
17448                 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17449                 // its own permission.
17450                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17451                         != PackageManager.PERMISSION_GRANTED) {
17452                     throw new SecurityException("Requires permission "
17453                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17454                 }
17455 
17456                 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
17457                     throw new IllegalArgumentException("null profile info or fd");
17458                 }
17459 
17460                 ProcessRecord proc = null;
17461                 if (process != null) {
17462                     proc = findProcessLocked(process, userId, "profileControl");
17463                 }
17464 
17465                 if (start && (proc == null || proc.thread == null)) {
17466                     throw new IllegalArgumentException("Unknown process: " + process);
17467                 }
17468 
17469                 if (start) {
17470                     stopProfilerLocked(null, 0);
17471                     setProfileApp(proc.info, proc.processName, profilerInfo);
17472                     mProfileData.setProfileProc(proc);
17473                     mProfileType = profileType;
17474                     ParcelFileDescriptor fd = profilerInfo.profileFd;
17475                     try {
17476                         fd = fd.dup();
17477                     } catch (IOException e) {
17478                         fd = null;
17479                     }
17480                     profilerInfo.profileFd = fd;
17481                     proc.thread.profilerControl(start, profilerInfo, profileType);
17482                     fd = null;
17483                     try {
17484                         mProfileData.getProfilerInfo().profileFd.close();
17485                     } catch (IOException e) {
17486                     }
17487                     mProfileData.getProfilerInfo().profileFd = null;
17488 
17489                     if (proc.pid == MY_PID) {
17490                         // When profiling the system server itself, avoid closing the file
17491                         // descriptor, as profilerControl will not create a copy.
17492                         // Note: it is also not correct to just set profileFd to null, as the
17493                         //       whole ProfilerInfo instance is passed down!
17494                         profilerInfo = null;
17495                     }
17496                 } else {
17497                     stopProfilerLocked(proc, profileType);
17498                     if (profilerInfo != null && profilerInfo.profileFd != null) {
17499                         try {
17500                             profilerInfo.profileFd.close();
17501                         } catch (IOException e) {
17502                         }
17503                     }
17504                 }
17505 
17506                 return true;
17507             }
17508         } catch (RemoteException e) {
17509             throw new IllegalStateException("Process disappeared");
17510         } finally {
17511             if (profilerInfo != null && profilerInfo.profileFd != null) {
17512                 try {
17513                     profilerInfo.profileFd.close();
17514                 } catch (IOException e) {
17515                 }
17516             }
17517         }
17518     }
17519 
findProcessLocked(String process, int userId, String callName)17520     private ProcessRecord findProcessLocked(String process, int userId, String callName) {
17521         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
17522                 userId, true, ALLOW_FULL_ONLY, callName, null);
17523         ProcessRecord proc = null;
17524         try {
17525             int pid = Integer.parseInt(process);
17526             synchronized (mPidsSelfLocked) {
17527                 proc = mPidsSelfLocked.get(pid);
17528             }
17529         } catch (NumberFormatException e) {
17530         }
17531 
17532         if (proc == null) {
17533             ArrayMap<String, SparseArray<ProcessRecord>> all
17534                     = mProcessList.mProcessNames.getMap();
17535             SparseArray<ProcessRecord> procs = all.get(process);
17536             if (procs != null && procs.size() > 0) {
17537                 proc = procs.valueAt(0);
17538                 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
17539                     for (int i=1; i<procs.size(); i++) {
17540                         ProcessRecord thisProc = procs.valueAt(i);
17541                         if (thisProc.userId == userId) {
17542                             proc = thisProc;
17543                             break;
17544                         }
17545                     }
17546                 }
17547             }
17548         }
17549 
17550         return proc;
17551     }
17552 
17553     @Override
dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)17554     public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo,
17555             boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) {
17556 
17557         try {
17558             synchronized (this) {
17559                 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17560                 // its own permission (same as profileControl).
17561                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17562                         != PackageManager.PERMISSION_GRANTED) {
17563                     throw new SecurityException("Requires permission "
17564                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17565                 }
17566 
17567                 if (fd == null) {
17568                     throw new IllegalArgumentException("null fd");
17569                 }
17570 
17571                 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
17572                 if (proc == null || proc.thread == null) {
17573                     throw new IllegalArgumentException("Unknown process: " + process);
17574                 }
17575 
17576                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
17577                 if (!isDebuggable) {
17578                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17579                         throw new SecurityException("Process not debuggable: " + proc);
17580                     }
17581                 }
17582 
17583                 proc.thread.dumpHeap(managed, mallocInfo, runGc, path, fd, finishCallback);
17584                 fd = null;
17585                 return true;
17586             }
17587         } catch (RemoteException e) {
17588             throw new IllegalStateException("Process disappeared");
17589         } finally {
17590             if (fd != null) {
17591                 try {
17592                     fd.close();
17593                 } catch (IOException e) {
17594                 }
17595             }
17596         }
17597     }
17598 
17599     @Override
setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)17600     public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize,
17601             String reportPackage) {
17602         if (processName != null) {
17603             enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
17604                     "setDumpHeapDebugLimit()");
17605         } else {
17606             synchronized (mPidsSelfLocked) {
17607                 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid());
17608                 if (proc == null) {
17609                     throw new SecurityException("No process found for calling pid "
17610                             + Binder.getCallingPid());
17611                 }
17612                 if (!Build.IS_DEBUGGABLE
17613                         && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17614                     throw new SecurityException("Not running a debuggable build");
17615                 }
17616                 processName = proc.processName;
17617                 uid = proc.uid;
17618                 if (reportPackage != null && !proc.pkgList.containsKey(reportPackage)) {
17619                     throw new SecurityException("Package " + reportPackage + " is not running in "
17620                             + proc);
17621                 }
17622             }
17623         }
17624         synchronized (this) {
17625             if (maxMemSize > 0) {
17626                 mMemWatchProcesses.put(processName, uid, new Pair(maxMemSize, reportPackage));
17627             } else {
17628                 if (uid != 0) {
17629                     mMemWatchProcesses.remove(processName, uid);
17630                 } else {
17631                     mMemWatchProcesses.getMap().remove(processName);
17632                 }
17633             }
17634         }
17635     }
17636 
17637     @Override
dumpHeapFinished(String path)17638     public void dumpHeapFinished(String path) {
17639         synchronized (this) {
17640             if (Binder.getCallingPid() != mMemWatchDumpPid) {
17641                 Slog.w(TAG, "dumpHeapFinished: Calling pid " + Binder.getCallingPid()
17642                         + " does not match last pid " + mMemWatchDumpPid);
17643                 return;
17644             }
17645             if (mMemWatchDumpFile == null || !mMemWatchDumpFile.equals(path)) {
17646                 Slog.w(TAG, "dumpHeapFinished: Calling path " + path
17647                         + " does not match last path " + mMemWatchDumpFile);
17648                 return;
17649             }
17650             if (DEBUG_PSS) Slog.d(TAG_PSS, "Dump heap finished for " + path);
17651             mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG);
17652 
17653             // Forced gc to clean up the remnant hprof fd.
17654             Runtime.getRuntime().gc();
17655         }
17656     }
17657 
17658     /** In this method we try to acquire our lock to make sure that we have not deadlocked */
monitor()17659     public void monitor() {
17660         synchronized (this) { }
17661     }
17662 
onCoreSettingsChange(Bundle settings)17663     void onCoreSettingsChange(Bundle settings) {
17664         synchronized (this) {
17665             mProcessList.updateCoreSettingsLocked(settings);
17666         }
17667     }
17668 
17669     // Multi-user methods
17670 
17671     /**
17672      * Start user, if its not already running, but don't bring it to foreground.
17673      */
17674     @Override
startUserInBackground(final int userId)17675     public boolean startUserInBackground(final int userId) {
17676         return startUserInBackgroundWithListener(userId, null);
17677     }
17678 
17679     @Override
startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17680     public boolean startUserInBackgroundWithListener(final int userId,
17681                 @Nullable IProgressListener unlockListener) {
17682         return mUserController.startUser(userId, /* foreground */ false, unlockListener);
17683     }
17684 
17685     @Override
startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17686     public boolean startUserInForegroundWithListener(final int userId,
17687             @Nullable IProgressListener unlockListener) {
17688         // Permission check done inside UserController.
17689         return mUserController.startUser(userId, /* foreground */ true, unlockListener);
17690     }
17691 
17692     @Override
unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener)17693     public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) {
17694         return mUserController.unlockUser(userId, token, secret, listener);
17695     }
17696 
17697     @Override
switchUser(final int targetUserId)17698     public boolean switchUser(final int targetUserId) {
17699         return mUserController.switchUser(targetUserId);
17700     }
17701 
17702     @Override
stopUser(final int userId, boolean force, final IStopUserCallback callback)17703     public int stopUser(final int userId, boolean force, final IStopUserCallback callback) {
17704         return mUserController.stopUser(userId, force, callback, null /* keyEvictedCallback */);
17705     }
17706 
17707     @Override
getCurrentUser()17708     public UserInfo getCurrentUser() {
17709         return mUserController.getCurrentUser();
17710     }
17711 
getStartedUserState(int userId)17712     String getStartedUserState(int userId) {
17713         final UserState userState = mUserController.getStartedUserState(userId);
17714         return UserState.stateToString(userState.state);
17715     }
17716 
17717     @Override
isUserRunning(int userId, int flags)17718     public boolean isUserRunning(int userId, int flags) {
17719         if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId())
17720                 && checkCallingPermission(INTERACT_ACROSS_USERS)
17721                     != PackageManager.PERMISSION_GRANTED) {
17722             String msg = "Permission Denial: isUserRunning() from pid="
17723                     + Binder.getCallingPid()
17724                     + ", uid=" + Binder.getCallingUid()
17725                     + " requires " + INTERACT_ACROSS_USERS;
17726             Slog.w(TAG, msg);
17727             throw new SecurityException(msg);
17728         }
17729         return mUserController.isUserRunning(userId, flags);
17730     }
17731 
17732     @Override
getRunningUserIds()17733     public int[] getRunningUserIds() {
17734         if (checkCallingPermission(INTERACT_ACROSS_USERS)
17735                 != PackageManager.PERMISSION_GRANTED) {
17736             String msg = "Permission Denial: isUserRunning() from pid="
17737                     + Binder.getCallingPid()
17738                     + ", uid=" + Binder.getCallingUid()
17739                     + " requires " + INTERACT_ACROSS_USERS;
17740             Slog.w(TAG, msg);
17741             throw new SecurityException(msg);
17742         }
17743         return mUserController.getStartedUserArray();
17744     }
17745 
17746     @Override
registerUserSwitchObserver(IUserSwitchObserver observer, String name)17747     public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
17748         mUserController.registerUserSwitchObserver(observer, name);
17749     }
17750 
17751     @Override
unregisterUserSwitchObserver(IUserSwitchObserver observer)17752     public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
17753         mUserController.unregisterUserSwitchObserver(observer);
17754     }
17755 
getAppInfoForUser(ApplicationInfo info, int userId)17756     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
17757         if (info == null) return null;
17758         ApplicationInfo newInfo = new ApplicationInfo(info);
17759         newInfo.initForUser(userId);
17760         return newInfo;
17761     }
17762 
isUserStopped(int userId)17763     public boolean isUserStopped(int userId) {
17764         return mUserController.getStartedUserState(userId) == null;
17765     }
17766 
getActivityInfoForUser(ActivityInfo aInfo, int userId)17767     ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
17768         if (aInfo == null
17769                 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
17770             return aInfo;
17771         }
17772 
17773         ActivityInfo info = new ActivityInfo(aInfo);
17774         info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
17775         return info;
17776     }
17777 
processSanityChecksLocked(ProcessRecord process)17778     private boolean processSanityChecksLocked(ProcessRecord process) {
17779         if (process == null || process.thread == null) {
17780             return false;
17781         }
17782 
17783         boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
17784         if (!isDebuggable) {
17785             if ((process.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17786                 return false;
17787             }
17788         }
17789 
17790         return true;
17791     }
17792 
startBinderTracking()17793     public boolean startBinderTracking() throws RemoteException {
17794         synchronized (this) {
17795             mBinderTransactionTrackingEnabled = true;
17796             // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17797             // permission (same as profileControl).
17798             if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17799                     != PackageManager.PERMISSION_GRANTED) {
17800                 throw new SecurityException("Requires permission "
17801                         + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17802             }
17803 
17804             for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
17805                 ProcessRecord process = mProcessList.mLruProcesses.get(i);
17806                 if (!processSanityChecksLocked(process)) {
17807                     continue;
17808                 }
17809                 try {
17810                     process.thread.startBinderTracking();
17811                 } catch (RemoteException e) {
17812                     Log.v(TAG, "Process disappared");
17813                 }
17814             }
17815             return true;
17816         }
17817     }
17818 
stopBinderTrackingAndDump(ParcelFileDescriptor fd)17819     public boolean stopBinderTrackingAndDump(ParcelFileDescriptor fd) throws RemoteException {
17820         try {
17821             synchronized (this) {
17822                 mBinderTransactionTrackingEnabled = false;
17823                 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17824                 // permission (same as profileControl).
17825                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17826                         != PackageManager.PERMISSION_GRANTED) {
17827                     throw new SecurityException("Requires permission "
17828                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17829                 }
17830 
17831                 if (fd == null) {
17832                     throw new IllegalArgumentException("null fd");
17833                 }
17834 
17835                 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor()));
17836                 pw.println("Binder transaction traces for all processes.\n");
17837                 for (ProcessRecord process : mProcessList.mLruProcesses) {
17838                     if (!processSanityChecksLocked(process)) {
17839                         continue;
17840                     }
17841 
17842                     pw.println("Traces for process: " + process.processName);
17843                     pw.flush();
17844                     try {
17845                         TransferPipe tp = new TransferPipe();
17846                         try {
17847                             process.thread.stopBinderTrackingAndDump(tp.getWriteFd());
17848                             tp.go(fd.getFileDescriptor());
17849                         } finally {
17850                             tp.kill();
17851                         }
17852                     } catch (IOException e) {
17853                         pw.println("Failure while dumping IPC traces from " + process +
17854                                 ".  Exception: " + e);
17855                         pw.flush();
17856                     } catch (RemoteException e) {
17857                         pw.println("Got a RemoteException while dumping IPC traces from " +
17858                                 process + ".  Exception: " + e);
17859                         pw.flush();
17860                     }
17861                 }
17862                 fd = null;
17863                 return true;
17864             }
17865         } finally {
17866             if (fd != null) {
17867                 try {
17868                     fd.close();
17869                 } catch (IOException e) {
17870                 }
17871             }
17872         }
17873     }
17874 
17875     @VisibleForTesting
17876     public final class LocalService extends ActivityManagerInternal {
17877         @Override
checkContentProviderAccess(String authority, int userId)17878         public String checkContentProviderAccess(String authority, int userId) {
17879             return ActivityManagerService.this.checkContentProviderAccess(authority, userId);
17880         }
17881 
17882         @Override
onWakefulnessChanged(int wakefulness)17883         public void onWakefulnessChanged(int wakefulness) {
17884             ActivityManagerService.this.onWakefulnessChanged(wakefulness);
17885         }
17886 
17887         @Override
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)17888         public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
17889                 String processName, String abiOverride, int uid, Runnable crashHandler) {
17890             return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
17891                     processName, abiOverride, uid, crashHandler);
17892         }
17893 
17894         @Override
killForegroundAppsForUser(int userHandle)17895         public void killForegroundAppsForUser(int userHandle) {
17896             synchronized (ActivityManagerService.this) {
17897                 final ArrayList<ProcessRecord> procs = new ArrayList<>();
17898                 final int NP = mProcessList.mProcessNames.getMap().size();
17899                 for (int ip = 0; ip < NP; ip++) {
17900                     final SparseArray<ProcessRecord> apps =
17901                             mProcessList.mProcessNames.getMap().valueAt(ip);
17902                     final int NA = apps.size();
17903                     for (int ia = 0; ia < NA; ia++) {
17904                         final ProcessRecord app = apps.valueAt(ia);
17905                         if (app.isPersistent()) {
17906                             // We don't kill persistent processes.
17907                             continue;
17908                         }
17909                         if (app.removed
17910                                 || (app.userId == userHandle && app.hasForegroundActivities())) {
17911                             procs.add(app);
17912                         }
17913                     }
17914                 }
17915 
17916                 final int N = procs.size();
17917                 for (int i = 0; i < N; i++) {
17918                     mProcessList.removeProcessLocked(procs.get(i), false, true, "kill all fg");
17919                 }
17920             }
17921         }
17922 
17923         @Override
setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken, long duration)17924         public void setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken,
17925                 long duration) {
17926             mPendingIntentController.setPendingIntentWhitelistDuration(target, whitelistToken,
17927                     duration);
17928         }
17929 
17930         @Override
setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken, int flags)17931         public void setPendingIntentAllowBgActivityStarts(IIntentSender target,
17932                 IBinder whitelistToken, int flags) {
17933             if (!(target instanceof PendingIntentRecord)) {
17934                 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():"
17935                         + " not a PendingIntentRecord: " + target);
17936                 return;
17937             }
17938             synchronized (ActivityManagerService.this) {
17939                 ((PendingIntentRecord) target).setAllowBgActivityStarts(whitelistToken, flags);
17940             }
17941         }
17942 
17943         @Override
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken)17944         public void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
17945                 IBinder whitelistToken) {
17946             if (!(target instanceof PendingIntentRecord)) {
17947                 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():"
17948                         + " not a PendingIntentRecord: " + target);
17949                 return;
17950             }
17951             synchronized (ActivityManagerService.this) {
17952                 ((PendingIntentRecord) target).clearAllowBgActivityStarts(whitelistToken);
17953             }
17954         }
17955 
17956         @Override
setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids)17957         public void setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids) {
17958             synchronized (ActivityManagerService.this) {
17959                 mDeviceIdleWhitelist = allAppids;
17960                 mDeviceIdleExceptIdleWhitelist = exceptIdleAppids;
17961             }
17962         }
17963 
17964         @Override
updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding)17965         public void updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding) {
17966             synchronized (ActivityManagerService.this) {
17967                 mDeviceIdleTempWhitelist = appids;
17968                 setAppIdTempWhitelistStateLocked(changingAppId, adding);
17969             }
17970         }
17971 
17972         @Override
getUidProcessState(int uid)17973         public int getUidProcessState(int uid) {
17974             return getUidState(uid);
17975         }
17976 
17977         @Override
isSystemReady()17978         public boolean isSystemReady() {
17979             // no need to synchronize(this) just to read & return the value
17980             return mSystemReady;
17981         }
17982 
17983         /**
17984          * Sets if the given pid has an overlay UI or not.
17985          *
17986          * @param pid The pid we are setting overlay UI for.
17987          * @param hasOverlayUi True if the process has overlay UI.
17988          * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
17989          */
17990         @Override
setHasOverlayUi(int pid, boolean hasOverlayUi)17991         public void setHasOverlayUi(int pid, boolean hasOverlayUi) {
17992             synchronized (ActivityManagerService.this) {
17993                 final ProcessRecord pr;
17994                 synchronized (mPidsSelfLocked) {
17995                     pr = mPidsSelfLocked.get(pid);
17996                     if (pr == null) {
17997                         Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid);
17998                         return;
17999                     }
18000                 }
18001                 if (pr.hasOverlayUi() == hasOverlayUi) {
18002                     return;
18003                 }
18004                 pr.setHasOverlayUi(hasOverlayUi);
18005                 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid);
18006                 updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
18007             }
18008         }
18009 
18010         /**
18011          * Called after the network policy rules are updated by
18012          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
18013          * and {@param procStateSeq}.
18014          */
18015         @Override
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)18016         public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
18017             if (DEBUG_NETWORK) {
18018                 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: "
18019                         + uid + " seq: " + procStateSeq);
18020             }
18021             UidRecord record;
18022             synchronized (ActivityManagerService.this) {
18023                 record = mProcessList.getUidRecordLocked(uid);
18024                 if (record == null) {
18025                     if (DEBUG_NETWORK) {
18026                         Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
18027                                 + " procStateSeq: " + procStateSeq);
18028                     }
18029                     return;
18030                 }
18031             }
18032             synchronized (record.networkStateLock) {
18033                 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
18034                     if (DEBUG_NETWORK) {
18035                         Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already"
18036                                 + " been handled for uid: " + uid);
18037                     }
18038                     return;
18039                 }
18040                 record.lastNetworkUpdatedProcStateSeq = procStateSeq;
18041                 if (record.curProcStateSeq > procStateSeq) {
18042                     if (DEBUG_NETWORK) {
18043                         Slog.d(TAG_NETWORK, "No need to handle older seq no., Uid: " + uid
18044                                 + ", curProcstateSeq: " + record.curProcStateSeq
18045                                 + ", procStateSeq: " + procStateSeq);
18046                     }
18047                     return;
18048                 }
18049                 if (record.waitingForNetwork) {
18050                     if (DEBUG_NETWORK) {
18051                         Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid
18052                                 + ", procStateSeq: " + procStateSeq);
18053                     }
18054                     record.networkStateLock.notifyAll();
18055                 }
18056             }
18057         }
18058 
18059         @Override
isRuntimeRestarted()18060         public boolean isRuntimeRestarted() {
18061             return mSystemServiceManager.isRuntimeRestarted();
18062         }
18063 
18064         @Override
canStartMoreUsers()18065         public boolean canStartMoreUsers() {
18066             return mUserController.canStartMoreUsers();
18067         }
18068 
18069         @Override
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)18070         public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
18071             mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage);
18072         }
18073 
18074         @Override
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)18075         public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
18076             mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage);
18077         }
18078 
18079         @Override
getMaxRunningUsers()18080         public int getMaxRunningUsers() {
18081             return mUserController.mMaxRunningUsers;
18082         }
18083 
18084         @Override
isUidActive(int uid)18085         public boolean isUidActive(int uid) {
18086             synchronized (ActivityManagerService.this) {
18087                 return isUidActiveLocked(uid);
18088             }
18089         }
18090 
18091         @Override
getMemoryStateForProcesses()18092         public List<ProcessMemoryState> getMemoryStateForProcesses() {
18093             List<ProcessMemoryState> processMemoryStates = new ArrayList<>();
18094             synchronized (mPidsSelfLocked) {
18095                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
18096                     final ProcessRecord r = mPidsSelfLocked.valueAt(i);
18097                     processMemoryStates.add(
18098                             new ProcessMemoryState(r.uid, r.pid, r.processName, r.curAdj));
18099                 }
18100             }
18101             return processMemoryStates;
18102         }
18103 
18104         @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)18105         public int handleIncomingUser(int callingPid, int callingUid, int userId,
18106                 boolean allowAll, int allowMode, String name, String callerPackage) {
18107             return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
18108                     allowMode, name, callerPackage);
18109         }
18110 
18111         @Override
enforceCallingPermission(String permission, String func)18112         public void enforceCallingPermission(String permission, String func) {
18113             ActivityManagerService.this.enforceCallingPermission(permission, func);
18114         }
18115 
18116         @Override
getCurrentUserId()18117         public int getCurrentUserId() {
18118             return mUserController.getCurrentUserId();
18119         }
18120 
18121         @Override
isUserRunning(int userId, int flags)18122         public boolean isUserRunning(int userId, int flags) {
18123             // Holding am lock isn't required to call into user controller.
18124             return mUserController.isUserRunning(userId, flags);
18125         }
18126 
18127         @Override
trimApplications()18128         public void trimApplications() {
18129             ActivityManagerService.this.trimApplications(OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
18130         }
18131 
killProcessesForRemovedTask(ArrayList<Object> procsToKill)18132         public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) {
18133             synchronized (ActivityManagerService.this) {
18134                 for (int i = 0; i < procsToKill.size(); i++) {
18135                     final WindowProcessController wpc =
18136                             (WindowProcessController) procsToKill.get(i);
18137                     final ProcessRecord pr = (ProcessRecord) wpc.mOwner;
18138                     if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
18139                             && pr.curReceivers.isEmpty()) {
18140                         pr.kill("remove task", true);
18141                     } else {
18142                         // We delay killing processes that are not in the background or running a
18143                         // receiver.
18144                         pr.waitingToKill = "remove task";
18145                     }
18146                 }
18147             }
18148         }
18149 
18150         @Override
killProcess(String processName, int uid, String reason)18151         public void killProcess(String processName, int uid, String reason) {
18152             synchronized (ActivityManagerService.this) {
18153                 final ProcessRecord proc = getProcessRecordLocked(processName, uid,
18154                         true /* keepIfLarge */);
18155                 if (proc != null) {
18156                     mProcessList.removeProcessLocked(proc, false /* callerWillRestart */,
18157                             true /* allowRestart */, reason);
18158                 }
18159             }
18160         }
18161 
18162         @Override
hasRunningActivity(int uid, @Nullable String packageName)18163         public boolean hasRunningActivity(int uid, @Nullable String packageName) {
18164             if (packageName == null) return false;
18165 
18166             synchronized (ActivityManagerService.this) {
18167                 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
18168                     final ProcessRecord pr = mProcessList.mLruProcesses.get(i);
18169                     if (pr.uid != uid) {
18170                         continue;
18171                     }
18172                     if (pr.getWindowProcessController().hasRunningActivity(packageName)) {
18173                         return true;
18174                     }
18175                 }
18176             }
18177             return false;
18178         }
18179 
18180         @Override
updateOomAdj()18181         public void updateOomAdj() {
18182             synchronized (ActivityManagerService.this) {
18183                 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
18184             }
18185         }
18186 
18187         @Override
updateCpuStats()18188         public void updateCpuStats() {
18189             synchronized (ActivityManagerService.this) {
18190                 ActivityManagerService.this.updateCpuStats();
18191             }
18192         }
18193 
18194         @Override
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)18195         public void updateBatteryStats(ComponentName activity, int uid, int userId,
18196                 boolean resumed) {
18197             synchronized (ActivityManagerService.this) {
18198                 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed);
18199             }
18200         }
18201 
18202         @Override
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)18203         public void updateActivityUsageStats(ComponentName activity, int userId, int event,
18204                 IBinder appToken, ComponentName taskRoot) {
18205             synchronized (ActivityManagerService.this) {
18206                 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event,
18207                         appToken, taskRoot);
18208             }
18209         }
18210 
18211         @Override
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)18212         public void updateForegroundTimeIfOnBattery(
18213                 String packageName, int uid, long cpuTimeDiff) {
18214             synchronized (ActivityManagerService.this) {
18215                 if (!mBatteryStatsService.isOnBattery()) {
18216                     return;
18217                 }
18218                 final BatteryStatsImpl bsi = mBatteryStatsService.getActiveStatistics();
18219                 synchronized (bsi) {
18220                     final BatteryStatsImpl.Uid.Proc ps =
18221                             bsi.getProcessStatsLocked(uid, packageName);
18222                     if (ps != null) {
18223                         ps.addForegroundTimeLocked(cpuTimeDiff);
18224                     }
18225                 }
18226             }
18227         }
18228 
18229         @Override
sendForegroundProfileChanged(int userId)18230         public void sendForegroundProfileChanged(int userId) {
18231             mUserController.sendForegroundProfileChanged(userId);
18232         }
18233 
18234         @Override
shouldConfirmCredentials(int userId)18235         public boolean shouldConfirmCredentials(int userId) {
18236             return mUserController.shouldConfirmCredentials(userId);
18237         }
18238 
18239         @Override
getCurrentProfileIds()18240         public int[] getCurrentProfileIds() {
18241             return mUserController.getCurrentProfileIds();
18242         }
18243 
18244         @Override
getCurrentUser()18245         public UserInfo getCurrentUser() {
18246             return mUserController.getCurrentUser();
18247         }
18248 
18249         @Override
ensureNotSpecialUser(int userId)18250         public void ensureNotSpecialUser(int userId) {
18251             mUserController.ensureNotSpecialUser(userId);
18252         }
18253 
18254         @Override
isCurrentProfile(int userId)18255         public boolean isCurrentProfile(int userId) {
18256             return mUserController.isCurrentProfile(userId);
18257         }
18258 
18259         @Override
hasStartedUserState(int userId)18260         public boolean hasStartedUserState(int userId) {
18261             return mUserController.hasStartedUserState(userId);
18262         }
18263 
18264         @Override
finishUserSwitch(Object uss)18265         public void finishUserSwitch(Object uss) {
18266             mUserController.finishUserSwitch((UserState) uss);
18267         }
18268 
18269         @Override
scheduleAppGcs()18270         public void scheduleAppGcs() {
18271             synchronized (ActivityManagerService.this) {
18272                 ActivityManagerService.this.scheduleAppGcsLocked();
18273             }
18274         }
18275 
18276         @Override
getTaskIdForActivity(IBinder token, boolean onlyRoot)18277         public int getTaskIdForActivity(IBinder token, boolean onlyRoot) {
18278             synchronized (ActivityManagerService.this) {
18279                 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot);
18280             }
18281         }
18282 
18283         @Override
getActivityPresentationInfo(IBinder token)18284         public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
18285             int displayId = Display.INVALID_DISPLAY;
18286             try {
18287                 displayId = mActivityTaskManager.getActivityDisplayId(token);
18288             } catch (RemoteException e) {
18289             }
18290 
18291             return new ActivityPresentationInfo(mActivityTaskManager.getTaskForActivity(token,
18292                     /*onlyRoot=*/ false), displayId,
18293                     mActivityTaskManager.getActivityClassForToken(token));
18294         }
18295 
18296         @Override
setBooting(boolean booting)18297         public void setBooting(boolean booting) {
18298             mBooting = booting;
18299         }
18300 
18301         @Override
isBooting()18302         public boolean isBooting() {
18303             return mBooting;
18304         }
18305 
18306         @Override
setBooted(boolean booted)18307         public void setBooted(boolean booted) {
18308             mBooted = booted;
18309         }
18310 
18311         @Override
isBooted()18312         public boolean isBooted() {
18313             return mBooted;
18314         }
18315 
18316         @Override
finishBooting()18317         public void finishBooting() {
18318             ActivityManagerService.this.finishBooting();
18319         }
18320 
18321         @Override
tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, String tag)18322         public void tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid,
18323                 long duration, String tag) {
18324             synchronized (ActivityManagerService.this) {
18325                 ActivityManagerService.this.tempWhitelistForPendingIntentLocked(
18326                         callerPid, callerUid, targetUid, duration, tag);
18327             }
18328         }
18329 
18330         @Override
broadcastIntentInPackage(String packageName, 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)18331         public int broadcastIntentInPackage(String packageName, int uid, int realCallingUid,
18332                 int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo,
18333                 int resultCode, String resultData, Bundle resultExtras, String requiredPermission,
18334                 Bundle bOptions, boolean serialized, boolean sticky, int userId,
18335                 boolean allowBackgroundActivityStarts) {
18336             synchronized (ActivityManagerService.this) {
18337                 return ActivityManagerService.this.broadcastIntentInPackage(packageName, uid,
18338                         realCallingUid, realCallingPid, intent, resolvedType, resultTo, resultCode,
18339                         resultData, resultExtras, requiredPermission, bOptions, serialized, sticky,
18340                         userId, allowBackgroundActivityStarts);
18341             }
18342         }
18343 
18344         @Override
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, int userId, boolean allowBackgroundActivityStarts)18345         public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType,
18346                 boolean fgRequired, String callingPackage, int userId,
18347                 boolean allowBackgroundActivityStarts) throws TransactionTooLargeException {
18348             synchronized(ActivityManagerService.this) {
18349                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
18350                         "startServiceInPackage: " + service + " type=" + resolvedType);
18351                 final long origId = Binder.clearCallingIdentity();
18352                 ComponentName res;
18353                 try {
18354                     res = mServices.startServiceLocked(null, service,
18355                             resolvedType, -1, uid, fgRequired, callingPackage, userId,
18356                             allowBackgroundActivityStarts);
18357                 } finally {
18358                     Binder.restoreCallingIdentity(origId);
18359                 }
18360                 return res;
18361             }
18362         }
18363 
18364         // The arguments here are untyped because the base ActivityManagerInternal class
18365         // doesn't have compile-time visiblity into ActivityServiceConnectionHolder or
18366         // ConnectionRecord.
18367         @Override
disconnectActivityFromServices(Object connectionHolder, Object conns)18368         public void disconnectActivityFromServices(Object connectionHolder, Object conns) {
18369             // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder
18370             // 'conns' is an untyped HashSet<ConnectionRecord>
18371             final ActivityServiceConnectionsHolder holder =
18372                     (ActivityServiceConnectionsHolder) connectionHolder;
18373             final HashSet<ConnectionRecord> toDisconnect = (HashSet<ConnectionRecord>) conns;
18374             synchronized(ActivityManagerService.this) {
18375                 for (ConnectionRecord cr : toDisconnect) {
18376                     mServices.removeConnectionLocked(cr, null, holder);
18377                 }
18378             }
18379         }
18380 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)18381         public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
18382             synchronized(ActivityManagerService.this) {
18383                 mServices.cleanUpServices(userId, component, baseIntent);
18384             }
18385         }
18386 
getActivityInfoForUser(ActivityInfo aInfo, int userId)18387         public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
18388             // Locked intentionally not held as it isn't needed for this case.
18389             return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId);
18390         }
18391 
ensureBootCompleted()18392         public void ensureBootCompleted() {
18393             // Locked intentionally not held as it isn't needed for this case.
18394             ActivityManagerService.this.ensureBootCompleted();
18395         }
18396 
updateOomLevelsForDisplay(int displayId)18397         public void updateOomLevelsForDisplay(int displayId) {
18398             synchronized(ActivityManagerService.this) {
18399                 if (mWindowManager != null) {
18400                     mProcessList.applyDisplaySize(mWindowManager);
18401                 }
18402             }
18403         }
18404 
isActivityStartsLoggingEnabled()18405         public boolean isActivityStartsLoggingEnabled() {
18406             return mConstants.mFlagActivityStartsLoggingEnabled;
18407         }
18408 
isBackgroundActivityStartsEnabled()18409         public boolean isBackgroundActivityStartsEnabled() {
18410             return mConstants.mFlagBackgroundActivityStartsEnabled;
18411         }
18412 
reportCurKeyguardUsageEvent(boolean keyguardShowing)18413         public void reportCurKeyguardUsageEvent(boolean keyguardShowing) {
18414             synchronized(ActivityManagerService.this) {
18415                 ActivityManagerService.this.reportGlobalUsageEventLocked(keyguardShowing
18416                         ? UsageEvents.Event.KEYGUARD_SHOWN
18417                         : UsageEvents.Event.KEYGUARD_HIDDEN);
18418             }
18419         }
18420 
18421         @Override
inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)18422         public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) {
18423             synchronized (ActivityManagerService.this) {
18424                 return ActivityManagerService.this.inputDispatchingTimedOut(
18425                         pid, aboveSystem, reason);
18426             }
18427         }
18428 
18429         @Override
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)18430         public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
18431                 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
18432                 boolean aboveSystem, String reason) {
18433             return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc,
18434                     activityShortComponentName, aInfo, parentShortComponentName,
18435                     (WindowProcessController) parentProc, aboveSystem, reason);
18436 
18437         }
18438 
18439         @Override
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)18440         public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) {
18441             synchronized (ActivityManagerService.this) {
18442                 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
18443                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18444                         | Intent.FLAG_RECEIVER_REPLACE_PENDING
18445                         | Intent.FLAG_RECEIVER_FOREGROUND
18446                         | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18447                 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
18448                         OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
18449                         Binder.getCallingPid(), UserHandle.USER_ALL);
18450                 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
18451                     intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
18452                     intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
18453                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
18454                             | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18455                     if (initLocale || !mProcessesReady) {
18456                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
18457                     }
18458                     broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
18459                             OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
18460                             Binder.getCallingPid(), UserHandle.USER_ALL);
18461                 }
18462 
18463                 // Send a broadcast to PackageInstallers if the configuration change is interesting
18464                 // for the purposes of installing additional splits.
18465                 if (!initLocale && isSplitConfigurationChange(changes)) {
18466                     intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
18467                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
18468                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
18469 
18470                     // Typically only app stores will have this permission.
18471                     String[] permissions =
18472                             new String[] { android.Manifest.permission.INSTALL_PACKAGES };
18473                     broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
18474                             permissions, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
18475                             Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
18476                 }
18477             }
18478         }
18479 
18480         /**
18481          * Returns true if this configuration change is interesting enough to send an
18482          * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
18483          */
isSplitConfigurationChange(int configDiff)18484         private boolean isSplitConfigurationChange(int configDiff) {
18485             return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
18486         }
18487 
18488         @Override
broadcastCloseSystemDialogs(String reason)18489         public void broadcastCloseSystemDialogs(String reason) {
18490             synchronized (ActivityManagerService.this) {
18491                 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
18492                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18493                         | Intent.FLAG_RECEIVER_FOREGROUND);
18494                 if (reason != null) {
18495                     intent.putExtra("reason", reason);
18496                 }
18497 
18498                 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
18499                         OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
18500                         Binder.getCallingPid(), UserHandle.USER_ALL);
18501             }
18502         }
18503 
18504         @Override
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)18505         public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
18506             synchronized (ActivityManagerService.this) {
18507                 ActivityManagerService.this.killAllBackgroundProcessesExcept(
18508                         minTargetSdk, maxProcState);
18509             }
18510         }
18511 
18512         @Override
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName)18513         public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
18514                 boolean isTop, String hostingType, ComponentName hostingName) {
18515             try {
18516                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18517                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
18518                             + processName);
18519                 }
18520                 synchronized (ActivityManagerService.this) {
18521                     // If the process is known as top app, set a hint so when the process is
18522                     // started, the top priority can be applied immediately to avoid cpu being
18523                     // preempted by other processes before attaching the process of top app.
18524                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
18525                             new HostingRecord(hostingType, hostingName, isTop),
18526                             ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
18527                             false /* isolated */, true /* keepIfLarge */);
18528                 }
18529             } finally {
18530                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18531             }
18532         }
18533 
18534         @Override
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)18535         public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
18536                 ProfilerInfo profilerInfo, Object wmLock) {
18537             synchronized (ActivityManagerService.this) {
18538                 /**
18539                  * This function is called from the window manager context and needs to be executed
18540                  * synchronously.  To avoid deadlock, we pass a message to AMS to execute the
18541                  * function and notify the passed in lock when it has been completed.
18542                  */
18543                 synchronized (wmLock) {
18544                     if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
18545                         setDebugApp(aInfo.processName, true, false);
18546                     }
18547 
18548                     if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
18549                         setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
18550                     }
18551 
18552                     if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
18553                         setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
18554                     }
18555 
18556                     if (profilerInfo != null) {
18557                         setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
18558                     }
18559                     wmLock.notify();
18560                 }
18561             }
18562         }
18563 
18564         @Override
getStorageMountMode(int pid, int uid)18565         public int getStorageMountMode(int pid, int uid) {
18566             if (uid == SHELL_UID || uid == ROOT_UID) {
18567                 return Zygote.MOUNT_EXTERNAL_FULL;
18568             }
18569             synchronized (mPidsSelfLocked) {
18570                 final ProcessRecord pr = mPidsSelfLocked.get(pid);
18571                 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.mountMode;
18572             }
18573         }
18574 
18575         @Override
isAppForeground(int uid)18576         public boolean isAppForeground(int uid) {
18577             return ActivityManagerService.this.isAppForeground(uid);
18578         }
18579 
18580         @Override
isAppBad(ApplicationInfo info)18581         public boolean isAppBad(ApplicationInfo info) {
18582             return ActivityManagerService.this.isAppBad(info);
18583         }
18584 
18585         @Override
clearPendingBackup(int userId)18586         public void clearPendingBackup(int userId) {
18587             ActivityManagerService.this.clearPendingBackup(userId);
18588         }
18589 
18590         /**
18591          * When power button is very long pressed, call this interface to do some pre-shutdown work
18592          * like persisting database etc.
18593          */
18594         @Override
prepareForPossibleShutdown()18595         public void prepareForPossibleShutdown() {
18596             ActivityManagerService.this.prepareForPossibleShutdown();
18597         }
18598 
18599         @Override
hasRunningForegroundService(int uid, int foregroundServicetype)18600         public boolean hasRunningForegroundService(int uid, int foregroundServicetype) {
18601             synchronized (ActivityManagerService.this) {
18602                 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
18603                     final ProcessRecord pr = mProcessList.mLruProcesses.get(i);
18604                     if (pr.uid != uid) {
18605                         continue;
18606                     }
18607 
18608                     if ((pr.getForegroundServiceTypes() & foregroundServicetype) != 0) {
18609                         return true;
18610                     }
18611                 }
18612             }
18613 
18614             return false;
18615         }
18616 
18617         @Override
registerProcessObserver(IProcessObserver processObserver)18618         public void registerProcessObserver(IProcessObserver processObserver) {
18619             ActivityManagerService.this.registerProcessObserver(processObserver);
18620         }
18621 
18622         @Override
unregisterProcessObserver(IProcessObserver processObserver)18623         public void unregisterProcessObserver(IProcessObserver processObserver) {
18624             ActivityManagerService.this.unregisterProcessObserver(processObserver);
18625         }
18626 
18627         @Override
isActiveInstrumentation(int uid)18628         public boolean isActiveInstrumentation(int uid) {
18629             return ActivityManagerService.this.isActiveInstrumentation(uid);
18630         }
18631     }
18632 
inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason)18633     long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
18634         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
18635             throw new SecurityException("Requires permission " + FILTER_EVENTS);
18636         }
18637         ProcessRecord proc;
18638         long timeout;
18639         synchronized (this) {
18640             synchronized (mPidsSelfLocked) {
18641                 proc = mPidsSelfLocked.get(pid);
18642             }
18643             timeout = proc != null ? proc.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
18644         }
18645 
18646         if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) {
18647             return -1;
18648         }
18649 
18650         return timeout;
18651     }
18652 
18653     /**
18654      * Handle input dispatching timeouts.
18655      * @return whether input dispatching should be aborted or not.
18656      */
inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, WindowProcessController parentProcess, boolean aboveSystem, String reason)18657     boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName,
18658             ApplicationInfo aInfo, String parentShortComponentName,
18659             WindowProcessController parentProcess, boolean aboveSystem, String reason) {
18660         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
18661             throw new SecurityException("Requires permission " + FILTER_EVENTS);
18662         }
18663 
18664         final String annotation;
18665         if (reason == null) {
18666             annotation = "Input dispatching timed out";
18667         } else {
18668             annotation = "Input dispatching timed out (" + reason + ")";
18669         }
18670 
18671         if (proc != null) {
18672             synchronized (this) {
18673                 if (proc.isDebugging()) {
18674                     return false;
18675                 }
18676 
18677                 if (proc.getActiveInstrumentation() != null) {
18678                     Bundle info = new Bundle();
18679                     info.putString("shortMsg", "keyDispatchingTimedOut");
18680                     info.putString("longMsg", annotation);
18681                     finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
18682                     return true;
18683                 }
18684             }
18685             proc.appNotResponding(activityShortComponentName, aInfo,
18686                     parentShortComponentName, parentProcess, aboveSystem, annotation);
18687         }
18688 
18689         return true;
18690     }
18691 
18692     /**
18693      * Called by app main thread to wait for the network policy rules to get updated.
18694      *
18695      * @param procStateSeq The sequence number indicating the process state change that the main
18696      *                     thread is interested in.
18697      */
18698     @Override
waitForNetworkStateUpdate(long procStateSeq)18699     public void waitForNetworkStateUpdate(long procStateSeq) {
18700         final int callingUid = Binder.getCallingUid();
18701         if (DEBUG_NETWORK) {
18702             Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq);
18703         }
18704         UidRecord record;
18705         synchronized (this) {
18706             record = mProcessList.getUidRecordLocked(callingUid);
18707             if (record == null) {
18708                 return;
18709             }
18710         }
18711         synchronized (record.networkStateLock) {
18712             if (record.lastDispatchedProcStateSeq < procStateSeq) {
18713                 if (DEBUG_NETWORK) {
18714                     Slog.d(TAG_NETWORK, "Uid state change for seq no. " + procStateSeq + " is not "
18715                             + "dispatched to NPMS yet, so don't wait. Uid: " + callingUid
18716                             + " lastProcStateSeqDispatchedToObservers: "
18717                             + record.lastDispatchedProcStateSeq);
18718                 }
18719                 return;
18720             }
18721             if (record.curProcStateSeq > procStateSeq) {
18722                 if (DEBUG_NETWORK) {
18723                     Slog.d(TAG_NETWORK, "Ignore the wait requests for older seq numbers. Uid: "
18724                             + callingUid + ", curProcStateSeq: " + record.curProcStateSeq
18725                             + ", procStateSeq: " + procStateSeq);
18726                 }
18727                 return;
18728             }
18729             if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
18730                 if (DEBUG_NETWORK) {
18731                     Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. "
18732                             + procStateSeq + ", so no need to wait. Uid: "
18733                             + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: "
18734                             + record.lastNetworkUpdatedProcStateSeq);
18735                 }
18736                 return;
18737             }
18738             try {
18739                 if (DEBUG_NETWORK) {
18740                     Slog.d(TAG_NETWORK, "Starting to wait for the network rules update."
18741                         + " Uid: " + callingUid + " procStateSeq: " + procStateSeq);
18742                 }
18743                 final long startTime = SystemClock.uptimeMillis();
18744                 record.waitingForNetwork = true;
18745                 record.networkStateLock.wait(mWaitForNetworkTimeoutMs);
18746                 record.waitingForNetwork = false;
18747                 final long totalTime = SystemClock.uptimeMillis() - startTime;
18748                 if (totalTime >= mWaitForNetworkTimeoutMs || DEBUG_NETWORK) {
18749                     Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: "
18750                             + totalTime + ". Uid: " + callingUid + " procStateSeq: "
18751                             + procStateSeq + " UidRec: " + record
18752                             + " validateUidRec: " + mValidateUids.get(callingUid));
18753                 }
18754             } catch (InterruptedException e) {
18755                 Thread.currentThread().interrupt();
18756             }
18757         }
18758     }
18759 
waitForBroadcastIdle(PrintWriter pw)18760     public void waitForBroadcastIdle(PrintWriter pw) {
18761         enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()");
18762         while (true) {
18763             boolean idle = true;
18764             synchronized (this) {
18765                 for (BroadcastQueue queue : mBroadcastQueues) {
18766                     if (!queue.isIdle()) {
18767                         final String msg = "Waiting for queue " + queue + " to become idle...";
18768                         pw.println(msg);
18769                         pw.println(queue.describeState());
18770                         pw.flush();
18771                         Slog.v(TAG, msg);
18772                         queue.cancelDeferrals();
18773                         idle = false;
18774                     }
18775                 }
18776             }
18777 
18778             if (idle) {
18779                 final String msg = "All broadcast queues are idle!";
18780                 pw.println(msg);
18781                 pw.flush();
18782                 Slog.v(TAG, msg);
18783                 return;
18784             } else {
18785                 SystemClock.sleep(1000);
18786             }
18787         }
18788     }
18789 
18790     /**
18791      * Kill processes for the user with id userId and that depend on the package named packageName
18792      */
18793     @Override
killPackageDependents(String packageName, int userId)18794     public void killPackageDependents(String packageName, int userId) {
18795         enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()");
18796         if (packageName == null) {
18797             throw new NullPointerException(
18798                     "Cannot kill the dependents of a package without its name.");
18799         }
18800 
18801         long callingId = Binder.clearCallingIdentity();
18802         IPackageManager pm = AppGlobals.getPackageManager();
18803         int pkgUid = -1;
18804         try {
18805             pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
18806         } catch (RemoteException e) {
18807         }
18808         if (userId != UserHandle.USER_ALL && pkgUid == -1) {
18809             throw new IllegalArgumentException(
18810                     "Cannot kill dependents of non-existing package " + packageName);
18811         }
18812         try {
18813             synchronized(this) {
18814                 mProcessList.killPackageProcessesLocked(packageName, UserHandle.getAppId(pkgUid),
18815                         userId, ProcessList.FOREGROUND_APP_ADJ, "dep: " + packageName);
18816             }
18817         } finally {
18818             Binder.restoreCallingIdentity(callingId);
18819         }
18820     }
18821 
18822     @Override
restartUserInBackground(final int userId)18823     public int restartUserInBackground(final int userId) {
18824         return mUserController.restartUser(userId, /* foreground */ false);
18825     }
18826 
18827     @Override
scheduleApplicationInfoChanged(List<String> packageNames, int userId)18828     public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) {
18829         enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
18830                 "scheduleApplicationInfoChanged()");
18831 
18832         synchronized (this) {
18833             final long origId = Binder.clearCallingIdentity();
18834             try {
18835                 updateApplicationInfoLocked(packageNames, userId);
18836             } finally {
18837                 Binder.restoreCallingIdentity(origId);
18838             }
18839         }
18840     }
18841 
18842     /**
18843      * Synchronously update the system ActivityThread, bypassing any deferred threading so any
18844      * resources and overlaid values are available immediately.
18845      */
updateSystemUiContext()18846     public void updateSystemUiContext() {
18847         PackageManagerInternal packageManagerInternal;
18848         synchronized (this) {
18849             packageManagerInternal = getPackageManagerInternalLocked();
18850         }
18851 
18852         ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android",
18853                 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM);
18854         ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai);
18855     }
18856 
updateApplicationInfoLocked(@onNull List<String> packagesToUpdate, int userId)18857     void updateApplicationInfoLocked(@NonNull List<String> packagesToUpdate, int userId) {
18858         final boolean updateFrameworkRes = packagesToUpdate.contains("android");
18859         if (updateFrameworkRes) {
18860             PackageParser.readConfigUseRoundIcon(null);
18861         }
18862         mProcessList.updateApplicationInfoLocked(packagesToUpdate, userId, updateFrameworkRes);
18863 
18864         if (updateFrameworkRes) {
18865             // Update system server components that need to know about changed overlays. Because the
18866             // overlay is applied in ActivityThread, we need to serialize through its thread too.
18867             final Executor executor = ActivityThread.currentActivityThread().getExecutor();
18868             final DisplayManagerInternal display =
18869                     LocalServices.getService(DisplayManagerInternal.class);
18870             if (display != null) {
18871                 executor.execute(display::onOverlayChanged);
18872             }
18873             if (mWindowManager != null) {
18874                 executor.execute(mWindowManager::onOverlayChanged);
18875             }
18876         }
18877     }
18878 
18879     /**
18880      * Attach an agent to the specified process (proces name or PID)
18881      */
attachAgent(String process, String path)18882     public void attachAgent(String process, String path) {
18883         try {
18884             synchronized (this) {
18885                 ProcessRecord proc = findProcessLocked(process, UserHandle.USER_SYSTEM,
18886                         "attachAgent");
18887                 if (proc == null || proc.thread == null) {
18888                     throw new IllegalArgumentException("Unknown process: " + process);
18889                 }
18890 
18891                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
18892                 if (!isDebuggable) {
18893                     if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
18894                         throw new SecurityException("Process not debuggable: " + proc);
18895                     }
18896                 }
18897 
18898                 proc.thread.attachAgent(path);
18899             }
18900         } catch (RemoteException e) {
18901             throw new IllegalStateException("Process disappeared");
18902         }
18903     }
18904 
18905     /**
18906      * When power button is very long pressed, call this interface to do some pre-shutdown work
18907      * like persisting database etc.
18908      */
prepareForPossibleShutdown()18909     public void prepareForPossibleShutdown() {
18910         synchronized (this) {
18911             if (mUsageStatsService != null) {
18912                 mUsageStatsService.prepareForPossibleShutdown();
18913             }
18914         }
18915     }
18916 
18917     @VisibleForTesting
18918     public static class Injector {
18919         private NetworkManagementInternal mNmi;
18920 
getContext()18921         public Context getContext() {
18922             return null;
18923         }
18924 
getAppOpsService(File file, Handler handler)18925         public AppOpsService getAppOpsService(File file, Handler handler) {
18926             return new AppOpsService(file, handler);
18927         }
18928 
getUiHandler(ActivityManagerService service)18929         public Handler getUiHandler(ActivityManagerService service) {
18930             return service.new UiHandler();
18931         }
18932 
isNetworkRestrictedForUid(int uid)18933         public boolean isNetworkRestrictedForUid(int uid) {
18934             if (ensureHasNetworkManagementInternal()) {
18935                 return mNmi.isNetworkRestrictedForUid(uid);
18936             }
18937             return false;
18938         }
18939 
ensureHasNetworkManagementInternal()18940         private boolean ensureHasNetworkManagementInternal() {
18941             if (mNmi == null) {
18942                 mNmi = LocalServices.getService(NetworkManagementInternal.class);
18943             }
18944             return mNmi != null;
18945         }
18946     }
18947 
18948     @Override
startDelegateShellPermissionIdentity(int delegateUid, @Nullable String[] permissions)18949     public void startDelegateShellPermissionIdentity(int delegateUid,
18950             @Nullable String[] permissions) {
18951         if (UserHandle.getCallingAppId() != Process.SHELL_UID
18952                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
18953             throw new SecurityException("Only the shell can delegate its permissions");
18954         }
18955 
18956         // We allow delegation only to one instrumentation started from the shell
18957         synchronized (ActivityManagerService.this) {
18958             // If there is a delegate it should be the same instance for app ops and permissions.
18959             if (mAppOpsService.getAppOpsServiceDelegate()
18960                     != getPackageManagerInternalLocked().getCheckPermissionDelegate()) {
18961                 throw new IllegalStateException("Bad shell delegate state");
18962             }
18963 
18964             // If the delegate is already set up for the target UID, nothing to do.
18965             if (mAppOpsService.getAppOpsServiceDelegate() != null) {
18966                 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) {
18967                     throw new IllegalStateException("Bad shell delegate state");
18968                 }
18969                 final ShellDelegate delegate = (ShellDelegate) mAppOpsService
18970                         .getAppOpsServiceDelegate();
18971                 if (delegate.getDelegateUid() != delegateUid) {
18972                     throw new SecurityException("Shell can delegate permissions only "
18973                             + "to one instrumentation at a time");
18974                 }
18975                 delegate.setPermissions(permissions);
18976                 return;
18977             }
18978 
18979             final int instrCount = mActiveInstrumentation.size();
18980             for (int i = 0; i < instrCount; i++) {
18981                 final ActiveInstrumentation instr = mActiveInstrumentation.get(i);
18982                 if (instr.mTargetInfo.uid != delegateUid) {
18983                     continue;
18984                 }
18985                 // If instrumentation started from the shell the connection is not null
18986                 if (instr.mUiAutomationConnection == null) {
18987                     throw new SecurityException("Shell can delegate its permissions" +
18988                             " only to an instrumentation started from the shell");
18989                 }
18990 
18991                 // Hook them up...
18992                 final ShellDelegate shellDelegate = new ShellDelegate(
18993                         instr.mTargetInfo.packageName, delegateUid, permissions);
18994                 mAppOpsService.setAppOpsServiceDelegate(shellDelegate);
18995                 getPackageManagerInternalLocked().setCheckPermissionDelegate(shellDelegate);
18996                 return;
18997             }
18998         }
18999     }
19000 
19001     @Override
stopDelegateShellPermissionIdentity()19002     public void stopDelegateShellPermissionIdentity() {
19003         if (UserHandle.getCallingAppId() != Process.SHELL_UID
19004                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
19005             throw new SecurityException("Only the shell can delegate its permissions");
19006         }
19007         synchronized (ActivityManagerService.this) {
19008             mAppOpsService.setAppOpsServiceDelegate(null);
19009             getPackageManagerInternalLocked().setCheckPermissionDelegate(null);
19010         }
19011     }
19012 
19013     private class ShellDelegate implements CheckOpsDelegate, CheckPermissionDelegate {
19014         private final String mTargetPackageName;
19015         private final int mTargetUid;
19016         private @Nullable String[] mPermissions;
19017 
ShellDelegate(String targetPacakgeName, int targetUid, @Nullable String[] permissions)19018         ShellDelegate(String targetPacakgeName, int targetUid, @Nullable String[] permissions) {
19019             mTargetPackageName = targetPacakgeName;
19020             mTargetUid = targetUid;
19021             mPermissions = permissions;
19022         }
19023 
getDelegateUid()19024         int getDelegateUid() {
19025             return mTargetUid;
19026         }
19027 
setPermissions(@ullable String[] permissions)19028         void setPermissions(@Nullable String[] permissions) {
19029             mPermissions = permissions;
19030         }
19031 
19032         @Override
checkOperation(int code, int uid, String packageName, boolean raw, QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl)19033         public int checkOperation(int code, int uid, String packageName, boolean raw,
19034                 QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl) {
19035             if (uid == mTargetUid && isTargetOp(code)) {
19036                 final long identity = Binder.clearCallingIdentity();
19037                 try {
19038                     return superImpl.apply(code, Process.SHELL_UID,
19039                             "com.android.shell", raw);
19040                 } finally {
19041                     Binder.restoreCallingIdentity(identity);
19042                 }
19043             }
19044             return superImpl.apply(code, uid, packageName, raw);
19045         }
19046 
19047         @Override
checkAudioOperation(int code, int usage, int uid, String packageName, QuadFunction<Integer, Integer, Integer, String, Integer> superImpl)19048         public int checkAudioOperation(int code, int usage, int uid, String packageName,
19049                 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) {
19050             if (uid == mTargetUid && isTargetOp(code)) {
19051                 final long identity = Binder.clearCallingIdentity();
19052                 try {
19053                     return superImpl.apply(code, usage, Process.SHELL_UID,
19054                             "com.android.shell");
19055                 } finally {
19056                     Binder.restoreCallingIdentity(identity);
19057                 }
19058             }
19059             return superImpl.apply(code, usage, uid, packageName);
19060         }
19061 
19062         @Override
noteOperation(int code, int uid, String packageName, TriFunction<Integer, Integer, String, Integer> superImpl)19063         public int noteOperation(int code, int uid, String packageName,
19064                 TriFunction<Integer, Integer, String, Integer> superImpl) {
19065             if (uid == mTargetUid && isTargetOp(code)) {
19066                 final long identity = Binder.clearCallingIdentity();
19067                 try {
19068                     return mAppOpsService.noteProxyOperation(code, Process.SHELL_UID,
19069                             "com.android.shell", uid, packageName);
19070                 } finally {
19071                     Binder.restoreCallingIdentity(identity);
19072                 }
19073             }
19074             return superImpl.apply(code, uid, packageName);
19075         }
19076 
19077         @Override
checkPermission(String permName, String pkgName, int userId, TriFunction<String, String, Integer, Integer> superImpl)19078         public int checkPermission(String permName, String pkgName, int userId,
19079                 TriFunction<String, String, Integer, Integer> superImpl) {
19080             if (mTargetPackageName.equals(pkgName) && isTargetPermission(permName)) {
19081                 final long identity = Binder.clearCallingIdentity();
19082                 try {
19083                     return superImpl.apply(permName, "com.android.shell", userId);
19084                 } finally {
19085                     Binder.restoreCallingIdentity(identity);
19086                 }
19087             }
19088             return superImpl.apply(permName, pkgName, userId);
19089         }
19090 
19091         @Override
checkUidPermission(String permName, int uid, BiFunction<String, Integer, Integer> superImpl)19092         public int checkUidPermission(String permName, int uid,
19093                 BiFunction<String, Integer, Integer> superImpl) {
19094             if (uid == mTargetUid  && isTargetPermission(permName)) {
19095                 final long identity = Binder.clearCallingIdentity();
19096                 try {
19097                     return superImpl.apply(permName, Process.SHELL_UID);
19098                 } finally {
19099                     Binder.restoreCallingIdentity(identity);
19100                 }
19101             }
19102             return superImpl.apply(permName, uid);
19103         }
19104 
isTargetOp(int code)19105         private boolean isTargetOp(int code) {
19106             // null permissions means all ops are targeted
19107             if (mPermissions == null) {
19108                 return true;
19109             }
19110             // no permission for the op means the op is targeted
19111             final String permission = AppOpsManager.opToPermission(code);
19112             if (permission == null) {
19113                 return true;
19114             }
19115             return isTargetPermission(permission);
19116         }
19117 
isTargetPermission(@onNull String permission)19118         private boolean isTargetPermission(@NonNull String permission) {
19119             // null permissions means all permissions are targeted
19120             return (mPermissions == null || ArrayUtils.contains(mPermissions, permission));
19121         }
19122     }
19123 
19124     /**
19125      * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would
19126      * cause a watchdog kill.
19127      */
maybeTriggerWatchdog()19128     void maybeTriggerWatchdog() {
19129         final String key = "debug.trigger.watchdog";
19130         if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) {
19131             Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!");
19132 
19133             // Clear the property; otherwise the system would hang again after a watchdog restart.
19134             SystemProperties.set(key, "");
19135             synchronized (ActivityManagerService.this) {
19136                 try {
19137                     // Arbitrary long sleep for watchdog to catch.
19138                     Thread.sleep(60 * 60 * 1000);
19139                 } catch (InterruptedException e) {
19140                 }
19141             }
19142         }
19143     }
19144 
isOnOffloadQueue(int flags)19145     private boolean isOnOffloadQueue(int flags) {
19146         return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
19147     }
19148 
19149     @Override
getLifeMonitor()19150     public ParcelFileDescriptor getLifeMonitor() {
19151         if (!isCallerShell()) {
19152             throw new SecurityException("Only shell can call it");
19153         }
19154         synchronized (this) {
19155             try {
19156                 if (mLifeMonitorFds == null) {
19157                     mLifeMonitorFds = ParcelFileDescriptor.createPipe();
19158                 }
19159                 // The returned FD will be closed, but we want to keep our reader open,
19160                 // so return a dup instead.
19161                 return mLifeMonitorFds[0].dup();
19162             } catch (IOException e) {
19163                 Slog.w(TAG, "Unable to create pipe", e);
19164                 return null;
19165             }
19166         }
19167     }
19168 }
19169