• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006-2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.am;
18 
19 import static android.Manifest.permission.CHANGE_CONFIGURATION;
20 import static android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
21 import static android.Manifest.permission.FILTER_EVENTS;
22 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
23 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
24 import static android.Manifest.permission.REMOVE_TASKS;
25 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
26 import static android.app.ActivityManager.INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS;
27 import static android.app.ActivityManager.INSTR_FLAG_MOUNT_EXTERNAL_STORAGE_FULL;
28 import static android.app.ActivityManager.PROCESS_STATE_LAST_ACTIVITY;
29 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
30 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
31 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
32 import static android.app.AppOpsManager.OP_NONE;
33 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
34 import static android.content.pm.ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
35 import static android.content.pm.PackageManager.GET_PROVIDERS;
36 import static android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES;
37 import static android.content.pm.PackageManager.MATCH_ALL;
38 import static android.content.pm.PackageManager.MATCH_ANY_USER;
39 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
40 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
41 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
42 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
43 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
44 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
45 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
46 import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
47 import static android.os.FactoryTest.FACTORY_TEST_OFF;
48 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
49 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_HIGH;
50 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
51 import static android.os.IServiceManager.DUMP_FLAG_PROTO;
52 import static android.os.Process.BLUETOOTH_UID;
53 import static android.os.Process.FIRST_APPLICATION_UID;
54 import static android.os.Process.NETWORK_STACK_UID;
55 import static android.os.Process.NFC_UID;
56 import static android.os.Process.PHONE_UID;
57 import static android.os.Process.PROC_CHAR;
58 import static android.os.Process.PROC_OUT_LONG;
59 import static android.os.Process.PROC_PARENS;
60 import static android.os.Process.PROC_SPACE_TERM;
61 import static android.os.Process.ROOT_UID;
62 import static android.os.Process.SCHED_FIFO;
63 import static android.os.Process.SCHED_RESET_ON_FORK;
64 import static android.os.Process.SE_UID;
65 import static android.os.Process.SHELL_UID;
66 import static android.os.Process.SIGNAL_USR1;
67 import static android.os.Process.SYSTEM_UID;
68 import static android.os.Process.THREAD_PRIORITY_FOREGROUND;
69 import static android.os.Process.ZYGOTE_PROCESS;
70 import static android.os.Process.getTotalMemory;
71 import static android.os.Process.isThreadInProcess;
72 import static android.os.Process.killProcess;
73 import static android.os.Process.killProcessQuiet;
74 import static android.os.Process.myPid;
75 import static android.os.Process.myUid;
76 import static android.os.Process.readProcFile;
77 import static android.os.Process.removeAllProcessGroups;
78 import static android.os.Process.sendSignal;
79 import static android.os.Process.setThreadPriority;
80 import static android.os.Process.setThreadScheduler;
81 import static android.provider.Settings.Global.ALWAYS_FINISH_ACTIVITIES;
82 import static android.provider.Settings.Global.DEBUG_APP;
83 import static android.provider.Settings.Global.NETWORK_ACCESS_TIMEOUT_MS;
84 import static android.provider.Settings.Global.WAIT_FOR_DEBUGGER;
85 import static android.text.format.DateUtils.DAY_IN_MILLIS;
86 
87 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ALL;
88 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
89 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
90 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKUP;
91 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST;
92 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_BACKGROUND;
93 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BROADCAST_LIGHT;
94 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
95 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_NETWORK;
96 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_OOM_ADJ;
97 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
98 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_POWER;
99 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
100 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESS_OBSERVERS;
101 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROVIDER;
102 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS;
103 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
104 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS;
105 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_WHITELISTS;
106 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BACKUP;
107 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_BROADCAST;
108 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
109 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_LRU;
110 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
111 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_NETWORK;
112 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_OOM_ADJ;
113 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_POWER;
114 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESSES;
115 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROCESS_OBSERVERS;
116 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PROVIDER;
117 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_PSS;
118 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
119 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
120 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
121 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
122 import static com.android.server.am.MemoryStatUtil.hasMemcg;
123 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
124 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
125 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
126 import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
127 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
128 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
129 import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
130 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
131 import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
132 import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
133 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD;
134 import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
135 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD;
136 import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
137 import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD;
138 import static com.android.server.wm.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
139 import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
140 import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString;
141 
142 import android.Manifest;
143 import android.Manifest.permission;
144 import android.annotation.NonNull;
145 import android.annotation.Nullable;
146 import android.annotation.UserIdInt;
147 import android.app.Activity;
148 import android.app.ActivityManager;
149 import android.app.ActivityManager.RunningTaskInfo;
150 import android.app.ActivityManager.StackInfo;
151 import android.app.ActivityManagerInternal;
152 import android.app.ActivityManagerProto;
153 import android.app.ActivityThread;
154 import android.app.AppGlobals;
155 import android.app.AppOpsManager;
156 import android.app.AppOpsManagerInternal.CheckOpsDelegate;
157 import android.app.ApplicationErrorReport;
158 import android.app.ApplicationThreadConstants;
159 import android.app.BroadcastOptions;
160 import android.app.ContentProviderHolder;
161 import android.app.Dialog;
162 import android.app.IActivityController;
163 import android.app.IActivityManager;
164 import android.app.IApplicationThread;
165 import android.app.IAssistDataReceiver;
166 import android.app.IInstrumentationWatcher;
167 import android.app.INotificationManager;
168 import android.app.IProcessObserver;
169 import android.app.IServiceConnection;
170 import android.app.IStopUserCallback;
171 import android.app.ITaskStackListener;
172 import android.app.IUiAutomationConnection;
173 import android.app.IUidObserver;
174 import android.app.IUserSwitchObserver;
175 import android.app.Instrumentation;
176 import android.app.Notification;
177 import android.app.NotificationManager;
178 import android.app.PendingIntent;
179 import android.app.ProcessMemoryState;
180 import android.app.ProfilerInfo;
181 import android.app.WaitResult;
182 import android.app.WindowConfiguration.ActivityType;
183 import android.app.WindowConfiguration.WindowingMode;
184 import android.app.backup.IBackupManager;
185 import android.app.usage.UsageEvents;
186 import android.app.usage.UsageEvents.Event;
187 import android.app.usage.UsageStatsManagerInternal;
188 import android.appwidget.AppWidgetManager;
189 import android.content.AutofillOptions;
190 import android.content.BroadcastReceiver;
191 import android.content.ComponentCallbacks2;
192 import android.content.ComponentName;
193 import android.content.ContentCaptureOptions;
194 import android.content.ContentProvider;
195 import android.content.ContentResolver;
196 import android.content.Context;
197 import android.content.IContentProvider;
198 import android.content.IIntentReceiver;
199 import android.content.IIntentSender;
200 import android.content.Intent;
201 import android.content.IntentFilter;
202 import android.content.pm.ActivityInfo;
203 import android.content.pm.ActivityPresentationInfo;
204 import android.content.pm.ApplicationInfo;
205 import android.content.pm.ApplicationInfo.HiddenApiEnforcementPolicy;
206 import android.content.pm.IPackageDataObserver;
207 import android.content.pm.IPackageManager;
208 import android.content.pm.InstrumentationInfo;
209 import android.content.pm.PackageInfo;
210 import android.content.pm.PackageManager;
211 import android.content.pm.PackageManager.NameNotFoundException;
212 import android.content.pm.PackageManagerInternal;
213 import android.content.pm.PackageManagerInternal.CheckPermissionDelegate;
214 import android.content.pm.PackageParser;
215 import android.content.pm.ParceledListSlice;
216 import android.content.pm.PathPermission;
217 import android.content.pm.PermissionInfo;
218 import android.content.pm.ProviderInfo;
219 import android.content.pm.ResolveInfo;
220 import android.content.pm.SELinuxUtil;
221 import android.content.pm.ServiceInfo;
222 import android.content.pm.UserInfo;
223 import android.content.res.CompatibilityInfo;
224 import android.content.res.Configuration;
225 import android.content.res.Resources;
226 import android.database.ContentObserver;
227 import android.graphics.Rect;
228 import android.hardware.display.DisplayManagerInternal;
229 import android.location.LocationManager;
230 import android.media.audiofx.AudioEffect;
231 import android.net.Proxy;
232 import android.net.Uri;
233 import android.os.AppZygote;
234 import android.os.BatteryStats;
235 import android.os.Binder;
236 import android.os.BinderProxy;
237 import android.os.Build;
238 import android.os.Bundle;
239 import android.os.Debug;
240 import android.os.DropBoxManager;
241 import android.os.FactoryTest;
242 import android.os.FileUtils;
243 import android.os.Handler;
244 import android.os.IBinder;
245 import android.os.IDeviceIdentifiersPolicyService;
246 import android.os.IPermissionController;
247 import android.os.IProcessInfoService;
248 import android.os.IProgressListener;
249 import android.os.Looper;
250 import android.os.Message;
251 import android.os.Parcel;
252 import android.os.ParcelFileDescriptor;
253 import android.os.PowerManager;
254 import android.os.PowerManager.ServiceType;
255 import android.os.PowerManagerInternal;
256 import android.os.Process;
257 import android.os.RemoteCallback;
258 import android.os.RemoteCallbackList;
259 import android.os.RemoteException;
260 import android.os.ResultReceiver;
261 import android.os.ServiceManager;
262 import android.os.ShellCallback;
263 import android.os.StrictMode;
264 import android.os.SystemClock;
265 import android.os.SystemProperties;
266 import android.os.Trace;
267 import android.os.TransactionTooLargeException;
268 import android.os.UserHandle;
269 import android.os.UserManager;
270 import android.os.WorkSource;
271 import android.os.storage.IStorageManager;
272 import android.os.storage.StorageManager;
273 import android.provider.DeviceConfig;
274 import android.provider.Settings;
275 import android.provider.DeviceConfig.Properties;
276 import android.server.ServerProtoEnums;
277 import android.sysprop.VoldProperties;
278 import android.text.TextUtils;
279 import android.text.format.DateUtils;
280 import android.text.style.SuggestionSpan;
281 import android.util.ArrayMap;
282 import android.util.ArraySet;
283 import android.util.DebugUtils;
284 import android.util.EventLog;
285 import android.util.Log;
286 import android.util.Pair;
287 import android.util.PrintWriterPrinter;
288 import android.util.Slog;
289 import android.util.SparseArray;
290 import android.util.SparseIntArray;
291 import android.util.StatsLog;
292 import android.util.TimeUtils;
293 import android.util.TimingsTraceLog;
294 import android.util.proto.ProtoOutputStream;
295 import android.util.proto.ProtoUtils;
296 import android.view.Display;
297 import android.view.Gravity;
298 import android.view.IRecentsAnimationRunner;
299 import android.view.LayoutInflater;
300 import android.view.View;
301 import android.view.WindowManager;
302 import android.view.autofill.AutofillManagerInternal;
303 
304 import com.android.internal.R;
305 import com.android.internal.annotations.GuardedBy;
306 import com.android.internal.annotations.VisibleForTesting;
307 import com.android.internal.app.DumpHeapActivity;
308 import com.android.internal.app.IAppOpsCallback;
309 import com.android.internal.app.IAppOpsService;
310 import com.android.internal.app.ProcessMap;
311 import com.android.internal.app.SystemUserHomeActivity;
312 import com.android.internal.app.procstats.ProcessStats;
313 import com.android.internal.content.PackageHelper;
314 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
315 import com.android.internal.notification.SystemNotificationChannels;
316 import com.android.internal.os.BackgroundThread;
317 import com.android.internal.os.BatteryStatsImpl;
318 import com.android.internal.os.BinderInternal;
319 import com.android.internal.os.ByteTransferPipe;
320 import com.android.internal.os.IResultReceiver;
321 import com.android.internal.os.ProcessCpuTracker;
322 import com.android.internal.os.TransferPipe;
323 import com.android.internal.os.Zygote;
324 import com.android.internal.telephony.TelephonyIntents;
325 import com.android.internal.util.ArrayUtils;
326 import com.android.internal.util.DumpUtils;
327 import com.android.internal.util.FastPrintWriter;
328 import com.android.internal.util.MemInfoReader;
329 import com.android.internal.util.Preconditions;
330 import com.android.internal.util.function.QuadFunction;
331 import com.android.internal.util.function.TriFunction;
332 import com.android.server.AlarmManagerInternal;
333 import com.android.server.AttributeCache;
334 import com.android.server.DeviceIdleController;
335 import com.android.server.DisplayThread;
336 import com.android.server.IntentResolver;
337 import com.android.server.IoThread;
338 import com.android.server.LocalServices;
339 import com.android.server.LockGuard;
340 import com.android.server.NetworkManagementInternal;
341 import com.android.server.PackageWatchdog;
342 import com.android.server.RescueParty;
343 import com.android.server.ServiceThread;
344 import com.android.server.SystemConfig;
345 import com.android.server.SystemService;
346 import com.android.server.SystemServiceManager;
347 import com.android.server.ThreadPriorityBooster;
348 import com.android.server.Watchdog;
349 import com.android.server.am.ActivityManagerServiceDumpProcessesProto.UidObserverRegistrationProto;
350 import com.android.server.appop.AppOpsService;
351 import com.android.server.contentcapture.ContentCaptureManagerInternal;
352 import com.android.server.firewall.IntentFirewall;
353 import com.android.server.job.JobSchedulerInternal;
354 import com.android.server.pm.Installer;
355 import com.android.server.pm.Installer.InstallerException;
356 import com.android.server.uri.GrantUri;
357 import com.android.server.uri.UriGrantsManagerInternal;
358 import com.android.server.utils.PriorityDump;
359 import com.android.server.vr.VrManagerInternal;
360 import com.android.server.wm.ActivityMetricsLaunchObserver;
361 import com.android.server.wm.ActivityServiceConnectionsHolder;
362 import com.android.server.wm.ActivityTaskManagerInternal;
363 import com.android.server.wm.ActivityTaskManagerService;
364 import com.android.server.wm.WindowManagerService;
365 import com.android.server.wm.WindowProcessController;
366 
367 import dalvik.system.VMRuntime;
368 
369 import libcore.util.EmptyArray;
370 
371 import java.io.File;
372 import java.io.FileDescriptor;
373 import java.io.FileNotFoundException;
374 import java.io.FileOutputStream;
375 import java.io.IOException;
376 import java.io.InputStreamReader;
377 import java.io.PrintWriter;
378 import java.io.StringWriter;
379 import java.io.UnsupportedEncodingException;
380 import java.text.SimpleDateFormat;
381 import java.util.ArrayList;
382 import java.util.Arrays;
383 import java.util.Collections;
384 import java.util.Comparator;
385 import java.util.Date;
386 import java.util.HashMap;
387 import java.util.HashSet;
388 import java.util.Iterator;
389 import java.util.List;
390 import java.util.Locale;
391 import java.util.Map;
392 import java.util.Objects;
393 import java.util.Set;
394 import java.util.concurrent.CountDownLatch;
395 import java.util.concurrent.Executor;
396 import java.util.concurrent.atomic.AtomicBoolean;
397 import java.util.concurrent.atomic.AtomicInteger;
398 import java.util.concurrent.atomic.AtomicLong;
399 import java.util.function.BiFunction;
400 
401 public class ActivityManagerService extends IActivityManager.Stub
402         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
403 
404     /**
405      * Priority we boost main thread and RT of top app to.
406      */
407     public static final int TOP_APP_PRIORITY_BOOST = -10;
408 
409     private static final String SYSTEM_PROPERTY_DEVICE_PROVISIONED =
410             "persist.sys.device_provisioned";
411 
412     static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM;
413     static final String TAG_BACKUP = TAG + POSTFIX_BACKUP;
414     private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST;
415     private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP;
416     private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
417     private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK;
418     static final String TAG_LRU = TAG + POSTFIX_LRU;
419     private static final String TAG_MU = TAG + POSTFIX_MU;
420     private static final String TAG_NETWORK = TAG + POSTFIX_NETWORK;
421     static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ;
422     private static final String TAG_POWER = TAG + POSTFIX_POWER;
423     static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS;
424     static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES;
425     private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER;
426     static final String TAG_PSS = TAG + POSTFIX_PSS;
427     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
428     private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
429     static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS;
430 
431     // Mock "pretend we're idle now" broadcast action to the job scheduler; declared
432     // here so that while the job scheduler can depend on AMS, the other way around
433     // need not be the case.
434     public static final String ACTION_TRIGGER_IDLE = "com.android.server.ACTION_TRIGGER_IDLE";
435 
436     /** Control over CPU and battery monitoring */
437     // write battery stats every 30 minutes.
438     static final long BATTERY_STATS_TIME = 30 * 60 * 1000;
439     static final boolean MONITOR_CPU_USAGE = true;
440     // don't sample cpu less than every 5 seconds.
441     static final long MONITOR_CPU_MIN_TIME = 5 * 1000;
442     // wait possibly forever for next cpu sample.
443     static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;
444     static final boolean MONITOR_THREAD_CPU_USAGE = false;
445 
446     // The flags that are set for all calls we make to the package manager.
447     public static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
448 
449     static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
450 
451     public static final String ANR_TRACE_DIR = "/data/anr";
452 
453     // Maximum number of receivers an app can register.
454     private static final int MAX_RECEIVERS_ALLOWED_PER_APP = 1000;
455 
456     // How long we wait for a launched process to attach to the activity manager
457     // before we decide it's never going to come up for real.
458     static final int PROC_START_TIMEOUT = 10*1000;
459     // How long we wait for an attached process to publish its content providers
460     // before we decide it must be hung.
461     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000;
462 
463     // How long we wait to kill an application zygote, after the last process using
464     // it has gone away.
465     static final int KILL_APP_ZYGOTE_DELAY_MS = 5 * 1000;
466     /**
467      * How long we wait for an provider to be published. Should be longer than
468      * {@link #CONTENT_PROVIDER_PUBLISH_TIMEOUT}.
469      */
470     static final int CONTENT_PROVIDER_WAIT_TIMEOUT = 20 * 1000;
471 
472     // How long we wait for a launched process to attach to the activity manager
473     // before we decide it's never going to come up for real, when the process was
474     // started with a wrapper for instrumentation (such as Valgrind) because it
475     // could take much longer than usual.
476     static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
477 
478     // How long we allow a receiver to run before giving up on it.
479     static final int BROADCAST_FG_TIMEOUT = 10*1000;
480     static final int BROADCAST_BG_TIMEOUT = 60*1000;
481 
482     public static final int MY_PID = myPid();
483 
484     static final String[] EMPTY_STRING_ARRAY = new String[0];
485 
486     // How many bytes to write into the dropbox log before truncating
487     static final int DROPBOX_MAX_SIZE = 192 * 1024;
488     // Assumes logcat entries average around 100 bytes; that's not perfect stack traces count
489     // as one line, but close enough for now.
490     static final int RESERVED_BYTES_PER_LOGCAT_LINE = 100;
491 
492     /** If a UID observer takes more than this long, send a WTF. */
493     private static final int SLOW_UID_OBSERVER_THRESHOLD_MS = 20;
494 
495     // Necessary ApplicationInfo flags to mark an app as persistent
496     static final int PERSISTENT_MASK =
497             ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT;
498 
499     // Intent sent when remote bugreport collection has been completed
500     private static final String INTENT_REMOTE_BUGREPORT_FINISHED =
501             "com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED";
502 
503     // If set, we will push process association information in to procstats.
504     static final boolean TRACK_PROCSTATS_ASSOCIATIONS = true;
505 
506     /**
507      * Default value for {@link Settings.Global#NETWORK_ACCESS_TIMEOUT_MS}.
508      */
509     private static final long NETWORK_ACCESS_TIMEOUT_DEFAULT_MS = 200; // 0.2 sec
510 
511     // The minimum memory growth threshold (in KB) for low RAM devices.
512     private static final int MINIMUM_MEMORY_GROWTH_THRESHOLD = 10 * 1000; // 10 MB
513 
514     /**
515      * The number of binder proxies we need to have before we start warning and
516      * dumping debug info.
517      */
518     private static final int BINDER_PROXY_HIGH_WATERMARK = 6000;
519 
520     /**
521      * Low watermark that needs to be met before we consider dumping info again,
522      * after already hitting the high watermark.
523      */
524     private static final int BINDER_PROXY_LOW_WATERMARK = 5500;
525 
526     /**
527      * State indicating that there is no need for any blocking for network.
528      */
529     @VisibleForTesting
530     static final int NETWORK_STATE_NO_CHANGE = 0;
531 
532     /**
533      * State indicating that the main thread needs to be informed about the network wait.
534      */
535     @VisibleForTesting
536     static final int NETWORK_STATE_BLOCK = 1;
537 
538     /**
539      * State indicating that any threads waiting for network state to get updated can be unblocked.
540      */
541     @VisibleForTesting
542     static final int NETWORK_STATE_UNBLOCK = 2;
543 
544     // Max character limit for a notification title. If the notification title is larger than this
545     // the notification will not be legible to the user.
546     private static final int MAX_BUGREPORT_TITLE_SIZE = 50;
547 
548     private static final int NATIVE_DUMP_TIMEOUT_MS = 2000; // 2 seconds;
549     private static final int JAVA_DUMP_MINIMUM_SIZE = 100; // 100 bytes.
550 
551     OomAdjuster mOomAdjuster;
552     final LowMemDetector mLowMemDetector;
553 
554     /** All system services */
555     SystemServiceManager mSystemServiceManager;
556 
557     private Installer mInstaller;
558 
559     final InstrumentationReporter mInstrumentationReporter = new InstrumentationReporter();
560 
561     final ArrayList<ActiveInstrumentation> mActiveInstrumentation = new ArrayList<>();
562 
563     public final IntentFirewall mIntentFirewall;
564 
565     public OomAdjProfiler mOomAdjProfiler = new OomAdjProfiler();
566 
567     // Whether we should use SCHED_FIFO for UI and RenderThreads.
568     boolean mUseFifoUiScheduling = false;
569 
570     // Use an offload queue for long broadcasts, e.g. BOOT_COMPLETED.
571     // For simplicity, since we statically declare the size of the array of BroadcastQueues,
572     // we still create this new offload queue, but never ever put anything on it.
573     boolean mEnableOffloadQueue;
574 
575     BroadcastQueue mFgBroadcastQueue;
576     BroadcastQueue mBgBroadcastQueue;
577     BroadcastQueue mOffloadBroadcastQueue;
578     // Convenient for easy iteration over the queues. Foreground is first
579     // so that dispatch of foreground broadcasts gets precedence.
580     final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[3];
581 
582     BroadcastStats mLastBroadcastStats;
583     BroadcastStats mCurBroadcastStats;
584 
broadcastQueueForIntent(Intent intent)585     BroadcastQueue broadcastQueueForIntent(Intent intent) {
586         if (isOnOffloadQueue(intent.getFlags())) {
587             if (DEBUG_BROADCAST_BACKGROUND) {
588                 Slog.i(TAG_BROADCAST,
589                         "Broadcast intent " + intent + " on offload queue");
590             }
591             return mOffloadBroadcastQueue;
592         }
593 
594         final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
595         if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST,
596                 "Broadcast intent " + intent + " on "
597                 + (isFg ? "foreground" : "background") + " queue");
598         return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
599     }
600 
601     /**
602      * The package name of the DeviceOwner. This package is not permitted to have its data cleared.
603      */
604     String mDeviceOwnerName;
605 
606     final UserController mUserController;
607     @VisibleForTesting
608     public final PendingIntentController mPendingIntentController;
609 
610     final AppErrors mAppErrors;
611     final PackageWatchdog mPackageWatchdog;
612 
613     /**
614      * Indicates the maximum time spent waiting for the network rules to get updated.
615      */
616     @VisibleForTesting
617     long mWaitForNetworkTimeoutMs;
618 
619     /** Total # of UID change events dispatched, shown in dumpsys. */
620     int mUidChangeDispatchCount;
621 
622     /**
623      * Helper class which strips out priority and proto arguments then calls the dump function with
624      * the appropriate arguments. If priority arguments are omitted, function calls the legacy
625      * dump command.
626      * If priority arguments are omitted all sections are dumped, otherwise sections are dumped
627      * according to their priority.
628      */
629     private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
630         @Override
631         public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
632                 boolean asProto) {
633             if (asProto) return;
634             doDump(fd, pw, new String[]{"activities"}, asProto);
635             doDump(fd, pw, new String[]{"service", "all-platform-critical"}, asProto);
636         }
637 
638         @Override
639         public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
640             doDump(fd, pw, new String[]{"-a", "--normal-priority"}, asProto);
641         }
642 
643         @Override
644         public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
645             doDump(fd, pw, args, asProto);
646         }
647     };
648 
649     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
650             THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_ACTIVITY);
651 
boostPriorityForLockedSection()652     static void boostPriorityForLockedSection() {
653         sThreadPriorityBooster.boost();
654     }
655 
resetPriorityAfterLockedSection()656     static void resetPriorityAfterLockedSection() {
657         sThreadPriorityBooster.reset();
658     }
659 
660     /**
661      * Process management.
662      */
663     final ProcessList mProcessList = new ProcessList();
664 
665     /**
666      * Tracking long-term execution of processes to look for abuse and other
667      * bad app behavior.
668      */
669     final ProcessStatsService mProcessStats;
670 
671     /**
672      * Non-persistent appId whitelist for background restrictions
673      */
674     int[] mBackgroundAppIdWhitelist = new int[] {
675             BLUETOOTH_UID
676     };
677 
678     /**
679      * Broadcast actions that will always be deliverable to unlaunched/background apps
680      */
681     ArraySet<String> mBackgroundLaunchBroadcasts;
682 
683     /**
684      * When an app has restrictions on the other apps that can have associations with it,
685      * it appears here with a set of the allowed apps and also track debuggability of the app.
686      */
687     ArrayMap<String, PackageAssociationInfo> mAllowedAssociations;
688 
689     /**
690      * Tracks association information for a particular package along with debuggability.
691      * <p> Associations for a package A are allowed to package B if B is part of the
692      *     allowed associations for A or if A is debuggable.
693      */
694     private final class PackageAssociationInfo {
695         private final String mSourcePackage;
696         private final ArraySet<String> mAllowedPackageAssociations;
697         private boolean mIsDebuggable;
698 
PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages, boolean isDebuggable)699         PackageAssociationInfo(String sourcePackage, ArraySet<String> allowedPackages,
700                 boolean isDebuggable) {
701             mSourcePackage = sourcePackage;
702             mAllowedPackageAssociations = allowedPackages;
703             mIsDebuggable = isDebuggable;
704         }
705 
706         /**
707          * Returns true if {@code mSourcePackage} is allowed association with
708          * {@code targetPackage}.
709          */
isPackageAssociationAllowed(String targetPackage)710         boolean isPackageAssociationAllowed(String targetPackage) {
711             return mIsDebuggable || mAllowedPackageAssociations.contains(targetPackage);
712         }
713 
isDebuggable()714         boolean isDebuggable() {
715             return mIsDebuggable;
716         }
717 
setDebuggable(boolean isDebuggable)718         void setDebuggable(boolean isDebuggable) {
719             mIsDebuggable = isDebuggable;
720         }
721 
getAllowedPackageAssociations()722         ArraySet<String> getAllowedPackageAssociations() {
723             return mAllowedPackageAssociations;
724         }
725     }
726 
727     /**
728      * All of the processes we currently have running organized by pid.
729      * The keys are the pid running the application.
730      *
731      * <p>NOTE: This object is protected by its own lock, NOT the global activity manager lock!
732      */
733     final PidMap mPidsSelfLocked = new PidMap();
734     final class PidMap {
735         private final SparseArray<ProcessRecord> mPidMap = new SparseArray<>();
736 
737         /**
738          * Puts the process record in the map.
739          * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
740          * method.
741          */
put(ProcessRecord app)742         void put(ProcessRecord app) {
743             synchronized (this) {
744                 mPidMap.put(app.pid, app);
745             }
746             mAtmInternal.onProcessMapped(app.pid, app.getWindowProcessController());
747         }
748 
749         /**
750          * Removes the process record from the map.
751          * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
752          * method.
753          */
remove(ProcessRecord app)754         void remove(ProcessRecord app) {
755             boolean removed = false;
756             synchronized (this) {
757                 final ProcessRecord existingApp = mPidMap.get(app.pid);
758                 if (existingApp != null && existingApp.startSeq == app.startSeq) {
759                     mPidMap.remove(app.pid);
760                     removed = true;
761                 }
762             }
763             if (removed) {
764                 mAtmInternal.onProcessUnMapped(app.pid);
765             }
766         }
767 
768         /**
769          * Removes the process record from the map if it has a thread.
770          * <p>NOTE: Callers should avoid acquiring the mPidsSelfLocked lock before calling this
771          * method.
772          */
removeIfNoThread(ProcessRecord app)773         boolean removeIfNoThread(ProcessRecord app) {
774             boolean removed = false;
775             synchronized (this) {
776                 final ProcessRecord existingApp = get(app.pid);
777                 if (existingApp != null && existingApp.startSeq == app.startSeq
778                         && app.thread == null) {
779                     mPidMap.remove(app.pid);
780                     removed = true;
781                 }
782             }
783             if (removed) {
784                 mAtmInternal.onProcessUnMapped(app.pid);
785             }
786             return removed;
787         }
788 
get(int pid)789         ProcessRecord get(int pid) {
790             return mPidMap.get(pid);
791         }
792 
size()793         int size() {
794             return mPidMap.size();
795         }
796 
valueAt(int index)797         ProcessRecord valueAt(int index) {
798             return mPidMap.valueAt(index);
799         }
800 
keyAt(int index)801         int keyAt(int index) {
802             return mPidMap.keyAt(index);
803         }
804 
indexOfKey(int key)805         int indexOfKey(int key) {
806             return mPidMap.indexOfKey(key);
807         }
808     }
809 
810     /**
811      * All of the processes that have been forced to be important.  The key
812      * is the pid of the caller who requested it (we hold a death
813      * link on it).
814      */
815     abstract class ImportanceToken implements IBinder.DeathRecipient {
816         final int pid;
817         final IBinder token;
818         final String reason;
819 
ImportanceToken(int _pid, IBinder _token, String _reason)820         ImportanceToken(int _pid, IBinder _token, String _reason) {
821             pid = _pid;
822             token = _token;
823             reason = _reason;
824         }
825 
826         @Override
toString()827         public String toString() {
828             return "ImportanceToken { " + Integer.toHexString(System.identityHashCode(this))
829                     + " " + reason + " " + pid + " " + token + " }";
830         }
831 
writeToProto(ProtoOutputStream proto, long fieldId)832         void writeToProto(ProtoOutputStream proto, long fieldId) {
833             final long pToken = proto.start(fieldId);
834             proto.write(ImportanceTokenProto.PID, pid);
835             if (token != null) {
836                 proto.write(ImportanceTokenProto.TOKEN, token.toString());
837             }
838             proto.write(ImportanceTokenProto.REASON, reason);
839             proto.end(pToken);
840         }
841     }
842     final SparseArray<ImportanceToken> mImportantProcesses = new SparseArray<ImportanceToken>();
843 
844     /**
845      * List of records for processes that someone had tried to start before the
846      * system was ready.  We don't start them at that point, but ensure they
847      * are started by the time booting is complete.
848      */
849     final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
850 
851     /**
852      * List of persistent applications that are in the process
853      * of being started.
854      */
855     final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
856 
857     /**
858      * List of processes that should gc as soon as things are idle.
859      */
860     final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
861 
862     /**
863      * Processes we want to collect PSS data from.
864      */
865     final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
866 
867     /**
868      * Depth of overlapping activity-start PSS deferral notes
869      */
870     private final AtomicInteger mActivityStartingNesting = new AtomicInteger(0);
871 
872     private final ActivityMetricsLaunchObserver mActivityLaunchObserver =
873             new ActivityMetricsLaunchObserver() {
874         @Override
875         public void onActivityLaunched(byte[] activity, int temperature) {
876             // This is safe to force to the head of the queue because it relies only
877             // on refcounting to track begin/end of deferrals, not on actual
878             // message ordering.  We don't care *what* activity is being
879             // launched; only that we're doing so.
880             if (mPssDeferralTime > 0) {
881                 final Message msg = mBgHandler.obtainMessage(DEFER_PSS_MSG);
882                 mBgHandler.sendMessageAtFrontOfQueue(msg);
883             }
884         }
885 
886         // The other observer methods are unused
887         @Override
888         public void onIntentStarted(Intent intent) {
889         }
890 
891         @Override
892         public void onIntentFailed() {
893         }
894 
895         @Override
896         public void onActivityLaunchCancelled(byte[] abortingActivity) {
897         }
898 
899         @Override
900         public void onActivityLaunchFinished(byte[] finalActivity) {
901         }
902     };
903 
904     /**
905      * How long we defer PSS gathering while activities are starting, in milliseconds.
906      * This is adjustable via DeviceConfig.  If it is zero or negative, no PSS deferral
907      * is done.
908      */
909     private volatile long mPssDeferralTime = 0;
910     private static final String ACTIVITY_START_PSS_DEFER_CONFIG = "activity_start_pss_defer";
911 
912     private boolean mBinderTransactionTrackingEnabled = false;
913 
914     /**
915      * Last time we requested PSS data of all processes.
916      */
917     long mLastFullPssTime = SystemClock.uptimeMillis();
918 
919     /**
920      * If set, the next time we collect PSS data we should do a full collection
921      * with data from native processes and the kernel.
922      */
923     boolean mFullPssPending = false;
924 
925     /**
926      * Observe DeviceConfig changes to the PSS calculation interval
927      */
928     private final DeviceConfig.OnPropertiesChangedListener mPssDelayConfigListener =
929             new DeviceConfig.OnPropertiesChangedListener() {
930                 @Override
931                 public void onPropertiesChanged(Properties properties) {
932                     mPssDeferralTime = properties.getLong(ACTIVITY_START_PSS_DEFER_CONFIG, 0);
933                     if (DEBUG_PSS) {
934                         Slog.d(TAG_PSS, "Activity-start PSS delay now "
935                                 + mPssDeferralTime + " ms");
936                     }
937                 }
938             };
939 
940     /**
941      * This is for verifying the UID report flow.
942      */
943     static final boolean VALIDATE_UID_STATES = true;
944     final ActiveUids mValidateUids = new ActiveUids(this, false /* postChangesToAtm */);
945 
946     /**
947      * Fingerprints (hashCode()) of stack traces that we've
948      * already logged DropBox entries for.  Guarded by itself.  If
949      * something (rogue user app) forces this over
950      * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
951      */
952     private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
953     private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
954 
955     /**
956      * Keeps track of all IIntentReceivers that have been registered for broadcasts.
957      * Hash keys are the receiver IBinder, hash value is a ReceiverList.
958      */
959     final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>();
960 
961     /**
962      * Resolver for broadcast intents to registered receivers.
963      * Holds BroadcastFilter (subclass of IntentFilter).
964      */
965     final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
966             = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
967         @Override
968         protected boolean allowFilterResult(
969                 BroadcastFilter filter, List<BroadcastFilter> dest) {
970             IBinder target = filter.receiverList.receiver.asBinder();
971             for (int i = dest.size() - 1; i >= 0; i--) {
972                 if (dest.get(i).receiverList.receiver.asBinder() == target) {
973                     return false;
974                 }
975             }
976             return true;
977         }
978 
979         @Override
980         protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
981             if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
982                     || userId == filter.owningUserId) {
983                 return super.newResult(filter, match, userId);
984             }
985             return null;
986         }
987 
988         @Override
989         protected BroadcastFilter[] newArray(int size) {
990             return new BroadcastFilter[size];
991         }
992 
993         @Override
994         protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
995             return packageName.equals(filter.packageName);
996         }
997     };
998 
999     /**
1000      * State of all active sticky broadcasts per user.  Keys are the action of the
1001      * sticky Intent, values are an ArrayList of all broadcasted intents with
1002      * that action (which should usually be one).  The SparseArray is keyed
1003      * by the user ID the sticky is for, and can include UserHandle.USER_ALL
1004      * for stickies that are sent to all users.
1005      */
1006     final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
1007             new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
1008 
1009     final ActiveServices mServices;
1010 
1011     final static class Association {
1012         final int mSourceUid;
1013         final String mSourceProcess;
1014         final int mTargetUid;
1015         final ComponentName mTargetComponent;
1016         final String mTargetProcess;
1017 
1018         int mCount;
1019         long mTime;
1020 
1021         int mNesting;
1022         long mStartTime;
1023 
1024         // states of the source process when the bind occurred.
1025         int mLastState = ActivityManager.MAX_PROCESS_STATE + 1;
1026         long mLastStateUptime;
1027         long[] mStateTimes = new long[ActivityManager.MAX_PROCESS_STATE
1028                 - ActivityManager.MIN_PROCESS_STATE+1];
1029 
Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)1030         Association(int sourceUid, String sourceProcess, int targetUid,
1031                 ComponentName targetComponent, String targetProcess) {
1032             mSourceUid = sourceUid;
1033             mSourceProcess = sourceProcess;
1034             mTargetUid = targetUid;
1035             mTargetComponent = targetComponent;
1036             mTargetProcess = targetProcess;
1037         }
1038     }
1039 
1040     /**
1041      * When service association tracking is enabled, this is all of the associations we
1042      * have seen.  Mapping is target uid -> target component -> source uid -> source process name
1043      * -> association data.
1044      */
1045     final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>>
1046             mAssociations = new SparseArray<>();
1047     boolean mTrackingAssociations;
1048 
1049     /**
1050      * Backup/restore process management
1051      */
1052     @GuardedBy("this")
1053     final SparseArray<BackupRecord> mBackupTargets = new SparseArray<>();
1054 
1055     final ProviderMap mProviderMap;
1056 
1057     /**
1058      * List of content providers who have clients waiting for them.  The
1059      * application is currently being launched and the provider will be
1060      * removed from this list once it is published.
1061      */
1062     final ArrayList<ContentProviderRecord> mLaunchingProviders = new ArrayList<>();
1063 
1064     boolean mSystemProvidersInstalled;
1065 
1066     CoreSettingsObserver mCoreSettingsObserver;
1067 
1068     DevelopmentSettingsObserver mDevelopmentSettingsObserver;
1069 
1070     private final class DevelopmentSettingsObserver extends ContentObserver {
1071         private final Uri mUri = Settings.Global
1072                 .getUriFor(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
1073 
1074         private final ComponentName mBugreportStorageProvider = new ComponentName(
1075                 "com.android.shell", "com.android.shell.BugreportStorageProvider");
1076 
DevelopmentSettingsObserver()1077         public DevelopmentSettingsObserver() {
1078             super(mHandler);
1079             mContext.getContentResolver().registerContentObserver(mUri, false, this,
1080                     UserHandle.USER_ALL);
1081             // Always kick once to ensure that we match current state
1082             onChange();
1083         }
1084 
1085         @Override
onChange(boolean selfChange, Uri uri, @UserIdInt int userId)1086         public void onChange(boolean selfChange, Uri uri, @UserIdInt int userId) {
1087             if (mUri.equals(uri)) {
1088                 onChange();
1089             }
1090         }
1091 
onChange()1092         public void onChange() {
1093             final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(),
1094                     Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, Build.IS_ENG ? 1 : 0) != 0;
1095             mContext.getPackageManager().setComponentEnabledSetting(mBugreportStorageProvider,
1096                     enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1097                             : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
1098                     0);
1099         }
1100     }
1101 
1102     /**
1103      * Thread-local storage used to carry caller permissions over through
1104      * indirect content-provider access.
1105      */
1106     private class Identity {
1107         public final IBinder token;
1108         public final int pid;
1109         public final int uid;
1110 
Identity(IBinder _token, int _pid, int _uid)1111         Identity(IBinder _token, int _pid, int _uid) {
1112             token = _token;
1113             pid = _pid;
1114             uid = _uid;
1115         }
1116     }
1117 
1118     private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
1119 
1120     /**
1121      * All information we have collected about the runtime performance of
1122      * any user id that can impact battery performance.
1123      */
1124     final BatteryStatsService mBatteryStatsService;
1125 
1126     /**
1127      * Information about component usage
1128      */
1129     UsageStatsManagerInternal mUsageStatsService;
1130 
1131     /**
1132      * Access to DeviceIdleController service.
1133      */
1134     DeviceIdleController.LocalService mLocalDeviceIdleController;
1135 
1136     /**
1137      * Power-save whitelisted app-ids (not including except-idle-whitelisted ones).
1138      */
1139     int[] mDeviceIdleWhitelist = new int[0];
1140 
1141     /**
1142      * Power-save whitelisted app-ids (including except-idle-whitelisted ones).
1143      */
1144     int[] mDeviceIdleExceptIdleWhitelist = new int[0];
1145 
1146     /**
1147      * Set of app ids that are temporarily allowed to escape bg check due to high-pri message
1148      */
1149     int[] mDeviceIdleTempWhitelist = new int[0];
1150 
1151     static final class PendingTempWhitelist {
1152         final int targetUid;
1153         final long duration;
1154         final String tag;
1155 
PendingTempWhitelist(int _targetUid, long _duration, String _tag)1156         PendingTempWhitelist(int _targetUid, long _duration, String _tag) {
1157             targetUid = _targetUid;
1158             duration = _duration;
1159             tag = _tag;
1160         }
1161 
writeToProto(ProtoOutputStream proto, long fieldId)1162         void writeToProto(ProtoOutputStream proto, long fieldId) {
1163             final long token = proto.start(fieldId);
1164             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TARGET_UID, targetUid);
1165             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.DURATION_MS, duration);
1166             proto.write(ActivityManagerServiceDumpProcessesProto.PendingTempWhitelist.TAG, tag);
1167             proto.end(token);
1168         }
1169     }
1170 
1171     final PendingTempWhitelists mPendingTempWhitelist = new PendingTempWhitelists(this);
1172 
1173     /**
1174      * Information about and control over application operations
1175      */
1176     final AppOpsService mAppOpsService;
1177 
1178     /**
1179      * List of initialization arguments to pass to all processes when binding applications to them.
1180      * For example, references to the commonly used services.
1181      */
1182     ArrayMap<String, IBinder> mAppBindArgs;
1183     ArrayMap<String, IBinder> mIsolatedAppBindArgs;
1184 
1185     /**
1186      * Temporary to avoid allocations.  Protected by main lock.
1187      */
1188     final StringBuilder mStringBuilder = new StringBuilder(256);
1189 
1190     volatile boolean mProcessesReady = false;
1191     volatile boolean mSystemReady = false;
1192     volatile boolean mOnBattery = false;
1193     final int mFactoryTest;
1194     volatile boolean mBooting = false;
1195 
1196     @GuardedBy("this") boolean mCallFinishBooting = false;
1197     @GuardedBy("this") boolean mBootAnimationComplete = false;
1198 
1199     final Context mContext;
1200 
1201     /**
1202      * This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
1203      * change at runtime. Use mContext for non-UI purposes.
1204      */
1205     final Context mUiContext;
1206 
1207     /**
1208      * Last time (in uptime) at which we checked for power usage.
1209      */
1210     long mLastPowerCheckUptime;
1211 
1212     /**
1213      * For some direct access we need to power manager.
1214      */
1215     PowerManagerInternal mLocalPowerManager;
1216 
1217     /**
1218      * State of external calls telling us if the device is awake or asleep.
1219      */
1220     int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE;
1221 
1222     /**
1223      * Allow the current computed overall memory level of the system to go down?
1224      * This is set to false when we are killing processes for reasons other than
1225      * memory management, so that the now smaller process list will not be taken as
1226      * an indication that memory is tighter.
1227      */
1228     boolean mAllowLowerMemLevel = false;
1229 
1230     /**
1231      * The last computed memory level, for holding when we are in a state that
1232      * processes are going away for other reasons.
1233      */
1234     int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
1235 
1236     /**
1237      * The last total number of process we have, to determine if changes actually look
1238      * like a shrinking number of process due to lower RAM.
1239      */
1240     int mLastNumProcesses;
1241 
1242     /**
1243      * The uptime of the last time we performed idle maintenance.
1244      */
1245     long mLastIdleTime = SystemClock.uptimeMillis();
1246 
1247     /**
1248      * Total time spent with RAM that has been added in the past since the last idle time.
1249      */
1250     long mLowRamTimeSinceLastIdle = 0;
1251 
1252     /**
1253      * If RAM is currently low, when that horrible situation started.
1254      */
1255     long mLowRamStartTime = 0;
1256 
1257     /**
1258      * For reporting to battery stats the current top application.
1259      */
1260     private String mCurResumedPackage = null;
1261     private int mCurResumedUid = -1;
1262 
1263     /**
1264      * For reporting to battery stats the apps currently running foreground
1265      * service.  The ProcessMap is package/uid tuples; each of these contain
1266      * an array of the currently foreground processes.
1267      */
1268     final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1269             = new ProcessMap<ArrayList<ProcessRecord>>();
1270 
1271     /**
1272      * Set if the systemServer made a call to enterSafeMode.
1273      */
1274     boolean mSafeMode;
1275 
1276     /**
1277      * If true, we are running under a test environment so will sample PSS from processes
1278      * much more rapidly to try to collect better data when the tests are rapidly
1279      * running through apps.
1280      */
1281     boolean mTestPssMode = false;
1282 
1283     String mDebugApp = null;
1284     boolean mWaitForDebugger = false;
1285     boolean mDebugTransient = false;
1286     String mOrigDebugApp = null;
1287     boolean mOrigWaitForDebugger = false;
1288     boolean mAlwaysFinishActivities = false;
1289 
1290     class ProfileData {
1291         private String mProfileApp = null;
1292         private ProcessRecord mProfileProc = null;
1293         private ProfilerInfo mProfilerInfo = null;
1294 
setProfileApp(String profileApp)1295         void setProfileApp(String profileApp) {
1296             mProfileApp = profileApp;
1297             if (mAtmInternal != null) {
1298                 mAtmInternal.setProfileApp(profileApp);
1299             }
1300         }
1301 
getProfileApp()1302         String getProfileApp() {
1303             return mProfileApp;
1304         }
1305 
setProfileProc(ProcessRecord profileProc)1306         void setProfileProc(ProcessRecord profileProc) {
1307             mProfileProc = profileProc;
1308             if (mAtmInternal != null) {
1309                 mAtmInternal.setProfileProc(profileProc == null ? null
1310                         : profileProc.getWindowProcessController());
1311             }
1312         }
1313 
getProfileProc()1314         ProcessRecord getProfileProc() {
1315             return mProfileProc;
1316         }
1317 
setProfilerInfo(ProfilerInfo profilerInfo)1318         void setProfilerInfo(ProfilerInfo profilerInfo) {
1319             mProfilerInfo = profilerInfo;
1320             if (mAtmInternal != null) {
1321                 mAtmInternal.setProfilerInfo(profilerInfo);
1322             }
1323         }
1324 
getProfilerInfo()1325         ProfilerInfo getProfilerInfo() {
1326             return mProfilerInfo;
1327         }
1328     }
1329     final ProfileData mProfileData = new ProfileData();
1330 
1331     /**
1332      * Stores a map of process name -> agent string. When a process is started and mAgentAppMap
1333      * is not null, this map is checked and the mapped agent installed during bind-time. Note:
1334      * A non-null agent in mProfileInfo overrides this.
1335      */
1336     private @Nullable Map<String, String> mAppAgentMap = null;
1337 
1338     int mProfileType = 0;
1339     final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>();
1340     String mMemWatchDumpProcName;
1341     String mMemWatchDumpFile;
1342     int mMemWatchDumpPid;
1343     int mMemWatchDumpUid;
1344     private boolean mMemWatchIsUserInitiated;
1345     String mTrackAllocationApp = null;
1346     String mNativeDebuggingApp = null;
1347 
1348     private final Injector mInjector;
1349 
1350     static final class ProcessChangeItem {
1351         static final int CHANGE_ACTIVITIES = 1<<0;
1352         static final int CHANGE_FOREGROUND_SERVICES = 1<<1;
1353         int changes;
1354         int uid;
1355         int pid;
1356         int processState;
1357         boolean foregroundActivities;
1358         int foregroundServiceTypes;
1359     }
1360 
1361     static final class UidObserverRegistration {
1362         final int uid;
1363         final String pkg;
1364         final int which;
1365         final int cutpoint;
1366 
1367         /**
1368          * Total # of callback calls that took more than {@link #SLOW_UID_OBSERVER_THRESHOLD_MS}.
1369          * We show it in dumpsys.
1370          */
1371         int mSlowDispatchCount;
1372 
1373         /** Max time it took for each dispatch. */
1374         int mMaxDispatchTime;
1375 
1376         final SparseIntArray lastProcStates;
1377 
1378         // Please keep the enum lists in sync
1379         private static int[] ORIG_ENUMS = new int[]{
1380                 ActivityManager.UID_OBSERVER_IDLE,
1381                 ActivityManager.UID_OBSERVER_ACTIVE,
1382                 ActivityManager.UID_OBSERVER_GONE,
1383                 ActivityManager.UID_OBSERVER_PROCSTATE,
1384         };
1385         private static int[] PROTO_ENUMS = new int[]{
1386                 ActivityManagerProto.UID_OBSERVER_FLAG_IDLE,
1387                 ActivityManagerProto.UID_OBSERVER_FLAG_ACTIVE,
1388                 ActivityManagerProto.UID_OBSERVER_FLAG_GONE,
1389                 ActivityManagerProto.UID_OBSERVER_FLAG_PROCSTATE,
1390         };
1391 
UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint)1392         UidObserverRegistration(int _uid, String _pkg, int _which, int _cutpoint) {
1393             uid = _uid;
1394             pkg = _pkg;
1395             which = _which;
1396             cutpoint = _cutpoint;
1397             if (cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
1398                 lastProcStates = new SparseIntArray();
1399             } else {
1400                 lastProcStates = null;
1401             }
1402         }
1403 
writeToProto(ProtoOutputStream proto, long fieldId)1404         void writeToProto(ProtoOutputStream proto, long fieldId) {
1405             final long token = proto.start(fieldId);
1406             proto.write(UidObserverRegistrationProto.UID, uid);
1407             proto.write(UidObserverRegistrationProto.PACKAGE, pkg);
1408             ProtoUtils.writeBitWiseFlagsToProtoEnum(proto, UidObserverRegistrationProto.FLAGS,
1409                     which, ORIG_ENUMS, PROTO_ENUMS);
1410             proto.write(UidObserverRegistrationProto.CUT_POINT, cutpoint);
1411             if (lastProcStates != null) {
1412                 final int NI = lastProcStates.size();
1413                 for (int i=0; i<NI; i++) {
1414                     final long pToken = proto.start(UidObserverRegistrationProto.LAST_PROC_STATES);
1415                     proto.write(UidObserverRegistrationProto.ProcState.UID, lastProcStates.keyAt(i));
1416                     proto.write(UidObserverRegistrationProto.ProcState.STATE, lastProcStates.valueAt(i));
1417                     proto.end(pToken);
1418                 }
1419             }
1420             proto.end(token);
1421         }
1422     }
1423 
1424     // TODO: Move below 4 members and code to ProcessList
1425     final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>();
1426     ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
1427 
1428     final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>();
1429     final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>();
1430 
1431     final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>();
1432     UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5];
1433 
1434     final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>();
1435     final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>();
1436 
1437     OomAdjObserver mCurOomAdjObserver;
1438     int mCurOomAdjUid;
1439 
1440     interface OomAdjObserver {
onOomAdjMessage(String msg)1441         void onOomAdjMessage(String msg);
1442     }
1443 
1444     /**
1445      * Runtime CPU use collection thread.  This object's lock is used to
1446      * perform synchronization with the thread (notifying it to run).
1447      */
1448     final Thread mProcessCpuThread;
1449 
1450     /**
1451      * Used to collect per-process CPU use for ANRs, battery stats, etc.
1452      * Must acquire this object's lock when accessing it.
1453      * NOTE: this lock will be held while doing long operations (trawling
1454      * through all processes in /proc), so it should never be acquired by
1455      * any critical paths such as when holding the main activity manager lock.
1456      */
1457     final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1458             MONITOR_THREAD_CPU_USAGE);
1459     final AtomicLong mLastCpuTime = new AtomicLong(0);
1460     final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1461     final CountDownLatch mProcessCpuInitLatch = new CountDownLatch(1);
1462 
1463     long mLastWriteTime = 0;
1464 
1465     /** Set to true after the system has finished booting. */
1466     volatile boolean mBooted = false;
1467 
1468     /**
1469      * Current boot phase.
1470      */
1471     int mBootPhase;
1472 
1473     @VisibleForTesting
1474     public WindowManagerService mWindowManager;
1475     @VisibleForTesting
1476     public ActivityTaskManagerService mActivityTaskManager;
1477     @VisibleForTesting
1478     public ActivityTaskManagerInternal mAtmInternal;
1479     @VisibleForTesting
1480     public UriGrantsManagerInternal mUgmInternal;
1481     final ActivityThread mSystemThread;
1482 
1483     private final class AppDeathRecipient implements IBinder.DeathRecipient {
1484         final ProcessRecord mApp;
1485         final int mPid;
1486         final IApplicationThread mAppThread;
1487 
AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1488         AppDeathRecipient(ProcessRecord app, int pid,
1489                 IApplicationThread thread) {
1490             if (DEBUG_ALL) Slog.v(
1491                 TAG, "New death recipient " + this
1492                  + " for thread " + thread.asBinder());
1493             mApp = app;
1494             mPid = pid;
1495             mAppThread = thread;
1496         }
1497 
1498         @Override
binderDied()1499         public void binderDied() {
1500             if (DEBUG_ALL) Slog.v(
1501                 TAG, "Death received in " + this
1502                 + " for thread " + mAppThread.asBinder());
1503             synchronized(ActivityManagerService.this) {
1504                 appDiedLocked(mApp, mPid, mAppThread, true);
1505             }
1506         }
1507     }
1508 
1509     static final int SHOW_ERROR_UI_MSG = 1;
1510     static final int SHOW_NOT_RESPONDING_UI_MSG = 2;
1511     static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1512     static final int WAIT_FOR_DEBUGGER_UI_MSG = 6;
1513     static final int SERVICE_TIMEOUT_MSG = 12;
1514     static final int UPDATE_TIME_ZONE = 13;
1515     static final int PROC_START_TIMEOUT_MSG = 20;
1516     static final int KILL_APPLICATION_MSG = 22;
1517     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
1518     static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
1519     static final int CLEAR_DNS_CACHE_MSG = 28;
1520     static final int UPDATE_HTTP_PROXY_MSG = 29;
1521     static final int DISPATCH_PROCESSES_CHANGED_UI_MSG = 31;
1522     static final int DISPATCH_PROCESS_DIED_UI_MSG = 32;
1523     static final int REPORT_MEM_USAGE_MSG = 33;
1524     static final int UPDATE_TIME_PREFERENCE_MSG = 41;
1525     static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 49;
1526     static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 50;
1527     static final int DELETE_DUMPHEAP_MSG = 51;
1528     static final int DISPATCH_UIDS_CHANGED_UI_MSG = 53;
1529     static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 56;
1530     static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 57;
1531     static final int IDLE_UIDS_MSG = 58;
1532     static final int HANDLE_TRUST_STORAGE_UPDATE_MSG = 63;
1533     static final int SERVICE_FOREGROUND_TIMEOUT_MSG = 66;
1534     static final int PUSH_TEMP_WHITELIST_UI_MSG = 68;
1535     static final int SERVICE_FOREGROUND_CRASH_MSG = 69;
1536     static final int DISPATCH_OOM_ADJ_OBSERVER_MSG = 70;
1537     static final int KILL_APP_ZYGOTE_MSG = 71;
1538 
1539     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1540 
1541     static final String SERVICE_RECORD_KEY = "servicerecord";
1542 
1543     long mLastMemUsageReportTime = 0;
1544 
1545     /**
1546      * Flag whether the current user is a "monkey", i.e. whether
1547      * the UI is driven by a UI automation tool.
1548      */
1549     private boolean mUserIsMonkey;
1550 
1551     @VisibleForTesting
1552     public final ServiceThread mHandlerThread;
1553     final MainHandler mHandler;
1554     final Handler mUiHandler;
1555     final ServiceThread mProcStartHandlerThread;
1556     final Handler mProcStartHandler;
1557 
1558     ActivityManagerConstants mConstants;
1559 
1560     // Encapsulates the global setting "hidden_api_blacklist_exemptions"
1561     final HiddenApiSettings mHiddenApiBlacklist;
1562 
1563     PackageManagerInternal mPackageManagerInt;
1564 
1565     /**
1566      * Whether to force background check on all apps (for battery saver) or not.
1567      */
1568     boolean mForceBackgroundCheck;
1569 
1570     private static String sTheRealBuildSerial = Build.UNKNOWN;
1571 
1572     private ParcelFileDescriptor[] mLifeMonitorFds;
1573 
1574     static final HostingRecord sNullHostingRecord = new HostingRecord(null);
1575     /**
1576      * Used to notify activity lifecycle events.
1577      */
1578     @Nullable ContentCaptureManagerInternal mContentCaptureService;
1579 
1580     final class UiHandler extends Handler {
UiHandler()1581         public UiHandler() {
1582             super(com.android.server.UiThread.get().getLooper(), null, true);
1583         }
1584 
1585         @Override
handleMessage(Message msg)1586         public void handleMessage(Message msg) {
1587             switch (msg.what) {
1588             case SHOW_ERROR_UI_MSG: {
1589                 mAppErrors.handleShowAppErrorUi(msg);
1590                 ensureBootCompleted();
1591             } break;
1592             case SHOW_NOT_RESPONDING_UI_MSG: {
1593                 mAppErrors.handleShowAnrUi(msg);
1594                 ensureBootCompleted();
1595             } break;
1596             case SHOW_STRICT_MODE_VIOLATION_UI_MSG: {
1597                 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1598                 synchronized (ActivityManagerService.this) {
1599                     ProcessRecord proc = (ProcessRecord) data.get("app");
1600                     if (proc == null) {
1601                         Slog.e(TAG, "App not found when showing strict mode dialog.");
1602                         break;
1603                     }
1604                     if (proc.crashDialog != null) {
1605                         Slog.e(TAG, "App already has strict mode dialog: " + proc);
1606                         return;
1607                     }
1608                     AppErrorResult res = (AppErrorResult) data.get("result");
1609                     if (mAtmInternal.showStrictModeViolationDialog()) {
1610                         Dialog d = new StrictModeViolationDialog(mUiContext,
1611                                 ActivityManagerService.this, res, proc);
1612                         d.show();
1613                         proc.crashDialog = d;
1614                     } else {
1615                         // The device is asleep, so just pretend that the user
1616                         // saw a crash dialog and hit "force quit".
1617                         res.set(0);
1618                     }
1619                 }
1620                 ensureBootCompleted();
1621             } break;
1622             case WAIT_FOR_DEBUGGER_UI_MSG: {
1623                 synchronized (ActivityManagerService.this) {
1624                     ProcessRecord app = (ProcessRecord)msg.obj;
1625                     if (msg.arg1 != 0) {
1626                         if (!app.waitedForDebugger) {
1627                             Dialog d = new AppWaitingForDebuggerDialog(
1628                                     ActivityManagerService.this,
1629                                     mUiContext, app);
1630                             app.waitDialog = d;
1631                             app.waitedForDebugger = true;
1632                             d.show();
1633                         }
1634                     } else {
1635                         if (app.waitDialog != null) {
1636                             app.waitDialog.dismiss();
1637                             app.waitDialog = null;
1638                         }
1639                     }
1640                 }
1641             } break;
1642             case DISPATCH_PROCESSES_CHANGED_UI_MSG: {
1643                 dispatchProcessesChanged();
1644                 break;
1645             }
1646             case DISPATCH_PROCESS_DIED_UI_MSG: {
1647                 final int pid = msg.arg1;
1648                 final int uid = msg.arg2;
1649                 dispatchProcessDied(pid, uid);
1650                 break;
1651             }
1652             case DISPATCH_UIDS_CHANGED_UI_MSG: {
1653                 if (false) { // DO NOT SUBMIT WITH TRUE
1654                     maybeTriggerWatchdog();
1655                 }
1656                 dispatchUidsChanged();
1657             } break;
1658             case DISPATCH_OOM_ADJ_OBSERVER_MSG: {
1659                 dispatchOomAdjObserver((String)msg.obj);
1660             } break;
1661             case PUSH_TEMP_WHITELIST_UI_MSG: {
1662                 pushTempWhitelist();
1663             } break;
1664             }
1665         }
1666     }
1667 
1668     final class MainHandler extends Handler {
MainHandler(Looper looper)1669         public MainHandler(Looper looper) {
1670             super(looper, null, true);
1671         }
1672 
1673         @Override
handleMessage(Message msg)1674         public void handleMessage(Message msg) {
1675             switch (msg.what) {
1676             case GC_BACKGROUND_PROCESSES_MSG: {
1677                 synchronized (ActivityManagerService.this) {
1678                     performAppGcsIfAppropriateLocked();
1679                 }
1680             } break;
1681             case SERVICE_TIMEOUT_MSG: {
1682                 mServices.serviceTimeout((ProcessRecord)msg.obj);
1683             } break;
1684             case SERVICE_FOREGROUND_TIMEOUT_MSG: {
1685                 mServices.serviceForegroundTimeout((ServiceRecord)msg.obj);
1686             } break;
1687             case SERVICE_FOREGROUND_CRASH_MSG: {
1688                 mServices.serviceForegroundCrash(
1689                     (ProcessRecord) msg.obj, msg.getData().getCharSequence(SERVICE_RECORD_KEY));
1690             } break;
1691             case UPDATE_TIME_ZONE: {
1692                 synchronized (ActivityManagerService.this) {
1693                     for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) {
1694                         ProcessRecord r = mProcessList.mLruProcesses.get(i);
1695                         if (r.thread != null) {
1696                             try {
1697                                 r.thread.updateTimeZone();
1698                             } catch (RemoteException ex) {
1699                                 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
1700                             }
1701                         }
1702                     }
1703                 }
1704             } break;
1705             case CLEAR_DNS_CACHE_MSG: {
1706                 synchronized (ActivityManagerService.this) {
1707                     mProcessList.clearAllDnsCacheLocked();
1708                 }
1709             } break;
1710             case UPDATE_HTTP_PROXY_MSG: {
1711                 mProcessList.setAllHttpProxy();
1712             } break;
1713             case PROC_START_TIMEOUT_MSG: {
1714                 ProcessRecord app = (ProcessRecord)msg.obj;
1715                 synchronized (ActivityManagerService.this) {
1716                     processStartTimedOutLocked(app);
1717                 }
1718             } break;
1719             case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: {
1720                 ProcessRecord app = (ProcessRecord)msg.obj;
1721                 synchronized (ActivityManagerService.this) {
1722                     processContentProviderPublishTimedOutLocked(app);
1723                 }
1724             } break;
1725             case KILL_APPLICATION_MSG: {
1726                 synchronized (ActivityManagerService.this) {
1727                     final int appId = msg.arg1;
1728                     final int userId = msg.arg2;
1729                     Bundle bundle = (Bundle)msg.obj;
1730                     String pkg = bundle.getString("pkg");
1731                     String reason = bundle.getString("reason");
1732                     forceStopPackageLocked(pkg, appId, false, false, true, false,
1733                             false, userId, reason);
1734                 }
1735             } break;
1736                 case KILL_APP_ZYGOTE_MSG: {
1737                     synchronized (ActivityManagerService.this) {
1738                         final AppZygote appZygote = (AppZygote) msg.obj;
1739                         mProcessList.killAppZygoteIfNeededLocked(appZygote);
1740                     }
1741                 } break;
1742             case CHECK_EXCESSIVE_POWER_USE_MSG: {
1743                 synchronized (ActivityManagerService.this) {
1744                     checkExcessivePowerUsageLocked();
1745                     removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
1746                     Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
1747                     sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
1748                 }
1749             } break;
1750             case REPORT_MEM_USAGE_MSG: {
1751                 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
1752                 Thread thread = new Thread() {
1753                     @Override public void run() {
1754                         reportMemUsage(memInfos);
1755                     }
1756                 };
1757                 thread.start();
1758                 break;
1759             }
1760             case UPDATE_TIME_PREFERENCE_MSG: {
1761                 // The user's time format preference might have changed.
1762                 // For convenience we re-use the Intent extra values.
1763                 synchronized (ActivityManagerService.this) {
1764                     mProcessList.updateAllTimePrefsLocked(msg.arg1);
1765                 }
1766                 break;
1767             }
1768             case NOTIFY_CLEARTEXT_NETWORK_MSG: {
1769                 final int uid = msg.arg1;
1770                 final byte[] firstPacket = (byte[]) msg.obj;
1771 
1772                 synchronized (mPidsSelfLocked) {
1773                     for (int i = 0; i < mPidsSelfLocked.size(); i++) {
1774                         final ProcessRecord p = mPidsSelfLocked.valueAt(i);
1775                         if (p.uid == uid && p.thread != null) {
1776                             try {
1777                                 p.thread.notifyCleartextNetwork(firstPacket);
1778                             } catch (RemoteException ignored) {
1779                             }
1780                         }
1781                     }
1782                 }
1783                 break;
1784             }
1785             case POST_DUMP_HEAP_NOTIFICATION_MSG: {
1786                 final String procName;
1787                 final int uid;
1788                 final long memLimit;
1789                 final String reportPackage;
1790                 final boolean isUserInitiated;
1791                 synchronized (ActivityManagerService.this) {
1792                     uid = mMemWatchDumpUid;
1793                     if (uid == SYSTEM_UID) {
1794                         procName = mContext.getString(R.string.android_system_label);
1795                     } else {
1796                         procName = mMemWatchDumpProcName;
1797                     }
1798                     Pair<Long, String> val = mMemWatchProcesses.get(procName, uid);
1799                     if (val == null) {
1800                         val = mMemWatchProcesses.get(procName, 0);
1801                     }
1802                     if (val != null) {
1803                         memLimit = val.first;
1804                         reportPackage = val.second;
1805                     } else {
1806                         memLimit = 0;
1807                         reportPackage = null;
1808                     }
1809                     isUserInitiated = mMemWatchIsUserInitiated;
1810                 }
1811                 if (procName == null) {
1812                     return;
1813                 }
1814 
1815                 if (DEBUG_PSS) Slog.d(TAG_PSS,
1816                         "Showing dump heap notification from " + procName + "/" + uid);
1817 
1818                 INotificationManager inm = NotificationManager.getService();
1819                 if (inm == null) {
1820                     return;
1821                 }
1822 
1823                 final int titleId = isUserInitiated
1824                         ? R.string.dump_heap_ready_notification : R.string.dump_heap_notification;
1825                 String text = mContext.getString(titleId, procName);
1826 
1827                 Intent deleteIntent = new Intent();
1828                 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
1829                 Intent intent = new Intent();
1830                 intent.setClassName("android", DumpHeapActivity.class.getName());
1831                 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName);
1832                 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit);
1833                 intent.putExtra(DumpHeapActivity.KEY_IS_USER_INITIATED, isUserInitiated);
1834                 intent.putExtra(DumpHeapActivity.KEY_IS_SYSTEM_PROCESS, uid == SYSTEM_UID);
1835                 if (reportPackage != null) {
1836                     intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage);
1837                 }
1838                 int userId = UserHandle.getUserId(uid);
1839                 Notification notification =
1840                         new Notification.Builder(mContext, SystemNotificationChannels.DEVELOPER)
1841                         .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
1842                         .setAutoCancel(true)
1843                         .setTicker(text)
1844                         .setColor(mContext.getColor(
1845                                 com.android.internal.R.color.system_notification_accent_color))
1846                         .setContentTitle(text)
1847                         .setContentText(
1848                                 mContext.getText(R.string.dump_heap_notification_detail))
1849                         .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
1850                                 intent, PendingIntent.FLAG_CANCEL_CURRENT, null,
1851                                 new UserHandle(userId)))
1852                         .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0,
1853                                 deleteIntent, 0, UserHandle.SYSTEM))
1854                         .build();
1855 
1856                 try {
1857                     inm.enqueueNotificationWithTag("android", "android", null,
1858                             SystemMessage.NOTE_DUMP_HEAP_NOTIFICATION,
1859                             notification, userId);
1860                 } catch (RuntimeException e) {
1861                     Slog.w(ActivityManagerService.TAG,
1862                             "Error showing notification for dump heap", e);
1863                 } catch (RemoteException e) {
1864                 }
1865             } break;
1866             case DELETE_DUMPHEAP_MSG: {
1867                 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(),
1868                         null, DumpHeapActivity.JAVA_URI,
1869                         Intent.FLAG_GRANT_READ_URI_PERMISSION
1870                                 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
1871                         UserHandle.myUserId());
1872                 synchronized (ActivityManagerService.this) {
1873                     mMemWatchDumpFile = null;
1874                     mMemWatchDumpProcName = null;
1875                     mMemWatchDumpPid = -1;
1876                     mMemWatchDumpUid = -1;
1877                 }
1878             } break;
1879             case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
1880                 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
1881                 try {
1882                     connection.shutdown();
1883                 } catch (RemoteException e) {
1884                     Slog.w(TAG, "Error shutting down UiAutomationConnection");
1885                 }
1886                 // Only a UiAutomation can set this flag and now that
1887                 // it is finished we make sure it is reset to its default.
1888                 mUserIsMonkey = false;
1889             } break;
1890             case IDLE_UIDS_MSG: {
1891                 idleUids();
1892             } break;
1893             case HANDLE_TRUST_STORAGE_UPDATE_MSG: {
1894                 synchronized (ActivityManagerService.this) {
1895                     mProcessList.handleAllTrustStorageUpdateLocked();
1896                 }
1897             } break;
1898             }
1899         }
1900     }
1901 
1902     static final int COLLECT_PSS_BG_MSG = 1;
1903     static final int DEFER_PSS_MSG = 2;
1904     static final int STOP_DEFERRING_PSS_MSG = 3;
1905 
1906     final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
1907         @Override
1908         public void handleMessage(Message msg) {
1909             switch (msg.what) {
1910             case COLLECT_PSS_BG_MSG: {
1911                 long start = SystemClock.uptimeMillis();
1912                 MemInfoReader memInfo = null;
1913                 synchronized (ActivityManagerService.this) {
1914                     if (mFullPssPending) {
1915                         mFullPssPending = false;
1916                         memInfo = new MemInfoReader();
1917                     }
1918                 }
1919                 if (memInfo != null) {
1920                     updateCpuStatsNow();
1921                     long nativeTotalPss = 0;
1922                     final List<ProcessCpuTracker.Stats> stats;
1923                     synchronized (mProcessCpuTracker) {
1924                         stats = mProcessCpuTracker.getStats( (st)-> {
1925                             return st.vsize > 0 && st.uid < FIRST_APPLICATION_UID;
1926                         });
1927                     }
1928                     final int N = stats.size();
1929                     for (int j = 0; j < N; j++) {
1930                         synchronized (mPidsSelfLocked) {
1931                             if (mPidsSelfLocked.indexOfKey(stats.get(j).pid) >= 0) {
1932                                 // This is one of our own processes; skip it.
1933                                 continue;
1934                             }
1935                         }
1936                         nativeTotalPss += Debug.getPss(stats.get(j).pid, null, null);
1937                     }
1938                     memInfo.readMemInfo();
1939                     synchronized (ActivityManagerService.this) {
1940                         if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in "
1941                                 + (SystemClock.uptimeMillis()-start) + "ms");
1942                         final long cachedKb = memInfo.getCachedSizeKb();
1943                         final long freeKb = memInfo.getFreeSizeKb();
1944                         final long zramKb = memInfo.getZramTotalSizeKb();
1945                         final long kernelKb = memInfo.getKernelUsedSizeKb();
1946                         EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
1947                                 kernelKb*1024, nativeTotalPss*1024);
1948                         mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
1949                                 nativeTotalPss);
1950                     }
1951                 }
1952 
1953                 int num = 0;
1954                 long[] tmp = new long[3];
1955                 do {
1956                     ProcessRecord proc;
1957                     int procState;
1958                     int statType;
1959                     int pid = -1;
1960                     long lastPssTime;
1961                     synchronized (ActivityManagerService.this) {
1962                         if (mPendingPssProcesses.size() <= 0) {
1963                             if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS,
1964                                     "Collected pss of " + num + " processes in "
1965                                     + (SystemClock.uptimeMillis() - start) + "ms");
1966                             mPendingPssProcesses.clear();
1967                             return;
1968                         }
1969                         proc = mPendingPssProcesses.remove(0);
1970                         procState = proc.pssProcState;
1971                         statType = proc.pssStatType;
1972                         lastPssTime = proc.lastPssTime;
1973                         long now = SystemClock.uptimeMillis();
1974                         if (proc.thread != null && procState == proc.setProcState
1975                                 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
1976                                         < now) {
1977                             pid = proc.pid;
1978                         } else {
1979                             ProcessList.abortNextPssTime(proc.procStateMemTracker);
1980                             if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid +
1981                                     ": still need " +
1982                                     (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE-now) +
1983                                     "ms until safe");
1984                             proc = null;
1985                             pid = 0;
1986                         }
1987                     }
1988                     if (proc != null) {
1989                         long startTime = SystemClock.currentThreadTimeMillis();
1990                         long pss = Debug.getPss(pid, tmp, null);
1991                         long endTime = SystemClock.currentThreadTimeMillis();
1992                         synchronized (ActivityManagerService.this) {
1993                             if (pss != 0 && proc.thread != null && proc.setProcState == procState
1994                                     && proc.pid == pid && proc.lastPssTime == lastPssTime) {
1995                                 num++;
1996                                 ProcessList.commitNextPssTime(proc.procStateMemTracker);
1997                                 recordPssSampleLocked(proc, procState, pss, tmp[0], tmp[1], tmp[2],
1998                                         statType, endTime-startTime, SystemClock.uptimeMillis());
1999                             } else {
2000                                 ProcessList.abortNextPssTime(proc.procStateMemTracker);
2001                                 if (DEBUG_PSS) Slog.d(TAG_PSS, "Skipped pss collection of " + pid +
2002                                         ": " + (proc.thread == null ? "NO_THREAD " : "") +
2003                                         (proc.pid != pid ? "PID_CHANGED " : "") +
2004                                         " initState=" + procState + " curState=" +
2005                                         proc.setProcState + " " +
2006                                         (proc.lastPssTime != lastPssTime ? "TIME_CHANGED" : ""));
2007                             }
2008                         }
2009                     }
2010                 } while (true);
2011             }
2012 
2013             case DEFER_PSS_MSG: {
2014                 deferPssForActivityStart();
2015             } break;
2016 
2017             case STOP_DEFERRING_PSS_MSG: {
2018                 final int nesting = mActivityStartingNesting.decrementAndGet();
2019                 if (nesting <= 0) {
2020                     if (DEBUG_PSS) {
2021                         Slog.d(TAG_PSS, "PSS activity start deferral interval ended; now "
2022                                 + nesting);
2023                     }
2024                     if (nesting < 0) {
2025                         Slog.wtf(TAG, "Activity start nesting undercount!");
2026                         mActivityStartingNesting.incrementAndGet();
2027                     }
2028                 } else {
2029                     if (DEBUG_PSS) {
2030                         Slog.d(TAG_PSS, "Still deferring PSS, nesting=" + nesting);
2031                     }
2032                 }
2033             }
2034             break;
2035 
2036             }
2037         }
2038     };
2039 
setSystemProcess()2040     public void setSystemProcess() {
2041         try {
2042             ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2043                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
2044             ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2045             ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2046                     DUMP_FLAG_PRIORITY_HIGH);
2047             ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2048             ServiceManager.addService("dbinfo", new DbBinder(this));
2049             if (MONITOR_CPU_USAGE) {
2050                 ServiceManager.addService("cpuinfo", new CpuBinder(this),
2051                         /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2052             }
2053             ServiceManager.addService("permission", new PermissionController(this));
2054             ServiceManager.addService("processinfo", new ProcessInfoService(this));
2055 
2056             ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2057                     "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
2058             mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2059 
2060             synchronized (this) {
2061                 ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
2062                         false,
2063                         0,
2064                         new HostingRecord("system"));
2065                 app.setPersistent(true);
2066                 app.pid = MY_PID;
2067                 app.getWindowProcessController().setPid(MY_PID);
2068                 app.maxAdj = ProcessList.SYSTEM_ADJ;
2069                 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2070                 mPidsSelfLocked.put(app);
2071                 mProcessList.updateLruProcessLocked(app, false, null);
2072                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2073             }
2074         } catch (PackageManager.NameNotFoundException e) {
2075             throw new RuntimeException(
2076                     "Unable to find android system package", e);
2077         }
2078 
2079         // Start watching app ops after we and the package manager are up and running.
2080         mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2081                 new IAppOpsCallback.Stub() {
2082                     @Override public void opChanged(int op, int uid, String packageName) {
2083                         if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2084                             if (mAppOpsService.checkOperation(op, uid, packageName)
2085                                     != AppOpsManager.MODE_ALLOWED) {
2086                                 runInBackgroundDisabled(uid);
2087                             }
2088                         }
2089                     }
2090                 });
2091     }
2092 
setWindowManager(WindowManagerService wm)2093     public void setWindowManager(WindowManagerService wm) {
2094         synchronized (this) {
2095             mWindowManager = wm;
2096             mActivityTaskManager.setWindowManager(wm);
2097         }
2098     }
2099 
setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)2100     public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2101         mUsageStatsService = usageStatsManager;
2102         mActivityTaskManager.setUsageStatsManager(usageStatsManager);
2103     }
2104 
2105     /**
2106      * Sets the internal content capture manager service.
2107      *
2108      * <p>It's called when {@code SystemServer} starts, so we don't really need to acquire the lock.
2109      */
setContentCaptureManager( @ullable ContentCaptureManagerInternal contentCaptureManager)2110     public void setContentCaptureManager(
2111             @Nullable ContentCaptureManagerInternal contentCaptureManager) {
2112         mContentCaptureService = contentCaptureManager;
2113     }
2114 
startObservingNativeCrashes()2115     public void startObservingNativeCrashes() {
2116         final NativeCrashListener ncl = new NativeCrashListener(this);
2117         ncl.start();
2118     }
2119 
getAppOpsService()2120     public IAppOpsService getAppOpsService() {
2121         return mAppOpsService;
2122     }
2123 
2124     static class MemBinder extends Binder {
2125         ActivityManagerService mActivityManagerService;
2126         private final PriorityDump.PriorityDumper mPriorityDumper =
2127                 new PriorityDump.PriorityDumper() {
2128             @Override
2129             public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args,
2130                     boolean asProto) {
2131                 dump(fd, pw, new String[] {"-a"}, asProto);
2132             }
2133 
2134             @Override
2135             public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
2136                 mActivityManagerService.dumpApplicationMemoryUsage(
2137                         fd, pw, "  ", args, false, null, asProto);
2138             }
2139         };
2140 
MemBinder(ActivityManagerService activityManagerService)2141         MemBinder(ActivityManagerService activityManagerService) {
2142             mActivityManagerService = activityManagerService;
2143         }
2144 
2145         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2146         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2147             if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2148                     "meminfo", pw)) return;
2149             PriorityDump.dump(mPriorityDumper, fd, pw, args);
2150         }
2151     }
2152 
2153     static class GraphicsBinder extends Binder {
2154         ActivityManagerService mActivityManagerService;
GraphicsBinder(ActivityManagerService activityManagerService)2155         GraphicsBinder(ActivityManagerService activityManagerService) {
2156             mActivityManagerService = activityManagerService;
2157         }
2158 
2159         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2160         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2161             if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2162                     "gfxinfo", pw)) return;
2163             mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2164         }
2165     }
2166 
2167     static class DbBinder extends Binder {
2168         ActivityManagerService mActivityManagerService;
DbBinder(ActivityManagerService activityManagerService)2169         DbBinder(ActivityManagerService activityManagerService) {
2170             mActivityManagerService = activityManagerService;
2171         }
2172 
2173         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2174         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2175             if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2176                     "dbinfo", pw)) return;
2177             mActivityManagerService.dumpDbInfo(fd, pw, args);
2178         }
2179     }
2180 
2181     static class CpuBinder extends Binder {
2182         ActivityManagerService mActivityManagerService;
2183         private final PriorityDump.PriorityDumper mPriorityDumper =
2184                 new PriorityDump.PriorityDumper() {
2185             @Override
2186             public void dumpCritical(FileDescriptor fd, PrintWriter pw, String[] args,
2187                     boolean asProto) {
2188                 if (asProto) return;
2189                 if (!DumpUtils.checkDumpAndUsageStatsPermission(mActivityManagerService.mContext,
2190                         "cpuinfo", pw)) return;
2191                 synchronized (mActivityManagerService.mProcessCpuTracker) {
2192                     pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2193                     pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2194                             SystemClock.uptimeMillis()));
2195                 }
2196             }
2197         };
2198 
CpuBinder(ActivityManagerService activityManagerService)2199         CpuBinder(ActivityManagerService activityManagerService) {
2200             mActivityManagerService = activityManagerService;
2201         }
2202 
2203         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2204         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2205             PriorityDump.dump(mPriorityDumper, fd, pw, args);
2206         }
2207     }
2208 
2209     public static final class Lifecycle extends SystemService {
2210         private final ActivityManagerService mService;
2211         private static ActivityTaskManagerService sAtm;
2212 
Lifecycle(Context context)2213         public Lifecycle(Context context) {
2214             super(context);
2215             mService = new ActivityManagerService(context, sAtm);
2216         }
2217 
startService( SystemServiceManager ssm, ActivityTaskManagerService atm)2218         public static ActivityManagerService startService(
2219                 SystemServiceManager ssm, ActivityTaskManagerService atm) {
2220             sAtm = atm;
2221             return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2222         }
2223 
2224         @Override
onStart()2225         public void onStart() {
2226             mService.start();
2227         }
2228 
2229         @Override
onBootPhase(int phase)2230         public void onBootPhase(int phase) {
2231             mService.mBootPhase = phase;
2232             if (phase == PHASE_SYSTEM_SERVICES_READY) {
2233                 mService.mBatteryStatsService.systemServicesReady();
2234                 mService.mServices.systemServicesReady();
2235             } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
2236                 mService.startBroadcastObservers();
2237             } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
2238                 mService.mPackageWatchdog.onPackagesReady();
2239             }
2240         }
2241 
2242         @Override
onCleanupUser(int userId)2243         public void onCleanupUser(int userId) {
2244             mService.mBatteryStatsService.onCleanupUser(userId);
2245         }
2246 
getService()2247         public ActivityManagerService getService() {
2248             return mService;
2249         }
2250     }
2251 
2252     /**
2253      * Encapsulates global settings related to hidden API enforcement behaviour, including tracking
2254      * the latest value via a content observer.
2255      */
2256     static class HiddenApiSettings extends ContentObserver
2257             implements DeviceConfig.OnPropertiesChangedListener {
2258 
2259         private final Context mContext;
2260         private boolean mBlacklistDisabled;
2261         private String mExemptionsStr;
2262         private List<String> mExemptions = Collections.emptyList();
2263         private int mLogSampleRate = -1;
2264         private int mStatslogSampleRate = -1;
2265         @HiddenApiEnforcementPolicy private int mPolicy = HIDDEN_API_ENFORCEMENT_DEFAULT;
2266 
2267         /**
2268          * Sampling rate for hidden API access event logs with libmetricslogger, as an integer in
2269          * the range 0 to 0x10000 inclusive.
2270          *
2271          * @hide
2272          */
2273         public static final String HIDDEN_API_ACCESS_LOG_SAMPLING_RATE =
2274                 "hidden_api_access_log_sampling_rate";
2275 
2276         /**
2277          * Sampling rate for hidden API access event logging with statslog, as an integer in the
2278          * range 0 to 0x10000 inclusive.
2279          *
2280          * @hide
2281          */
2282         public static final String HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE =
2283                 "hidden_api_access_statslog_sampling_rate";
2284 
onPropertiesChanged(DeviceConfig.Properties properties)2285         public void onPropertiesChanged(DeviceConfig.Properties properties) {
2286             int logSampleRate = properties.getInt(HIDDEN_API_ACCESS_LOG_SAMPLING_RATE,
2287                     mLogSampleRate);
2288             int statslogSampleRate = properties.getInt(HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE,
2289                     mStatslogSampleRate);
2290             setSampleRates(logSampleRate, statslogSampleRate);
2291         }
2292 
setSampleRates(int logSampleRate, int statslogSampleRate)2293         private void setSampleRates(int logSampleRate, int statslogSampleRate) {
2294             if (logSampleRate >= 0 && logSampleRate <= 0x10000
2295                     && logSampleRate != mLogSampleRate) {
2296                 mLogSampleRate = logSampleRate;
2297                 ZYGOTE_PROCESS.setHiddenApiAccessLogSampleRate(mLogSampleRate);
2298             }
2299 
2300             if (statslogSampleRate >= 0 && statslogSampleRate <= 0x10000
2301                     && statslogSampleRate != mStatslogSampleRate) {
2302                 mStatslogSampleRate = statslogSampleRate;
2303                 ZYGOTE_PROCESS.setHiddenApiAccessStatslogSampleRate(mStatslogSampleRate);
2304             }
2305 
2306         }
2307 
2308         /**
2309          * Set initial sampling rates from DeviceConfig. This is required after each restart,
2310          * if they never get updated.
2311          */
initializeSampleRates()2312         private void initializeSampleRates() {
2313             int logSampleRate = DeviceConfig.getInt(DeviceConfig.NAMESPACE_APP_COMPAT,
2314                     HIDDEN_API_ACCESS_LOG_SAMPLING_RATE, 0);
2315             int statslogSampleRate = DeviceConfig.getInt(DeviceConfig.NAMESPACE_APP_COMPAT,
2316                     HIDDEN_API_ACCESS_STATSLOG_SAMPLING_RATE, 0);
2317             setSampleRates(logSampleRate, statslogSampleRate);
2318         }
2319 
HiddenApiSettings(Handler handler, Context context)2320         public HiddenApiSettings(Handler handler, Context context) {
2321             super(handler);
2322             mContext = context;
2323         }
2324 
registerObserver()2325         public void registerObserver() {
2326             mContext.getContentResolver().registerContentObserver(
2327                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS),
2328                     false,
2329                     this);
2330             mContext.getContentResolver().registerContentObserver(
2331                     Settings.Global.getUriFor(Settings.Global.HIDDEN_API_POLICY),
2332                     false,
2333                     this);
2334             initializeSampleRates();
2335             DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_APP_COMPAT,
2336                     mContext.getMainExecutor(), this);
2337             update();
2338         }
2339 
update()2340         private void update() {
2341             String exemptions = Settings.Global.getString(mContext.getContentResolver(),
2342                     Settings.Global.HIDDEN_API_BLACKLIST_EXEMPTIONS);
2343             if (!TextUtils.equals(exemptions, mExemptionsStr)) {
2344                 mExemptionsStr = exemptions;
2345                 if ("*".equals(exemptions)) {
2346                     mBlacklistDisabled = true;
2347                     mExemptions = Collections.emptyList();
2348                 } else {
2349                     mBlacklistDisabled = false;
2350                     mExemptions = TextUtils.isEmpty(exemptions)
2351                             ? Collections.emptyList()
2352                             : Arrays.asList(exemptions.split(","));
2353                 }
2354                 if (!ZYGOTE_PROCESS.setApiBlacklistExemptions(mExemptions)) {
2355                   Slog.e(TAG, "Failed to set API blacklist exemptions!");
2356                   // leave mExemptionsStr as is, so we don't try to send the same list again.
2357                   mExemptions = Collections.emptyList();
2358                 }
2359             }
2360             mPolicy = getValidEnforcementPolicy(Settings.Global.HIDDEN_API_POLICY);
2361         }
2362 
getValidEnforcementPolicy(String settingsKey)2363         private @HiddenApiEnforcementPolicy int getValidEnforcementPolicy(String settingsKey) {
2364             int policy = Settings.Global.getInt(mContext.getContentResolver(), settingsKey,
2365                     ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT);
2366             if (ApplicationInfo.isValidHiddenApiEnforcementPolicy(policy)) {
2367                 return policy;
2368             } else {
2369                 return ApplicationInfo.HIDDEN_API_ENFORCEMENT_DEFAULT;
2370             }
2371         }
2372 
isDisabled()2373         boolean isDisabled() {
2374             return mBlacklistDisabled;
2375         }
2376 
getPolicy()2377         @HiddenApiEnforcementPolicy int getPolicy() {
2378             return mPolicy;
2379         }
2380 
onChange(boolean selfChange)2381         public void onChange(boolean selfChange) {
2382             update();
2383         }
2384     }
2385 
2386     @VisibleForTesting
ActivityManagerService(Injector injector)2387     public ActivityManagerService(Injector injector) {
2388         this(injector, null /* handlerThread */);
2389     }
2390 
2391     /**
2392      * Provides the basic functionality for activity task related tests when a handler thread is
2393      * given to initialize the dependency members.
2394      */
2395     @VisibleForTesting
ActivityManagerService(Injector injector, ServiceThread handlerThread)2396     public ActivityManagerService(Injector injector, ServiceThread handlerThread) {
2397         final boolean hasHandlerThread = handlerThread != null;
2398         mInjector = injector;
2399         mContext = mInjector.getContext();
2400         mUiContext = null;
2401         mAppErrors = null;
2402         mPackageWatchdog = null;
2403         mAppOpsService = mInjector.getAppOpsService(null /* file */, null /* handler */);
2404         mBatteryStatsService = null;
2405         mHandler = hasHandlerThread ? new MainHandler(handlerThread.getLooper()) : null;
2406         mHandlerThread = handlerThread;
2407         mConstants = hasHandlerThread
2408                 ? new ActivityManagerConstants(mContext, this, mHandler) : null;
2409         final ActiveUids activeUids = new ActiveUids(this, false /* postChangesToAtm */);
2410         mProcessList.init(this, activeUids);
2411         mLowMemDetector = null;
2412         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2413 
2414         mIntentFirewall = hasHandlerThread
2415                 ? new IntentFirewall(new IntentFirewallInterface(), mHandler) : null;
2416         mProcessCpuThread = null;
2417         mProcessStats = null;
2418         mProviderMap = null;
2419         // For the usage of {@link ActiveServices#cleanUpServices} that may be invoked from
2420         // {@link ActivityStackSupervisor#cleanUpRemovedTaskLocked}.
2421         mServices = hasHandlerThread ? new ActiveServices(this) : null;
2422         mSystemThread = null;
2423         mUiHandler = injector.getUiHandler(null /* service */);
2424         mUserController = hasHandlerThread ? new UserController(this) : null;
2425         mPendingIntentController = hasHandlerThread
2426                 ? new PendingIntentController(handlerThread.getLooper(), mUserController) : null;
2427         mProcStartHandlerThread = null;
2428         mProcStartHandler = null;
2429         mHiddenApiBlacklist = null;
2430         mFactoryTest = FACTORY_TEST_OFF;
2431     }
2432 
2433     // Note: This method is invoked on the main thread but may need to attach various
2434     // handlers to other threads.  So take care to be explicit about the looper.
ActivityManagerService(Context systemContext, ActivityTaskManagerService atm)2435     public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
2436         LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2437         mInjector = new Injector();
2438         mContext = systemContext;
2439 
2440         mFactoryTest = FactoryTest.getMode();
2441         mSystemThread = ActivityThread.currentActivityThread();
2442         mUiContext = mSystemThread.getSystemUiContext();
2443 
2444         Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2445 
2446         mHandlerThread = new ServiceThread(TAG,
2447                 THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2448         mHandlerThread.start();
2449         mHandler = new MainHandler(mHandlerThread.getLooper());
2450         mUiHandler = mInjector.getUiHandler(this);
2451 
2452         mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2453                 THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2454         mProcStartHandlerThread.start();
2455         mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
2456 
2457         mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2458         final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2459         mProcessList.init(this, activeUids);
2460         mLowMemDetector = new LowMemDetector(this);
2461         mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2462 
2463         // Broadcast policy parameters
2464         final BroadcastConstants foreConstants = new BroadcastConstants(
2465                 Settings.Global.BROADCAST_FG_CONSTANTS);
2466         foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2467 
2468         final BroadcastConstants backConstants = new BroadcastConstants(
2469                 Settings.Global.BROADCAST_BG_CONSTANTS);
2470         backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2471 
2472         final BroadcastConstants offloadConstants = new BroadcastConstants(
2473                 Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2474         offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2475         // by default, no "slow" policy in this queue
2476         offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2477 
2478         mEnableOffloadQueue = SystemProperties.getBoolean(
2479                 "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
2480 
2481         mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2482                 "foreground", foreConstants, false);
2483         mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2484                 "background", backConstants, true);
2485         mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
2486                 "offload", offloadConstants, true);
2487         mBroadcastQueues[0] = mFgBroadcastQueue;
2488         mBroadcastQueues[1] = mBgBroadcastQueue;
2489         mBroadcastQueues[2] = mOffloadBroadcastQueue;
2490 
2491         mServices = new ActiveServices(this);
2492         mProviderMap = new ProviderMap(this);
2493         mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2494         mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2495 
2496         final File systemDir = SystemServiceManager.ensureSystemDir();
2497 
2498         // TODO: Move creation of battery stats service outside of activity manager service.
2499         mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
2500                 BackgroundThread.get().getHandler());
2501         mBatteryStatsService.getActiveStatistics().readLocked();
2502         mBatteryStatsService.scheduleWriteToDisk();
2503         mOnBattery = DEBUG_POWER ? true
2504                 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2505         mBatteryStatsService.getActiveStatistics().setCallback(this);
2506         mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2507 
2508         mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2509 
2510         mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2511 
2512         mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2513 
2514         mUserController = new UserController(this);
2515 
2516         mPendingIntentController = new PendingIntentController(
2517                 mHandlerThread.getLooper(), mUserController);
2518 
2519         if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
2520             mUseFifoUiScheduling = true;
2521         }
2522 
2523         mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2524         mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2525 
2526         mActivityTaskManager = atm;
2527         mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2528                 DisplayThread.get().getLooper());
2529         mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2530 
2531         mProcessCpuThread = new Thread("CpuTracker") {
2532             @Override
2533             public void run() {
2534                 synchronized (mProcessCpuTracker) {
2535                     mProcessCpuInitLatch.countDown();
2536                     mProcessCpuTracker.init();
2537                 }
2538                 while (true) {
2539                     try {
2540                         try {
2541                             synchronized(this) {
2542                                 final long now = SystemClock.uptimeMillis();
2543                                 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2544                                 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2545                                 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2546                                 //        + ", write delay=" + nextWriteDelay);
2547                                 if (nextWriteDelay < nextCpuDelay) {
2548                                     nextCpuDelay = nextWriteDelay;
2549                                 }
2550                                 if (nextCpuDelay > 0) {
2551                                     mProcessCpuMutexFree.set(true);
2552                                     this.wait(nextCpuDelay);
2553                                 }
2554                             }
2555                         } catch (InterruptedException e) {
2556                         }
2557                         updateCpuStatsNow();
2558                     } catch (Exception e) {
2559                         Slog.e(TAG, "Unexpected exception collecting process stats", e);
2560                     }
2561                 }
2562             }
2563         };
2564 
2565         mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2566 
2567         Watchdog.getInstance().addMonitor(this);
2568         Watchdog.getInstance().addThread(mHandler);
2569 
2570         // bind background threads to little cores
2571         // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2572         // make sure we've already adjusted system_server's internal view of itself first
2573         updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2574         try {
2575             Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2576                     Process.THREAD_GROUP_SYSTEM);
2577             Process.setThreadGroupAndCpuset(
2578                     mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
2579                     Process.THREAD_GROUP_SYSTEM);
2580         } catch (Exception e) {
2581             Slog.w(TAG, "Setting background thread cpuset failed");
2582         }
2583 
2584     }
2585 
setSystemServiceManager(SystemServiceManager mgr)2586     public void setSystemServiceManager(SystemServiceManager mgr) {
2587         mSystemServiceManager = mgr;
2588     }
2589 
setInstaller(Installer installer)2590     public void setInstaller(Installer installer) {
2591         mInstaller = installer;
2592     }
2593 
start()2594     private void start() {
2595         removeAllProcessGroups();
2596         mProcessCpuThread.start();
2597 
2598         mBatteryStatsService.publish();
2599         mAppOpsService.publish(mContext);
2600         Slog.d("AppOps", "AppOpsService published");
2601         LocalServices.addService(ActivityManagerInternal.class, new LocalService());
2602         mActivityTaskManager.onActivityManagerInternalAdded();
2603         mUgmInternal.onActivityManagerInternalAdded();
2604         mPendingIntentController.onActivityManagerInternalAdded();
2605         // Wait for the synchronized block started in mProcessCpuThread,
2606         // so that any other access to mProcessCpuTracker from main thread
2607         // will be blocked during mProcessCpuTracker initialization.
2608         try {
2609             mProcessCpuInitLatch.await();
2610         } catch (InterruptedException e) {
2611             Slog.wtf(TAG, "Interrupted wait during start", e);
2612             Thread.currentThread().interrupt();
2613             throw new IllegalStateException("Interrupted wait during start");
2614         }
2615     }
2616 
initPowerManagement()2617     public void initPowerManagement() {
2618         mActivityTaskManager.onInitPowerManagement();
2619         mBatteryStatsService.initPowerManagement();
2620         mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
2621     }
2622 
getBackgroundLaunchBroadcasts()2623     private ArraySet<String> getBackgroundLaunchBroadcasts() {
2624         if (mBackgroundLaunchBroadcasts == null) {
2625             mBackgroundLaunchBroadcasts = SystemConfig.getInstance().getAllowImplicitBroadcasts();
2626         }
2627         return mBackgroundLaunchBroadcasts;
2628     }
2629 
2630     /**
2631      * Ensures that the given package name has an explicit set of allowed associations.
2632      * If it does not, give it an empty set.
2633      */
requireAllowedAssociationsLocked(String packageName)2634     void requireAllowedAssociationsLocked(String packageName) {
2635         ensureAllowedAssociations();
2636         if (mAllowedAssociations.get(packageName) == null) {
2637             mAllowedAssociations.put(packageName, new PackageAssociationInfo(packageName,
2638                     new ArraySet<>(), /* isDebuggable = */ false));
2639         }
2640     }
2641 
2642     /**
2643      * Returns true if the package {@code pkg1} running under user handle {@code uid1} is
2644      * allowed association with the package {@code pkg2} running under user handle {@code uid2}.
2645      * <p> If either of the packages are running as  part of the core system, then the
2646      * association is implicitly allowed.
2647      */
validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2)2648     boolean validateAssociationAllowedLocked(String pkg1, int uid1, String pkg2, int uid2) {
2649         ensureAllowedAssociations();
2650         // Interactions with the system uid are always allowed, since that is the core system
2651         // that everyone needs to be able to interact with. Also allow reflexive associations
2652         // within the same uid.
2653         if (uid1 == uid2 || UserHandle.getAppId(uid1) == SYSTEM_UID
2654                 || UserHandle.getAppId(uid2) == SYSTEM_UID) {
2655             return true;
2656         }
2657 
2658         // Check for association on both source and target packages.
2659         PackageAssociationInfo pai = mAllowedAssociations.get(pkg1);
2660         if (pai != null && !pai.isPackageAssociationAllowed(pkg2)) {
2661             return false;
2662         }
2663         pai = mAllowedAssociations.get(pkg2);
2664         if (pai != null && !pai.isPackageAssociationAllowed(pkg1)) {
2665             return false;
2666         }
2667         // If no explicit associations are provided in the manifest, then assume the app is
2668         // allowed associations with any package.
2669         return true;
2670     }
2671 
2672     /** Sets up allowed associations for system prebuilt packages from system config (if needed). */
ensureAllowedAssociations()2673     private void ensureAllowedAssociations() {
2674         if (mAllowedAssociations == null) {
2675             ArrayMap<String, ArraySet<String>> allowedAssociations =
2676                     SystemConfig.getInstance().getAllowedAssociations();
2677             mAllowedAssociations = new ArrayMap<>(allowedAssociations.size());
2678             PackageManagerInternal pm = getPackageManagerInternalLocked();
2679             for (int i = 0; i < allowedAssociations.size(); i++) {
2680                 final String pkg = allowedAssociations.keyAt(i);
2681                 final ArraySet<String> asc = allowedAssociations.valueAt(i);
2682 
2683                 // Query latest debuggable flag from package-manager.
2684                 boolean isDebuggable = false;
2685                 try {
2686                     ApplicationInfo ai = AppGlobals.getPackageManager()
2687                             .getApplicationInfo(pkg, MATCH_ALL, 0);
2688                     if (ai != null) {
2689                         isDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
2690                     }
2691                 } catch (RemoteException e) {
2692                     /* ignore */
2693                 }
2694                 mAllowedAssociations.put(pkg, new PackageAssociationInfo(pkg, asc, isDebuggable));
2695             }
2696         }
2697     }
2698 
2699     /** Updates allowed associations for app info (specifically, based on debuggability).  */
updateAssociationForApp(ApplicationInfo appInfo)2700     private void updateAssociationForApp(ApplicationInfo appInfo) {
2701         ensureAllowedAssociations();
2702         PackageAssociationInfo pai = mAllowedAssociations.get(appInfo.packageName);
2703         if (pai != null) {
2704             pai.setDebuggable((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
2705         }
2706     }
2707 
2708     @Override
onTransact(int code, Parcel data, Parcel reply, int flags)2709     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2710             throws RemoteException {
2711         if (code == SYSPROPS_TRANSACTION) {
2712             // We need to tell all apps about the system property change.
2713             ArrayList<IBinder> procs = new ArrayList<IBinder>();
2714             synchronized (this) {
2715                 final int NP = mProcessList.mProcessNames.getMap().size();
2716                 for (int ip = 0; ip < NP; ip++) {
2717                     SparseArray<ProcessRecord> apps =
2718                             mProcessList.mProcessNames.getMap().valueAt(ip);
2719                     final int NA = apps.size();
2720                     for (int ia = 0; ia < NA; ia++) {
2721                         ProcessRecord app = apps.valueAt(ia);
2722                         if (app.thread != null) {
2723                             procs.add(app.thread.asBinder());
2724                         }
2725                     }
2726                 }
2727             }
2728 
2729             int N = procs.size();
2730             for (int i=0; i<N; i++) {
2731                 Parcel data2 = Parcel.obtain();
2732                 try {
2733                     procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null,
2734                             Binder.FLAG_ONEWAY);
2735                 } catch (RemoteException e) {
2736                 }
2737                 data2.recycle();
2738             }
2739         }
2740         try {
2741             return super.onTransact(code, data, reply, flags);
2742         } catch (RuntimeException e) {
2743             // The activity manager only throws certain exceptions intentionally, so let's
2744             // log all others.
2745             if (!(e instanceof SecurityException
2746                     || e instanceof IllegalArgumentException
2747                     || e instanceof IllegalStateException)) {
2748                 Slog.wtf(TAG, "Activity Manager Crash."
2749                         + " UID:" + Binder.getCallingUid()
2750                         + " PID:" + Binder.getCallingPid()
2751                         + " TRANS:" + code, e);
2752             }
2753             throw e;
2754         }
2755     }
2756 
updateCpuStats()2757     void updateCpuStats() {
2758         final long now = SystemClock.uptimeMillis();
2759         if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2760             return;
2761         }
2762         if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2763             synchronized (mProcessCpuThread) {
2764                 mProcessCpuThread.notify();
2765             }
2766         }
2767     }
2768 
updateCpuStatsNow()2769     void updateCpuStatsNow() {
2770         synchronized (mProcessCpuTracker) {
2771             mProcessCpuMutexFree.set(false);
2772             final long now = SystemClock.uptimeMillis();
2773             boolean haveNewCpuStats = false;
2774 
2775             if (MONITOR_CPU_USAGE &&
2776                     mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2777                 mLastCpuTime.set(now);
2778                 mProcessCpuTracker.update();
2779                 if (mProcessCpuTracker.hasGoodLastStats()) {
2780                     haveNewCpuStats = true;
2781                     //Slog.i(TAG, mProcessCpu.printCurrentState());
2782                     //Slog.i(TAG, "Total CPU usage: "
2783                     //        + mProcessCpu.getTotalCpuPercent() + "%");
2784 
2785                     // Slog the cpu usage if the property is set.
2786                     if ("true".equals(SystemProperties.get("events.cpu"))) {
2787                         int user = mProcessCpuTracker.getLastUserTime();
2788                         int system = mProcessCpuTracker.getLastSystemTime();
2789                         int iowait = mProcessCpuTracker.getLastIoWaitTime();
2790                         int irq = mProcessCpuTracker.getLastIrqTime();
2791                         int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2792                         int idle = mProcessCpuTracker.getLastIdleTime();
2793 
2794                         int total = user + system + iowait + irq + softIrq + idle;
2795                         if (total == 0) total = 1;
2796 
2797                         EventLog.writeEvent(EventLogTags.CPU,
2798                                 ((user+system+iowait+irq+softIrq) * 100) / total,
2799                                 (user * 100) / total,
2800                                 (system * 100) / total,
2801                                 (iowait * 100) / total,
2802                                 (irq * 100) / total,
2803                                 (softIrq * 100) / total);
2804                     }
2805                 }
2806             }
2807 
2808             final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
2809             synchronized(bstats) {
2810                 synchronized(mPidsSelfLocked) {
2811                     if (haveNewCpuStats) {
2812                         if (bstats.startAddingCpuLocked()) {
2813                             int totalUTime = 0;
2814                             int totalSTime = 0;
2815                             final int N = mProcessCpuTracker.countStats();
2816                             for (int i=0; i<N; i++) {
2817                                 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
2818                                 if (!st.working) {
2819                                     continue;
2820                                 }
2821                                 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
2822                                 totalUTime += st.rel_utime;
2823                                 totalSTime += st.rel_stime;
2824                                 if (pr != null) {
2825                                     BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
2826                                     if (ps == null || !ps.isActive()) {
2827                                         pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
2828                                                 pr.info.uid, pr.processName);
2829                                     }
2830                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2831                                     pr.curCpuTime += st.rel_utime + st.rel_stime;
2832                                     if (pr.lastCpuTime == 0) {
2833                                         pr.lastCpuTime = pr.curCpuTime;
2834                                     }
2835                                 } else {
2836                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
2837                                     if (ps == null || !ps.isActive()) {
2838                                         st.batteryStats = ps = bstats.getProcessStatsLocked(
2839                                                 bstats.mapUid(st.uid), st.name);
2840                                     }
2841                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
2842                                 }
2843                             }
2844                             final int userTime = mProcessCpuTracker.getLastUserTime();
2845                             final int systemTime = mProcessCpuTracker.getLastSystemTime();
2846                             final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime();
2847                             final int irqTime = mProcessCpuTracker.getLastIrqTime();
2848                             final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime();
2849                             final int idleTime = mProcessCpuTracker.getLastIdleTime();
2850                             bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime,
2851                                     systemTime, iowaitTime, irqTime, softIrqTime, idleTime);
2852                         }
2853                     }
2854                 }
2855 
2856                 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2857                     mLastWriteTime = now;
2858                     mBatteryStatsService.scheduleWriteToDisk();
2859                 }
2860             }
2861         }
2862     }
2863 
2864     @Override
batteryNeedsCpuUpdate()2865     public void batteryNeedsCpuUpdate() {
2866         updateCpuStatsNow();
2867     }
2868 
2869     @Override
batteryPowerChanged(boolean onBattery)2870     public void batteryPowerChanged(boolean onBattery) {
2871         // When plugging in, update the CPU stats first before changing
2872         // the plug state.
2873         updateCpuStatsNow();
2874         synchronized (this) {
2875             synchronized(mPidsSelfLocked) {
2876                 mOnBattery = DEBUG_POWER ? true : onBattery;
2877             }
2878             mOomAdjProfiler.batteryPowerChanged(onBattery);
2879         }
2880     }
2881 
2882     @Override
batteryStatsReset()2883     public void batteryStatsReset() {
2884         mOomAdjProfiler.reset();
2885     }
2886 
2887     @Override
batterySendBroadcast(Intent intent)2888     public void batterySendBroadcast(Intent intent) {
2889         synchronized (this) {
2890             broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
2891                     OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
2892                     Binder.getCallingPid(), UserHandle.USER_ALL);
2893         }
2894     }
2895 
2896     /**
2897      * Initialize the application bind args. These are passed to each
2898      * process when the bindApplication() IPC is sent to the process. They're
2899      * lazily setup to make sure the services are running when they're asked for.
2900      */
getCommonServicesLocked(boolean isolated)2901     private ArrayMap<String, IBinder> getCommonServicesLocked(boolean isolated) {
2902         // Isolated processes won't get this optimization, so that we don't
2903         // violate the rules about which services they have access to.
2904         if (isolated) {
2905             if (mIsolatedAppBindArgs == null) {
2906                 mIsolatedAppBindArgs = new ArrayMap<>(1);
2907                 addServiceToMap(mIsolatedAppBindArgs, "package");
2908             }
2909             return mIsolatedAppBindArgs;
2910         }
2911 
2912         if (mAppBindArgs == null) {
2913             mAppBindArgs = new ArrayMap<>();
2914 
2915             // Add common services.
2916             // IMPORTANT: Before adding services here, make sure ephemeral apps can access them too.
2917             // Enable the check in ApplicationThread.bindApplication() to make sure.
2918             addServiceToMap(mAppBindArgs, "package");
2919             addServiceToMap(mAppBindArgs, Context.WINDOW_SERVICE);
2920             addServiceToMap(mAppBindArgs, Context.ALARM_SERVICE);
2921             addServiceToMap(mAppBindArgs, Context.DISPLAY_SERVICE);
2922             addServiceToMap(mAppBindArgs, Context.NETWORKMANAGEMENT_SERVICE);
2923             addServiceToMap(mAppBindArgs, Context.CONNECTIVITY_SERVICE);
2924             addServiceToMap(mAppBindArgs, Context.ACCESSIBILITY_SERVICE);
2925             addServiceToMap(mAppBindArgs, Context.INPUT_METHOD_SERVICE);
2926             addServiceToMap(mAppBindArgs, Context.INPUT_SERVICE);
2927             addServiceToMap(mAppBindArgs, "graphicsstats");
2928             addServiceToMap(mAppBindArgs, Context.APP_OPS_SERVICE);
2929             addServiceToMap(mAppBindArgs, "content");
2930             addServiceToMap(mAppBindArgs, Context.JOB_SCHEDULER_SERVICE);
2931             addServiceToMap(mAppBindArgs, Context.NOTIFICATION_SERVICE);
2932             addServiceToMap(mAppBindArgs, Context.VIBRATOR_SERVICE);
2933             addServiceToMap(mAppBindArgs, Context.ACCOUNT_SERVICE);
2934             addServiceToMap(mAppBindArgs, Context.POWER_SERVICE);
2935             addServiceToMap(mAppBindArgs, Context.USER_SERVICE);
2936             addServiceToMap(mAppBindArgs, "mount");
2937         }
2938         return mAppBindArgs;
2939     }
2940 
addServiceToMap(ArrayMap<String, IBinder> map, String name)2941     private static void addServiceToMap(ArrayMap<String, IBinder> map, String name) {
2942         final IBinder service = ServiceManager.getService(name);
2943         if (service != null) {
2944             map.put(name, service);
2945             if (false) {
2946                 Log.i(TAG, "Adding " + name + " to the pre-loaded service cache.");
2947             }
2948         }
2949     }
2950 
2951     @Override
setFocusedStack(int stackId)2952     public void setFocusedStack(int stackId) {
2953         mActivityTaskManager.setFocusedStack(stackId);
2954     }
2955 
2956     /** Sets the task stack listener that gets callbacks when a task stack changes. */
2957     @Override
registerTaskStackListener(ITaskStackListener listener)2958     public void registerTaskStackListener(ITaskStackListener listener) {
2959         mActivityTaskManager.registerTaskStackListener(listener);
2960     }
2961 
2962     /**
2963      * Unregister a task stack listener so that it stops receiving callbacks.
2964      */
2965     @Override
unregisterTaskStackListener(ITaskStackListener listener)2966     public void unregisterTaskStackListener(ITaskStackListener listener) {
2967         mActivityTaskManager.unregisterTaskStackListener(listener);
2968     }
2969 
updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2970     final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2971             ProcessRecord client) {
2972         mProcessList.updateLruProcessLocked(app, activityChange, client);
2973     }
2974 
removeLruProcessLocked(ProcessRecord app)2975     final void removeLruProcessLocked(ProcessRecord app) {
2976         mProcessList.removeLruProcessLocked(app);
2977     }
2978 
getProcessRecordLocked(String processName, int uid, boolean keepIfLarge)2979     final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
2980         return mProcessList.getProcessRecordLocked(processName, uid, keepIfLarge);
2981     }
2982 
getProcessNames()2983     final ProcessMap<ProcessRecord> getProcessNames() {
2984         return mProcessList.mProcessNames;
2985     }
2986 
notifyPackageUse(String packageName, int reason)2987     void notifyPackageUse(String packageName, int reason) {
2988         synchronized(this) {
2989             getPackageManagerInternalLocked().notifyPackageUse(packageName, reason);
2990         }
2991     }
2992 
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)2993     boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
2994             String processName, String abiOverride, int uid, Runnable crashHandler) {
2995         synchronized(this) {
2996             ApplicationInfo info = new ApplicationInfo();
2997             // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
2998             // For isolated processes, the former contains the parent's uid and the latter the
2999             // actual uid of the isolated process.
3000             // In the special case introduced by this method (which is, starting an isolated
3001             // process directly from the SystemServer without an actual parent app process) the
3002             // closest thing to a parent's uid is SYSTEM_UID.
3003             // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
3004             // the |isolated| logic in the ProcessRecord constructor.
3005             info.uid = SYSTEM_UID;
3006             info.processName = processName;
3007             info.className = entryPoint;
3008             info.packageName = "android";
3009             info.seInfoUser = SELinuxUtil.COMPLETE_STR;
3010             info.targetSdkVersion = Build.VERSION.SDK_INT;
3011             ProcessRecord proc = mProcessList.startProcessLocked(processName, info /* info */,
3012                     false /* knownToBeDead */, 0 /* intentFlags */,
3013                     sNullHostingRecord  /* hostingRecord */,
3014                     true /* allowWhileBooting */, true /* isolated */,
3015                     uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
3016                     crashHandler);
3017             return proc != null;
3018         }
3019     }
3020 
3021     @GuardedBy("this")
startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge)3022     final ProcessRecord startProcessLocked(String processName,
3023             ApplicationInfo info, boolean knownToBeDead, int intentFlags,
3024             HostingRecord hostingRecord, boolean allowWhileBooting,
3025             boolean isolated, boolean keepIfLarge) {
3026         return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
3027                 hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
3028                 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
3029                 null /* crashHandler */);
3030     }
3031 
isAllowedWhileBooting(ApplicationInfo ai)3032     boolean isAllowedWhileBooting(ApplicationInfo ai) {
3033         return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
3034     }
3035 
3036     /**
3037      * Update battery stats on the activity' usage.
3038      * @param activity
3039      * @param uid
3040      * @param userId
3041      * @param resumed
3042      */
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)3043     void updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed) {
3044         if (DEBUG_SWITCH) {
3045             Slog.d(TAG_SWITCH,
3046                     "updateBatteryStats: comp=" + activity + "res=" + resumed);
3047         }
3048         final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3049         StatsLog.write(StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED,
3050                 uid, activity.getPackageName(), activity.getShortClassName(),
3051                 resumed ? StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__FOREGROUND :
3052                         StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__STATE__BACKGROUND);
3053         synchronized (stats) {
3054             if (resumed) {
3055                 stats.noteActivityResumedLocked(uid);
3056             } else {
3057                 stats.noteActivityPausedLocked(uid);
3058             }
3059         }
3060     }
3061 
3062     /**
3063      * Update UsageStas on the activity's usage.
3064      * @param activity
3065      * @param userId
3066      * @param event
3067      * @param appToken ActivityRecord's appToken.
3068      * @param taskRoot TaskRecord's root
3069      */
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)3070     public void updateActivityUsageStats(ComponentName activity, int userId, int event,
3071             IBinder appToken, ComponentName taskRoot) {
3072         if (DEBUG_SWITCH) {
3073             Slog.d(TAG_SWITCH, "updateActivityUsageStats: comp="
3074                     + activity + " hash=" + appToken.hashCode() + " event=" + event);
3075         }
3076         synchronized (this) {
3077             if (mUsageStatsService != null) {
3078                 mUsageStatsService.reportEvent(activity, userId, event, appToken.hashCode(),
3079                         taskRoot);
3080             }
3081         }
3082         if (mContentCaptureService != null && (event == Event.ACTIVITY_PAUSED
3083                 || event == Event.ACTIVITY_RESUMED || event == Event.ACTIVITY_STOPPED
3084                 || event == Event.ACTIVITY_DESTROYED)) {
3085             mContentCaptureService.notifyActivityEvent(userId, activity, event);
3086         }
3087     }
3088 
3089     /**
3090      * Update UsageStats on this package's usage.
3091      * @param packageName
3092      * @param userId
3093      * @param event
3094      */
updateActivityUsageStats(String packageName, int userId, int event)3095     public void updateActivityUsageStats(String packageName, int userId, int event) {
3096         if (DEBUG_SWITCH) {
3097             Slog.d(TAG_SWITCH, "updateActivityUsageStats: package="
3098                     + packageName + " event=" + event);
3099         }
3100         synchronized (this) {
3101             if (mUsageStatsService != null) {
3102                 mUsageStatsService.reportEvent(packageName, userId, event);
3103             }
3104         }
3105     }
3106 
3107     /**
3108      * Update Usages on this foreground service's usage.
3109      * @param service
3110      * @param userId
3111      * @param started
3112      */
updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started)3113     void updateForegroundServiceUsageStats(ComponentName service, int userId, boolean started) {
3114         if (DEBUG_SWITCH) {
3115             Slog.d(TAG_SWITCH, "updateForegroundServiceUsageStats: comp="
3116                     + service + " started=" + started);
3117         }
3118         synchronized (this) {
3119             if (mUsageStatsService != null) {
3120                 mUsageStatsService.reportEvent(service, userId,
3121                         started ? UsageEvents.Event.FOREGROUND_SERVICE_START
3122                                 : UsageEvents.Event.FOREGROUND_SERVICE_STOP, 0, null);
3123             }
3124         }
3125     }
3126 
compatibilityInfoForPackage(ApplicationInfo ai)3127     CompatibilityInfo compatibilityInfoForPackage(ApplicationInfo ai) {
3128         return mAtmInternal.compatibilityInfoForPackage(ai);
3129     }
3130 
enforceNotIsolatedCaller(String caller)3131     private void enforceNotIsolatedCaller(String caller) {
3132         if (UserHandle.isIsolated(Binder.getCallingUid())) {
3133             throw new SecurityException("Isolated process not allowed to call " + caller);
3134         }
3135     }
3136 
3137     @Override
setPackageScreenCompatMode(String packageName, int mode)3138     public void setPackageScreenCompatMode(String packageName, int mode) {
3139         mActivityTaskManager.setPackageScreenCompatMode(packageName, mode);
3140     }
3141 
hasUsageStatsPermission(String callingPackage)3142     private boolean hasUsageStatsPermission(String callingPackage) {
3143         final int mode = mAppOpsService.noteOperation(AppOpsManager.OP_GET_USAGE_STATS,
3144                 Binder.getCallingUid(), callingPackage);
3145         if (mode == AppOpsManager.MODE_DEFAULT) {
3146             return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS)
3147                     == PackageManager.PERMISSION_GRANTED;
3148         }
3149         return mode == AppOpsManager.MODE_ALLOWED;
3150     }
3151 
3152     @Override
getPackageProcessState(String packageName, String callingPackage)3153     public int getPackageProcessState(String packageName, String callingPackage) {
3154         if (!hasUsageStatsPermission(callingPackage)) {
3155             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
3156                     "getPackageProcessState");
3157         }
3158 
3159         int procState = PROCESS_STATE_NONEXISTENT;
3160         synchronized (this) {
3161             for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) {
3162                 final ProcessRecord proc = mProcessList.mLruProcesses.get(i);
3163                 if (procState > proc.setProcState) {
3164                     if (proc.pkgList.containsKey(packageName) ||
3165                             (proc.pkgDeps != null && proc.pkgDeps.contains(packageName))) {
3166                         procState = proc.setProcState;
3167                     }
3168                 }
3169             }
3170         }
3171         return procState;
3172     }
3173 
3174     @Override
setProcessMemoryTrimLevel(String process, int userId, int level)3175     public boolean setProcessMemoryTrimLevel(String process, int userId, int level)
3176             throws RemoteException {
3177         if (!isCallerShell()) {
3178             EventLog.writeEvent(0x534e4554, 160390416, Binder.getCallingUid(), "");
3179             throw new SecurityException("Only shell can call it");
3180         }
3181         synchronized (this) {
3182             final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel");
3183             if (app == null) {
3184                 throw new IllegalArgumentException("Unknown process: " + process);
3185             }
3186             if (app.thread == null) {
3187                 throw new IllegalArgumentException("Process has no app thread");
3188             }
3189             if (app.trimMemoryLevel >= level) {
3190                 throw new IllegalArgumentException(
3191                         "Unable to set a higher trim level than current level");
3192             }
3193             if (!(level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN ||
3194                     app.getCurProcState() > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND)) {
3195                 throw new IllegalArgumentException("Unable to set a background trim level "
3196                     + "on a foreground process");
3197             }
3198             app.thread.scheduleTrimMemory(level);
3199             app.trimMemoryLevel = level;
3200             return true;
3201         }
3202     }
3203 
dispatchProcessesChanged()3204     private void dispatchProcessesChanged() {
3205         int N;
3206         synchronized (this) {
3207             N = mPendingProcessChanges.size();
3208             if (mActiveProcessChanges.length < N) {
3209                 mActiveProcessChanges = new ProcessChangeItem[N];
3210             }
3211             mPendingProcessChanges.toArray(mActiveProcessChanges);
3212             mPendingProcessChanges.clear();
3213             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3214                     "*** Delivering " + N + " process changes");
3215         }
3216 
3217         int i = mProcessObservers.beginBroadcast();
3218         while (i > 0) {
3219             i--;
3220             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3221             if (observer != null) {
3222                 try {
3223                     for (int j=0; j<N; j++) {
3224                         ProcessChangeItem item = mActiveProcessChanges[j];
3225                         if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
3226                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3227                                     "ACTIVITIES CHANGED pid=" + item.pid + " uid="
3228                                     + item.uid + ": " + item.foregroundActivities);
3229                             observer.onForegroundActivitiesChanged(item.pid, item.uid,
3230                                     item.foregroundActivities);
3231                         }
3232                         if ((item.changes & ProcessChangeItem.CHANGE_FOREGROUND_SERVICES) != 0) {
3233                             if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3234                                     "FOREGROUND SERVICES CHANGED pid=" + item.pid + " uid="
3235                                             + item.uid + ": " + item.foregroundServiceTypes);
3236                             observer.onForegroundServicesChanged(item.pid, item.uid,
3237                                     item.foregroundServiceTypes);
3238                         }
3239                     }
3240                 } catch (RemoteException e) {
3241                 }
3242             }
3243         }
3244         mProcessObservers.finishBroadcast();
3245 
3246         synchronized (this) {
3247             for (int j=0; j<N; j++) {
3248                 mAvailProcessChanges.add(mActiveProcessChanges[j]);
3249             }
3250         }
3251     }
3252 
3253     @GuardedBy("this")
enqueueProcessChangeItemLocked(int pid, int uid)3254     ProcessChangeItem enqueueProcessChangeItemLocked(int pid, int uid) {
3255         int i = mPendingProcessChanges.size()-1;
3256         ActivityManagerService.ProcessChangeItem item = null;
3257         while (i >= 0) {
3258             item = mPendingProcessChanges.get(i);
3259             if (item.pid == pid) {
3260                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3261                         "Re-using existing item: " + item);
3262                 break;
3263             }
3264             i--;
3265         }
3266 
3267         if (i < 0) {
3268             // No existing item in pending changes; need a new one.
3269             final int NA = mAvailProcessChanges.size();
3270             if (NA > 0) {
3271                 item = mAvailProcessChanges.remove(NA-1);
3272                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3273                         "Retrieving available item: " + item);
3274             } else {
3275                 item = new ActivityManagerService.ProcessChangeItem();
3276                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3277                         "Allocating new item: " + item);
3278             }
3279             item.changes = 0;
3280             item.pid = pid;
3281             item.uid = uid;
3282             if (mPendingProcessChanges.size() == 0) {
3283                 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS,
3284                         "*** Enqueueing dispatch processes changed!");
3285                 mUiHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED_UI_MSG)
3286                         .sendToTarget();
3287             }
3288             mPendingProcessChanges.add(item);
3289         }
3290 
3291         return item;
3292     }
3293 
dispatchProcessDied(int pid, int uid)3294     private void dispatchProcessDied(int pid, int uid) {
3295         int i = mProcessObservers.beginBroadcast();
3296         while (i > 0) {
3297             i--;
3298             final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3299             if (observer != null) {
3300                 try {
3301                     observer.onProcessDied(pid, uid);
3302                 } catch (RemoteException e) {
3303                 }
3304             }
3305         }
3306         mProcessObservers.finishBroadcast();
3307     }
3308 
3309     @VisibleForTesting
dispatchUidsChanged()3310     void dispatchUidsChanged() {
3311         int N;
3312         synchronized (this) {
3313             N = mPendingUidChanges.size();
3314             if (mActiveUidChanges.length < N) {
3315                 mActiveUidChanges = new UidRecord.ChangeItem[N];
3316             }
3317             for (int i=0; i<N; i++) {
3318                 final UidRecord.ChangeItem change = mPendingUidChanges.get(i);
3319                 mActiveUidChanges[i] = change;
3320                 if (change.uidRecord != null) {
3321                     change.uidRecord.pendingChange = null;
3322                     change.uidRecord = null;
3323                 }
3324             }
3325             mPendingUidChanges.clear();
3326             if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3327                     "*** Delivering " + N + " uid changes");
3328         }
3329 
3330         mUidChangeDispatchCount += N;
3331         int i = mUidObservers.beginBroadcast();
3332         while (i > 0) {
3333             i--;
3334             dispatchUidsChangedForObserver(mUidObservers.getBroadcastItem(i),
3335                     (UidObserverRegistration) mUidObservers.getBroadcastCookie(i), N);
3336         }
3337         mUidObservers.finishBroadcast();
3338 
3339         if (VALIDATE_UID_STATES && mUidObservers.getRegisteredCallbackCount() > 0) {
3340             for (int j = 0; j < N; ++j) {
3341                 final UidRecord.ChangeItem item = mActiveUidChanges[j];
3342                 if ((item.change & UidRecord.CHANGE_GONE) != 0) {
3343                     mValidateUids.remove(item.uid);
3344                 } else {
3345                     UidRecord validateUid = mValidateUids.get(item.uid);
3346                     if (validateUid == null) {
3347                         validateUid = new UidRecord(item.uid);
3348                         mValidateUids.put(item.uid, validateUid);
3349                     }
3350                     if ((item.change & UidRecord.CHANGE_IDLE) != 0) {
3351                         validateUid.idle = true;
3352                     } else if ((item.change & UidRecord.CHANGE_ACTIVE) != 0) {
3353                         validateUid.idle = false;
3354                     }
3355                     validateUid.setCurProcState(validateUid.setProcState = item.processState);
3356                     validateUid.lastDispatchedProcStateSeq = item.procStateSeq;
3357                 }
3358             }
3359         }
3360 
3361         synchronized (this) {
3362             for (int j = 0; j < N; j++) {
3363                 mAvailUidChanges.add(mActiveUidChanges[j]);
3364             }
3365         }
3366     }
3367 
dispatchUidsChangedForObserver(IUidObserver observer, UidObserverRegistration reg, int changesSize)3368     private void dispatchUidsChangedForObserver(IUidObserver observer,
3369             UidObserverRegistration reg, int changesSize) {
3370         if (observer == null) {
3371             return;
3372         }
3373         try {
3374             for (int j = 0; j < changesSize; j++) {
3375                 UidRecord.ChangeItem item = mActiveUidChanges[j];
3376                 final int change = item.change;
3377                 if (change == UidRecord.CHANGE_PROCSTATE &&
3378                         (reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) == 0) {
3379                     // No-op common case: no significant change, the observer is not
3380                     // interested in all proc state changes.
3381                     continue;
3382                 }
3383                 final long start = SystemClock.uptimeMillis();
3384                 if ((change & UidRecord.CHANGE_IDLE) != 0) {
3385                     if ((reg.which & ActivityManager.UID_OBSERVER_IDLE) != 0) {
3386                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3387                                 "UID idle uid=" + item.uid);
3388                         observer.onUidIdle(item.uid, item.ephemeral);
3389                     }
3390                 } else if ((change & UidRecord.CHANGE_ACTIVE) != 0) {
3391                     if ((reg.which & ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
3392                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3393                                 "UID active uid=" + item.uid);
3394                         observer.onUidActive(item.uid);
3395                     }
3396                 }
3397                 if ((reg.which & ActivityManager.UID_OBSERVER_CACHED) != 0) {
3398                     if ((change & UidRecord.CHANGE_CACHED) != 0) {
3399                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3400                                 "UID cached uid=" + item.uid);
3401                         observer.onUidCachedChanged(item.uid, true);
3402                     } else if ((change & UidRecord.CHANGE_UNCACHED) != 0) {
3403                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3404                                 "UID active uid=" + item.uid);
3405                         observer.onUidCachedChanged(item.uid, false);
3406                     }
3407                 }
3408                 if ((change & UidRecord.CHANGE_GONE) != 0) {
3409                     if ((reg.which & ActivityManager.UID_OBSERVER_GONE) != 0) {
3410                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3411                                 "UID gone uid=" + item.uid);
3412                         observer.onUidGone(item.uid, item.ephemeral);
3413                     }
3414                     if (reg.lastProcStates != null) {
3415                         reg.lastProcStates.delete(item.uid);
3416                     }
3417                 } else {
3418                     if ((reg.which & ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
3419                         if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
3420                                 "UID CHANGED uid=" + item.uid
3421                                         + ": " + item.processState);
3422                         boolean doReport = true;
3423                         if (reg.cutpoint >= ActivityManager.MIN_PROCESS_STATE) {
3424                             final int lastState = reg.lastProcStates.get(item.uid,
3425                                     ActivityManager.PROCESS_STATE_UNKNOWN);
3426                             if (lastState != ActivityManager.PROCESS_STATE_UNKNOWN) {
3427                                 final boolean lastAboveCut = lastState <= reg.cutpoint;
3428                                 final boolean newAboveCut = item.processState <= reg.cutpoint;
3429                                 doReport = lastAboveCut != newAboveCut;
3430                             } else {
3431                                 doReport = item.processState != PROCESS_STATE_NONEXISTENT;
3432                             }
3433                         }
3434                         if (doReport) {
3435                             if (reg.lastProcStates != null) {
3436                                 reg.lastProcStates.put(item.uid, item.processState);
3437                             }
3438                             observer.onUidStateChanged(item.uid, item.processState,
3439                                     item.procStateSeq);
3440                         }
3441                     }
3442                 }
3443                 final int duration = (int) (SystemClock.uptimeMillis() - start);
3444                 if (reg.mMaxDispatchTime < duration) {
3445                     reg.mMaxDispatchTime = duration;
3446                 }
3447                 if (duration >= SLOW_UID_OBSERVER_THRESHOLD_MS) {
3448                     reg.mSlowDispatchCount++;
3449                 }
3450             }
3451         } catch (RemoteException e) {
3452         }
3453     }
3454 
dispatchOomAdjObserver(String msg)3455     void dispatchOomAdjObserver(String msg) {
3456         OomAdjObserver observer;
3457         synchronized (this) {
3458             observer = mCurOomAdjObserver;
3459         }
3460 
3461         if (observer != null) {
3462             observer.onOomAdjMessage(msg);
3463         }
3464     }
3465 
setOomAdjObserver(int uid, OomAdjObserver observer)3466     void setOomAdjObserver(int uid, OomAdjObserver observer) {
3467         synchronized (this) {
3468             mCurOomAdjUid = uid;
3469             mCurOomAdjObserver = observer;
3470         }
3471     }
3472 
clearOomAdjObserver()3473     void clearOomAdjObserver() {
3474         synchronized (this) {
3475             mCurOomAdjUid = -1;
3476             mCurOomAdjObserver = null;
3477         }
3478     }
3479 
reportOomAdjMessageLocked(String tag, String msg)3480     void reportOomAdjMessageLocked(String tag, String msg) {
3481         Slog.d(tag, msg);
3482         if (mCurOomAdjObserver != null) {
3483             mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3484         }
3485     }
3486 
reportUidInfoMessageLocked(String tag, String msg, int uid)3487     void reportUidInfoMessageLocked(String tag, String msg, int uid) {
3488         Slog.i(TAG, msg);
3489         if (mCurOomAdjObserver != null && uid == mCurOomAdjUid) {
3490             mUiHandler.obtainMessage(DISPATCH_OOM_ADJ_OBSERVER_MSG, msg).sendToTarget();
3491         }
3492 
3493     }
3494 
3495     @Override
startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions)3496     public int startActivity(IApplicationThread caller, String callingPackage,
3497             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3498             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
3499         return mActivityTaskManager.startActivity(caller, callingPackage, intent, resolvedType,
3500                 resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
3501     }
3502 
3503     @Override
startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3504     public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3505             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3506             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3507 
3508             return mActivityTaskManager.startActivityAsUser(caller, callingPackage, intent,
3509                     resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo,
3510                     bOptions, userId);
3511     }
3512 
startActivityAndWait(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId)3513     WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3514             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
3515             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
3516             return mActivityTaskManager.startActivityAndWait(caller, callingPackage, intent,
3517                     resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo,
3518                     bOptions, userId);
3519     }
3520 
3521     @Override
startActivityFromRecents(int taskId, Bundle bOptions)3522     public final int startActivityFromRecents(int taskId, Bundle bOptions) {
3523         return mActivityTaskManager.startActivityFromRecents(taskId, bOptions);
3524     }
3525 
3526     @Override
startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver, IRecentsAnimationRunner recentsAnimationRunner)3527     public void startRecentsActivity(Intent intent, IAssistDataReceiver assistDataReceiver,
3528             IRecentsAnimationRunner recentsAnimationRunner) {
3529         mActivityTaskManager.startRecentsActivity(
3530                 intent, assistDataReceiver, recentsAnimationRunner);
3531     }
3532 
3533     @Override
cancelRecentsAnimation(boolean restoreHomeStackPosition)3534     public void cancelRecentsAnimation(boolean restoreHomeStackPosition) {
3535         mActivityTaskManager.cancelRecentsAnimation(restoreHomeStackPosition);
3536     }
3537 
3538     /**
3539      * This is the internal entry point for handling Activity.finish().
3540      *
3541      * @param token The Binder token referencing the Activity we want to finish.
3542      * @param resultCode Result code, if any, from this Activity.
3543      * @param resultData Result data (Intent), if any, from this Activity.
3544      * @param finishTask Whether to finish the task associated with this Activity.
3545      *
3546      * @return Returns true if the activity successfully finished, or false if it is still running.
3547      */
3548     @Override
finishActivity(IBinder token, int resultCode, Intent resultData, int finishTask)3549     public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
3550             int finishTask) {
3551         return mActivityTaskManager.finishActivity(token, resultCode, resultData, finishTask);
3552     }
3553 
3554     @Override
setRequestedOrientation(IBinder token, int requestedOrientation)3555     public void setRequestedOrientation(IBinder token, int requestedOrientation) {
3556         mActivityTaskManager.setRequestedOrientation(token, requestedOrientation);
3557     }
3558 
3559     @Override
finishHeavyWeightApp()3560     public final void finishHeavyWeightApp() {
3561         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3562                 != PackageManager.PERMISSION_GRANTED) {
3563             String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3564                     + Binder.getCallingPid()
3565                     + ", uid=" + Binder.getCallingUid()
3566                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3567             Slog.w(TAG, msg);
3568             throw new SecurityException(msg);
3569         }
3570         mAtmInternal.finishHeavyWeightApp();
3571     }
3572 
3573     @Override
crashApplication(int uid, int initialPid, String packageName, int userId, String message, boolean force)3574     public void crashApplication(int uid, int initialPid, String packageName, int userId,
3575             String message, boolean force) {
3576         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3577                 != PackageManager.PERMISSION_GRANTED) {
3578             String msg = "Permission Denial: crashApplication() from pid="
3579                     + Binder.getCallingPid()
3580                     + ", uid=" + Binder.getCallingUid()
3581                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3582             Slog.w(TAG, msg);
3583             throw new SecurityException(msg);
3584         }
3585 
3586         synchronized(this) {
3587             mAppErrors.scheduleAppCrashLocked(uid, initialPid, packageName, userId,
3588                     message, force);
3589         }
3590     }
3591 
3592     /**
3593      * Main function for removing an existing process from the activity manager
3594      * as a result of that process going away.  Clears out all connections
3595      * to the process.
3596      */
3597     @GuardedBy("this")
handleAppDiedLocked(ProcessRecord app, boolean restarting, boolean allowRestart)3598     final void handleAppDiedLocked(ProcessRecord app,
3599             boolean restarting, boolean allowRestart) {
3600         int pid = app.pid;
3601         boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1,
3602                 false /*replacingPid*/);
3603         if (!kept && !restarting) {
3604             removeLruProcessLocked(app);
3605             if (pid > 0) {
3606                 ProcessList.remove(pid);
3607             }
3608         }
3609 
3610         if (mProfileData.getProfileProc() == app) {
3611             clearProfilerLocked();
3612         }
3613 
3614         mAtmInternal.handleAppDied(app.getWindowProcessController(), restarting, () -> {
3615             Slog.w(TAG, "Crash of app " + app.processName
3616                     + " running instrumentation " + app.getActiveInstrumentation().mClass);
3617             Bundle info = new Bundle();
3618             info.putString("shortMsg", "Process crashed.");
3619             finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3620         });
3621     }
3622 
getRecordForAppLocked(IApplicationThread thread)3623     ProcessRecord getRecordForAppLocked(IApplicationThread thread) {
3624         if (thread == null) {
3625             return null;
3626         }
3627 
3628         ProcessRecord record = mProcessList.getLRURecordForAppLocked(thread);
3629         if (record != null) return record;
3630 
3631         // Validation: if it isn't in the LRU list, it shouldn't exist, but let's
3632         // double-check that.
3633         final IBinder threadBinder = thread.asBinder();
3634         final ArrayMap<String, SparseArray<ProcessRecord>> pmap =
3635                 mProcessList.mProcessNames.getMap();
3636         for (int i = pmap.size()-1; i >= 0; i--) {
3637             final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
3638             for (int j = procs.size()-1; j >= 0; j--) {
3639                 final ProcessRecord proc = procs.valueAt(j);
3640                 if (proc.thread != null && proc.thread.asBinder() == threadBinder) {
3641                     Slog.wtf(TAG, "getRecordForApp: exists in name list but not in LRU list: "
3642                             + proc);
3643                     return proc;
3644                 }
3645             }
3646         }
3647 
3648         return null;
3649     }
3650 
doLowMemReportIfNeededLocked(ProcessRecord dyingProc)3651     final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
3652         // If there are no longer any background processes running,
3653         // and the app that died was not running instrumentation,
3654         // then tell everyone we are now low on memory.
3655         if (!mProcessList.haveBackgroundProcessLocked()) {
3656             boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
3657             if (doReport) {
3658                 long now = SystemClock.uptimeMillis();
3659                 if (now < (mLastMemUsageReportTime+5*60*1000)) {
3660                     doReport = false;
3661                 } else {
3662                     mLastMemUsageReportTime = now;
3663                 }
3664             }
3665             final ArrayList<ProcessMemInfo> memInfos
3666                     = doReport ? new ArrayList<ProcessMemInfo>(mProcessList.getLruSizeLocked())
3667                     : null;
3668             EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mProcessList.getLruSizeLocked());
3669             long now = SystemClock.uptimeMillis();
3670             for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; i--) {
3671                 ProcessRecord rec = mProcessList.mLruProcesses.get(i);
3672                 if (rec == dyingProc || rec.thread == null) {
3673                     continue;
3674                 }
3675                 if (doReport) {
3676                     memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
3677                             rec.setProcState, rec.adjType, rec.makeAdjReason()));
3678                 }
3679                 if ((rec.lastLowMemory+mConstants.GC_MIN_INTERVAL) <= now) {
3680                     // The low memory report is overriding any current
3681                     // state for a GC request.  Make sure to do
3682                     // heavy/important/visible/foreground processes first.
3683                     if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
3684                         rec.lastRequestedGc = 0;
3685                     } else {
3686                         rec.lastRequestedGc = rec.lastLowMemory;
3687                     }
3688                     rec.reportLowMemory = true;
3689                     rec.lastLowMemory = now;
3690                     mProcessesToGc.remove(rec);
3691                     addProcessToGcListLocked(rec);
3692                 }
3693             }
3694             if (doReport) {
3695                 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
3696                 mHandler.sendMessage(msg);
3697             }
3698             scheduleAppGcsLocked();
3699         }
3700     }
3701 
3702     @GuardedBy("this")
appDiedLocked(ProcessRecord app)3703     final void appDiedLocked(ProcessRecord app) {
3704        appDiedLocked(app, app.pid, app.thread, false);
3705     }
3706 
3707     @GuardedBy("this")
appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied)3708     final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread,
3709             boolean fromBinderDied) {
3710         // First check if this ProcessRecord is actually active for the pid.
3711         synchronized (mPidsSelfLocked) {
3712             ProcessRecord curProc = mPidsSelfLocked.get(pid);
3713             if (curProc != app) {
3714                 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc);
3715                 return;
3716             }
3717         }
3718 
3719         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3720         synchronized (stats) {
3721             stats.noteProcessDiedLocked(app.info.uid, pid);
3722         }
3723 
3724         if (!app.killed) {
3725             if (!fromBinderDied) {
3726                 killProcessQuiet(pid);
3727             }
3728             ProcessList.killProcessGroup(app.uid, pid);
3729             app.killed = true;
3730         }
3731 
3732         // Clean up already done if the process has been re-started.
3733         if (app.pid == pid && app.thread != null &&
3734                 app.thread.asBinder() == thread.asBinder()) {
3735             boolean doLowMem = app.getActiveInstrumentation() == null;
3736             boolean doOomAdj = doLowMem;
3737             if (!app.killedByAm) {
3738                 reportUidInfoMessageLocked(TAG,
3739                         "Process " + app.processName + " (pid " + pid + ") has died: "
3740                                 + ProcessList.makeOomAdjString(app.setAdj, true) + " "
3741                                 + ProcessList.makeProcStateString(app.setProcState), app.info.uid);
3742                 mAllowLowerMemLevel = true;
3743             } else {
3744                 // Note that we always want to do oom adj to update our state with the
3745                 // new number of procs.
3746                 mAllowLowerMemLevel = false;
3747                 doLowMem = false;
3748             }
3749             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName,
3750                     app.setAdj, app.setProcState);
3751             if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
3752                 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder());
3753             handleAppDiedLocked(app, false, true);
3754 
3755             if (doOomAdj) {
3756                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
3757             }
3758             if (doLowMem) {
3759                 doLowMemReportIfNeededLocked(app);
3760             }
3761         } else if (app.pid != pid) {
3762             // A new process has already been started.
3763             reportUidInfoMessageLocked(TAG,
3764                     "Process " + app.processName + " (pid " + pid
3765                             + ") has died and restarted (pid " + app.pid + ").", app.info.uid);
3766             EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
3767         } else if (DEBUG_PROCESSES) {
3768             Slog.d(TAG_PROCESSES, "Received spurious death notification for thread "
3769                     + thread.asBinder());
3770         }
3771 
3772         // On the device which doesn't have Cgroup, log LmkStateChanged which is used as a signal
3773         // for pulling memory stats of other running processes when this process died.
3774         if (!hasMemcg()) {
3775             StatsLog.write(StatsLog.APP_DIED, SystemClock.elapsedRealtime());
3776         }
3777     }
3778 
3779     /**
3780      * If a stack trace dump file is configured, dump process stack traces.
3781      * @param firstPids of dalvik VM processes to dump stack traces for first
3782      * @param lastPids of dalvik VM processes to dump stack traces for last
3783      * @param nativePids optional list of native pids to dump stack crawls
3784      */
dumpStackTraces(ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, ArrayList<Integer> nativePids)3785     public static File dumpStackTraces(ArrayList<Integer> firstPids,
3786             ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids,
3787             ArrayList<Integer> nativePids) {
3788         ArrayList<Integer> extraPids = null;
3789 
3790         Slog.i(TAG, "dumpStackTraces pids=" + lastPids + " nativepids=" + nativePids);
3791 
3792         // Measure CPU usage as soon as we're called in order to get a realistic sampling
3793         // of the top users at the time of the request.
3794         if (processCpuTracker != null) {
3795             processCpuTracker.init();
3796             try {
3797                 Thread.sleep(200);
3798             } catch (InterruptedException ignored) {
3799             }
3800 
3801             processCpuTracker.update();
3802 
3803             // We'll take the stack crawls of just the top apps using CPU.
3804             final int N = processCpuTracker.countWorkingStats();
3805             extraPids = new ArrayList<>();
3806             for (int i = 0; i < N && extraPids.size() < 5; i++) {
3807                 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
3808                 if (lastPids.indexOfKey(stats.pid) >= 0) {
3809                     if (DEBUG_ANR) Slog.d(TAG, "Collecting stacks for extra pid " + stats.pid);
3810 
3811                     extraPids.add(stats.pid);
3812                 } else {
3813                     Slog.i(TAG, "Skipping next CPU consuming process, not a java proc: "
3814                             + stats.pid);
3815                 }
3816             }
3817         }
3818 
3819         final File tracesDir = new File(ANR_TRACE_DIR);
3820         // Each set of ANR traces is written to a separate file and dumpstate will process
3821         // all such files and add them to a captured bug report if they're recent enough.
3822         maybePruneOldTraces(tracesDir);
3823 
3824         // NOTE: We should consider creating the file in native code atomically once we've
3825         // gotten rid of the old scheme of dumping and lot of the code that deals with paths
3826         // can be removed.
3827         File tracesFile = createAnrDumpFile(tracesDir);
3828         if (tracesFile == null) {
3829             return null;
3830         }
3831 
3832         dumpStackTraces(tracesFile.getAbsolutePath(), firstPids, nativePids, extraPids);
3833         return tracesFile;
3834     }
3835 
3836     @GuardedBy("ActivityManagerService.class")
3837     private static SimpleDateFormat sAnrFileDateFormat;
3838 
createAnrDumpFile(File tracesDir)3839     private static synchronized File createAnrDumpFile(File tracesDir) {
3840         if (sAnrFileDateFormat == null) {
3841             sAnrFileDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
3842         }
3843 
3844         final String formattedDate = sAnrFileDateFormat.format(new Date());
3845         final File anrFile = new File(tracesDir, "anr_" + formattedDate);
3846 
3847         try {
3848             if (anrFile.createNewFile()) {
3849                 FileUtils.setPermissions(anrFile.getAbsolutePath(), 0600, -1, -1); // -rw-------
3850                 return anrFile;
3851             } else {
3852                 Slog.w(TAG, "Unable to create ANR dump file: createNewFile failed");
3853             }
3854         } catch (IOException ioe) {
3855             Slog.w(TAG, "Exception creating ANR dump file:", ioe);
3856         }
3857 
3858         return null;
3859     }
3860 
3861     /**
3862      * Prune all trace files that are more than a day old.
3863      *
3864      * NOTE: It might make sense to move this functionality to tombstoned eventually, along with a
3865      * shift away from anr_XX and tombstone_XX to a more descriptive name. We do it here for now
3866      * since it's the system_server that creates trace files for most ANRs.
3867      */
maybePruneOldTraces(File tracesDir)3868     private static void maybePruneOldTraces(File tracesDir) {
3869         final File[] files = tracesDir.listFiles();
3870         if (files == null) return;
3871 
3872         final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64);
3873         final long now = System.currentTimeMillis();
3874         Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
3875         for (int i = 0; i < files.length; ++i) {
3876             if (i > max || (now - files[i].lastModified()) > DAY_IN_MILLIS) {
3877                 if (!files[i].delete()) {
3878                     Slog.w(TAG, "Unable to prune stale trace file: " + files[i]);
3879                 }
3880             }
3881         }
3882     }
3883 
3884     /**
3885      * Dump java traces for process {@code pid} to the specified file. If java trace dumping
3886      * fails, a native backtrace is attempted. Note that the timeout {@code timeoutMs} only applies
3887      * to the java section of the trace, a further {@code NATIVE_DUMP_TIMEOUT_MS} might be spent
3888      * attempting to obtain native traces in the case of a failure. Returns the total time spent
3889      * capturing traces.
3890      */
dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs)3891     private static long dumpJavaTracesTombstoned(int pid, String fileName, long timeoutMs) {
3892         final long timeStart = SystemClock.elapsedRealtime();
3893         boolean javaSuccess = Debug.dumpJavaBacktraceToFileTimeout(pid, fileName,
3894                 (int) (timeoutMs / 1000));
3895         if (javaSuccess) {
3896             // Check that something is in the file, actually. Try-catch should not be necessary,
3897             // but better safe than sorry.
3898             try {
3899                 long size = new File(fileName).length();
3900                 if (size < JAVA_DUMP_MINIMUM_SIZE) {
3901                     Slog.w(TAG, "Successfully created Java ANR file is empty!");
3902                     javaSuccess = false;
3903                 }
3904             } catch (Exception e) {
3905                 Slog.w(TAG, "Unable to get ANR file size", e);
3906                 javaSuccess = false;
3907             }
3908         }
3909         if (!javaSuccess) {
3910             Slog.w(TAG, "Dumping Java threads failed, initiating native stack dump.");
3911             if (!Debug.dumpNativeBacktraceToFileTimeout(pid, fileName,
3912                     (NATIVE_DUMP_TIMEOUT_MS / 1000))) {
3913                 Slog.w(TAG, "Native stack dump failed!");
3914             }
3915         }
3916 
3917         return SystemClock.elapsedRealtime() - timeStart;
3918     }
3919 
dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids, ArrayList<Integer> nativePids, ArrayList<Integer> extraPids)3920     public static void dumpStackTraces(String tracesFile, ArrayList<Integer> firstPids,
3921             ArrayList<Integer> nativePids, ArrayList<Integer> extraPids) {
3922 
3923         Slog.i(TAG, "Dumping to " + tracesFile);
3924 
3925         // We don't need any sort of inotify based monitoring when we're dumping traces via
3926         // tombstoned. Data is piped to an "intercept" FD installed in tombstoned so we're in full
3927         // control of all writes to the file in question.
3928 
3929         // We must complete all stack dumps within 20 seconds.
3930         long remainingTime = 20 * 1000;
3931 
3932         // First collect all of the stacks of the most important pids.
3933         if (firstPids != null) {
3934             int num = firstPids.size();
3935             for (int i = 0; i < num; i++) {
3936                 Slog.i(TAG, "Collecting stacks for pid " + firstPids.get(i));
3937                 final long timeTaken = dumpJavaTracesTombstoned(firstPids.get(i), tracesFile,
3938                                                                 remainingTime);
3939 
3940                 remainingTime -= timeTaken;
3941                 if (remainingTime <= 0) {
3942                     Slog.e(TAG, "Aborting stack trace dump (current firstPid=" + firstPids.get(i) +
3943                            "); deadline exceeded.");
3944                     return;
3945                 }
3946 
3947                 if (DEBUG_ANR) {
3948                     Slog.d(TAG, "Done with pid " + firstPids.get(i) + " in " + timeTaken + "ms");
3949                 }
3950             }
3951         }
3952 
3953         // Next collect the stacks of the native pids
3954         if (nativePids != null) {
3955             for (int pid : nativePids) {
3956                 Slog.i(TAG, "Collecting stacks for native pid " + pid);
3957                 final long nativeDumpTimeoutMs = Math.min(NATIVE_DUMP_TIMEOUT_MS, remainingTime);
3958 
3959                 final long start = SystemClock.elapsedRealtime();
3960                 Debug.dumpNativeBacktraceToFileTimeout(
3961                         pid, tracesFile, (int) (nativeDumpTimeoutMs / 1000));
3962                 final long timeTaken = SystemClock.elapsedRealtime() - start;
3963 
3964                 remainingTime -= timeTaken;
3965                 if (remainingTime <= 0) {
3966                     Slog.e(TAG, "Aborting stack trace dump (current native pid=" + pid +
3967                         "); deadline exceeded.");
3968                     return;
3969                 }
3970 
3971                 if (DEBUG_ANR) {
3972                     Slog.d(TAG, "Done with native pid " + pid + " in " + timeTaken + "ms");
3973                 }
3974             }
3975         }
3976 
3977         // Lastly, dump stacks for all extra PIDs from the CPU tracker.
3978         if (extraPids != null) {
3979             for (int pid : extraPids) {
3980                 Slog.i(TAG, "Collecting stacks for extra pid " + pid);
3981 
3982                 final long timeTaken = dumpJavaTracesTombstoned(pid, tracesFile, remainingTime);
3983 
3984                 remainingTime -= timeTaken;
3985                 if (remainingTime <= 0) {
3986                     Slog.e(TAG, "Aborting stack trace dump (current extra pid=" + pid +
3987                             "); deadline exceeded.");
3988                     return;
3989                 }
3990 
3991                 if (DEBUG_ANR) {
3992                     Slog.d(TAG, "Done with extra pid " + pid + " in " + timeTaken + "ms");
3993                 }
3994             }
3995         }
3996         Slog.i(TAG, "Done dumping");
3997     }
3998 
3999     @Override
clearApplicationUserData(final String packageName, boolean keepState, final IPackageDataObserver observer, int userId)4000     public boolean clearApplicationUserData(final String packageName, boolean keepState,
4001             final IPackageDataObserver observer, int userId) {
4002         enforceNotIsolatedCaller("clearApplicationUserData");
4003         int uid = Binder.getCallingUid();
4004         int pid = Binder.getCallingPid();
4005         final int resolvedUserId = mUserController.handleIncomingUser(pid, uid, userId, false,
4006                 ALLOW_FULL_ONLY, "clearApplicationUserData", null);
4007 
4008         final ApplicationInfo appInfo;
4009         final boolean isInstantApp;
4010 
4011         long callingId = Binder.clearCallingIdentity();
4012         try {
4013             IPackageManager pm = AppGlobals.getPackageManager();
4014             synchronized(this) {
4015                 // Instant packages are not protected
4016                 if (getPackageManagerInternalLocked().isPackageDataProtected(
4017                         resolvedUserId, packageName)) {
4018                     throw new SecurityException(
4019                             "Cannot clear data for a protected package: " + packageName);
4020                 }
4021 
4022                 ApplicationInfo applicationInfo = null;
4023                 try {
4024                     applicationInfo = pm.getApplicationInfo(packageName,
4025                             MATCH_UNINSTALLED_PACKAGES, resolvedUserId);
4026                 } catch (RemoteException e) {
4027                     /* ignore */
4028                 }
4029                 appInfo = applicationInfo;
4030 
4031                 final boolean clearingOwnUidData = appInfo != null && appInfo.uid == uid;
4032 
4033                 if (!clearingOwnUidData && checkComponentPermission(permission.CLEAR_APP_USER_DATA,
4034                         pid, uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
4035                     throw new SecurityException("PID " + pid + " does not have permission "
4036                             + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
4037                             + " of package " + packageName);
4038                 }
4039 
4040                 final boolean hasInstantMetadata = getPackageManagerInternalLocked()
4041                         .hasInstantApplicationMetadata(packageName, resolvedUserId);
4042                 final boolean isUninstalledAppWithoutInstantMetadata =
4043                         (appInfo == null && !hasInstantMetadata);
4044                 isInstantApp = (appInfo != null && appInfo.isInstantApp())
4045                         || hasInstantMetadata;
4046                 final boolean canAccessInstantApps = checkComponentPermission(
4047                         permission.ACCESS_INSTANT_APPS, pid, uid, -1, true)
4048                         == PackageManager.PERMISSION_GRANTED;
4049 
4050                 if (isUninstalledAppWithoutInstantMetadata || (isInstantApp
4051                         && !canAccessInstantApps)) {
4052                     Slog.w(TAG, "Invalid packageName: " + packageName);
4053                     if (observer != null) {
4054                         try {
4055                             observer.onRemoveCompleted(packageName, false);
4056                         } catch (RemoteException e) {
4057                             Slog.i(TAG, "Observer no longer exists.");
4058                         }
4059                     }
4060                     return false;
4061                 }
4062 
4063                 if (appInfo != null) {
4064                     forceStopPackageLocked(packageName, appInfo.uid, "clear data");
4065                     mAtmInternal.removeRecentTasksByPackageName(packageName, resolvedUserId);
4066                 }
4067             }
4068 
4069             final IPackageDataObserver localObserver = new IPackageDataObserver.Stub() {
4070                 @Override
4071                 public void onRemoveCompleted(String packageName, boolean succeeded)
4072                         throws RemoteException {
4073                     if (appInfo != null) {
4074                         synchronized (ActivityManagerService.this) {
4075                             finishForceStopPackageLocked(packageName, appInfo.uid);
4076                         }
4077                     }
4078                     final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4079                             Uri.fromParts("package", packageName, null));
4080                     intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
4081                     intent.putExtra(Intent.EXTRA_UID, (appInfo != null) ? appInfo.uid : -1);
4082                     intent.putExtra(Intent.EXTRA_USER_HANDLE, resolvedUserId);
4083                     if (isInstantApp) {
4084                         intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
4085                         broadcastIntentInPackage("android", SYSTEM_UID, uid, pid, intent, null,
4086                                 null, 0, null, null, permission.ACCESS_INSTANT_APPS, null, false,
4087                                 false, resolvedUserId, false);
4088                     } else {
4089                         broadcastIntentInPackage("android", SYSTEM_UID, uid, pid, intent, null,
4090                                 null, 0, null, null, null, null, false, false, resolvedUserId,
4091                                 false);
4092                     }
4093 
4094                     if (observer != null) {
4095                         observer.onRemoveCompleted(packageName, succeeded);
4096                     }
4097                 }
4098             };
4099 
4100             try {
4101                 // Clear application user data
4102                 pm.clearApplicationUserData(packageName, localObserver, resolvedUserId);
4103 
4104                 if (appInfo != null) {
4105                     // Restore already established notification state and permission grants,
4106                     // so it told us to keep those intact -- it's about to emplace app data
4107                     // that is appropriate for those bits of system state.
4108                     if (!keepState) {
4109                         // Remove all permissions granted from/to this package
4110                         mUgmInternal.removeUriPermissionsForPackage(packageName, resolvedUserId,
4111                                 true, false);
4112 
4113                         // Reset notification state
4114                         INotificationManager inm = NotificationManager.getService();
4115                         inm.clearData(packageName, appInfo.uid, uid == appInfo.uid);
4116                     }
4117 
4118                     // Clear its scheduled jobs
4119                     JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
4120                     js.cancelJobsForUid(appInfo.uid, "clear data");
4121 
4122                     // Clear its pending alarms
4123                     AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class);
4124                     ami.removeAlarmsForUid(appInfo.uid);
4125                 }
4126             } catch (RemoteException e) {
4127             }
4128         } finally {
4129             Binder.restoreCallingIdentity(callingId);
4130         }
4131         return true;
4132     }
4133 
4134     @Override
killBackgroundProcesses(final String packageName, int userId)4135     public void killBackgroundProcesses(final String packageName, int userId) {
4136         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4137                 != PackageManager.PERMISSION_GRANTED &&
4138                 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4139                         != PackageManager.PERMISSION_GRANTED) {
4140             String msg = "Permission Denial: killBackgroundProcesses() from pid="
4141                     + Binder.getCallingPid()
4142                     + ", uid=" + Binder.getCallingUid()
4143                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4144             Slog.w(TAG, msg);
4145             throw new SecurityException(msg);
4146         }
4147 
4148         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4149                 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
4150         final int[] userIds = mUserController.expandUserId(userId);
4151 
4152         long callingId = Binder.clearCallingIdentity();
4153         try {
4154             IPackageManager pm = AppGlobals.getPackageManager();
4155             for (int targetUserId : userIds) {
4156                 int appId = -1;
4157                 try {
4158                     appId = UserHandle.getAppId(
4159                             pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
4160                                     targetUserId));
4161                 } catch (RemoteException e) {
4162                 }
4163                 if (appId == -1) {
4164                     Slog.w(TAG, "Invalid packageName: " + packageName);
4165                     return;
4166                 }
4167                 synchronized (this) {
4168                     mProcessList.killPackageProcessesLocked(packageName, appId, targetUserId,
4169                             ProcessList.SERVICE_ADJ, "kill background");
4170                 }
4171             }
4172         } finally {
4173             Binder.restoreCallingIdentity(callingId);
4174         }
4175     }
4176 
4177     @Override
killAllBackgroundProcesses()4178     public void killAllBackgroundProcesses() {
4179         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4180                 != PackageManager.PERMISSION_GRANTED) {
4181             final String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4182                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4183                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4184             Slog.w(TAG, msg);
4185             throw new SecurityException(msg);
4186         }
4187 
4188         final long callingId = Binder.clearCallingIdentity();
4189         try {
4190             synchronized (this) {
4191                 // Allow memory level to go down (the flag needs to be set before updating oom adj)
4192                 // because this method is also used to simulate low memory.
4193                 mAllowLowerMemLevel = true;
4194                 mProcessList.killPackageProcessesLocked(null /* packageName */, -1 /* appId */,
4195                         UserHandle.USER_ALL, ProcessList.CACHED_APP_MIN_ADJ, "kill all background");
4196 
4197                 doLowMemReportIfNeededLocked(null);
4198             }
4199         } finally {
4200             Binder.restoreCallingIdentity(callingId);
4201         }
4202     }
4203 
4204     /**
4205      * Kills all background processes, except those matching any of the
4206      * specified properties.
4207      *
4208      * @param minTargetSdk the target SDK version at or above which to preserve
4209      *                     processes, or {@code -1} to ignore the target SDK
4210      * @param maxProcState the process state at or below which to preserve
4211      *                     processes, or {@code -1} to ignore the process state
4212      */
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)4213     void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
4214         if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4215                 != PackageManager.PERMISSION_GRANTED) {
4216             final String msg = "Permission Denial: killAllBackgroundProcessesExcept() from pid="
4217                     + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4218                     + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4219             Slog.w(TAG, msg);
4220             throw new SecurityException(msg);
4221         }
4222 
4223         final long callingId = Binder.clearCallingIdentity();
4224         try {
4225             synchronized (this) {
4226                 mProcessList.killAllBackgroundProcessesExceptLocked(minTargetSdk, maxProcState);
4227             }
4228         } finally {
4229             Binder.restoreCallingIdentity(callingId);
4230         }
4231     }
4232 
4233     @Override
forceStopPackage(final String packageName, int userId)4234     public void forceStopPackage(final String packageName, int userId) {
4235         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4236                 != PackageManager.PERMISSION_GRANTED) {
4237             String msg = "Permission Denial: forceStopPackage() from pid="
4238                     + Binder.getCallingPid()
4239                     + ", uid=" + Binder.getCallingUid()
4240                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4241             Slog.w(TAG, msg);
4242             throw new SecurityException(msg);
4243         }
4244         final int callingPid = Binder.getCallingPid();
4245         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
4246                 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
4247         long callingId = Binder.clearCallingIdentity();
4248         try {
4249             IPackageManager pm = AppGlobals.getPackageManager();
4250             synchronized(this) {
4251                 int[] users = userId == UserHandle.USER_ALL
4252                         ? mUserController.getUsers() : new int[] { userId };
4253                 for (int user : users) {
4254                     if (getPackageManagerInternalLocked().isPackageStateProtected(
4255                             packageName, user)) {
4256                         Slog.w(TAG, "Ignoring request to force stop protected package "
4257                                 + packageName + " u" + user);
4258                         return;
4259                     }
4260 
4261                     int pkgUid = -1;
4262                     try {
4263                         pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
4264                                 user);
4265                     } catch (RemoteException e) {
4266                     }
4267                     if (pkgUid == -1) {
4268                         Slog.w(TAG, "Invalid packageName: " + packageName);
4269                         continue;
4270                     }
4271                     try {
4272                         pm.setPackageStoppedState(packageName, true, user);
4273                     } catch (RemoteException e) {
4274                     } catch (IllegalArgumentException e) {
4275                         Slog.w(TAG, "Failed trying to unstop package "
4276                                 + packageName + ": " + e);
4277                     }
4278                     if (mUserController.isUserRunning(user, 0)) {
4279                         forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
4280                         finishForceStopPackageLocked(packageName, pkgUid);
4281                     }
4282                 }
4283             }
4284         } finally {
4285             Binder.restoreCallingIdentity(callingId);
4286         }
4287     }
4288 
4289     @Override
addPackageDependency(String packageName)4290     public void addPackageDependency(String packageName) {
4291         synchronized (this) {
4292             int callingPid = Binder.getCallingPid();
4293             if (callingPid == myPid()) {
4294                 //  Yeah, um, no.
4295                 return;
4296             }
4297             ProcessRecord proc;
4298             synchronized (mPidsSelfLocked) {
4299                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
4300             }
4301             if (proc != null) {
4302                 if (proc.pkgDeps == null) {
4303                     proc.pkgDeps = new ArraySet<String>(1);
4304                 }
4305                 proc.pkgDeps.add(packageName);
4306             }
4307         }
4308     }
4309 
4310     /*
4311      * The pkg name and app id have to be specified.
4312      */
4313     @Override
killApplication(String pkg, int appId, int userId, String reason)4314     public void killApplication(String pkg, int appId, int userId, String reason) {
4315         if (pkg == null) {
4316             return;
4317         }
4318         // Make sure the uid is valid.
4319         if (appId < 0) {
4320             Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
4321             return;
4322         }
4323         int callerUid = Binder.getCallingUid();
4324         // Only the system server can kill an application
4325         if (UserHandle.getAppId(callerUid) == SYSTEM_UID) {
4326             // Post an aysnc message to kill the application
4327             Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4328             msg.arg1 = appId;
4329             msg.arg2 = userId;
4330             Bundle bundle = new Bundle();
4331             bundle.putString("pkg", pkg);
4332             bundle.putString("reason", reason);
4333             msg.obj = bundle;
4334             mHandler.sendMessage(msg);
4335         } else {
4336             throw new SecurityException(callerUid + " cannot kill pkg: " +
4337                     pkg);
4338         }
4339     }
4340 
4341     @Override
closeSystemDialogs(String reason)4342     public void closeSystemDialogs(String reason) {
4343         mAtmInternal.closeSystemDialogs(reason);
4344     }
4345 
4346     @Override
getProcessMemoryInfo(int[] pids)4347     public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
4348         enforceNotIsolatedCaller("getProcessMemoryInfo");
4349 
4350         final long now = SystemClock.uptimeMillis();
4351         final long lastNow = now - mConstants.MEMORY_INFO_THROTTLE_TIME;
4352 
4353         final int callingPid = Binder.getCallingPid();
4354         final int callingUid = Binder.getCallingUid();
4355         final int callingUserId = UserHandle.getUserId(callingUid);
4356         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4357                 callingUid) == PackageManager.PERMISSION_GRANTED;
4358         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4359         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4360                 "getProcessMemoryInfo", callingPid, callingUid);
4361 
4362         Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4363         for (int i=pids.length-1; i>=0; i--) {
4364             infos[i] = new Debug.MemoryInfo();
4365             final ProcessRecord proc;
4366             final int oomAdj;
4367             synchronized (this) {
4368                 synchronized (mPidsSelfLocked) {
4369                     proc = mPidsSelfLocked.get(pids[i]);
4370                     oomAdj = proc != null ? proc.setAdj : 0;
4371                 }
4372             }
4373             final int targetUid = (proc != null) ? proc.uid : -1;
4374             final int targetUserId = (proc != null) ? UserHandle.getUserId(targetUid) : -1;
4375 
4376             if (callingUid != targetUid) {
4377                 if (!allUids) {
4378                     continue; // Not allowed to see other UIDs.
4379                 }
4380 
4381                 if (!allUsers && (targetUserId != callingUserId)) {
4382                     continue; // Not allowed to see other users.
4383                 }
4384             }
4385             if (proc != null && proc.lastMemInfoTime >= lastNow && proc.lastMemInfo != null) {
4386                 // It hasn't been long enough that we want to take another sample; return
4387                 // the last one.
4388                 infos[i].set(proc.lastMemInfo);
4389                 continue;
4390             }
4391             final long startTime = SystemClock.currentThreadTimeMillis();
4392             final Debug.MemoryInfo memInfo = new Debug.MemoryInfo();
4393             Debug.getMemoryInfo(pids[i], memInfo);
4394             final long endTime = SystemClock.currentThreadTimeMillis();
4395             infos[i].set(memInfo);
4396             if (proc != null) {
4397                 synchronized (this) {
4398                     proc.lastMemInfo = memInfo;
4399                     proc.lastMemInfoTime = SystemClock.uptimeMillis();
4400                     if (proc.thread != null && proc.setAdj == oomAdj) {
4401                         // Record this for posterity if the process has been stable.
4402                         proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
4403                                 infos[i].getTotalUss(), infos[i].getTotalRss(), false,
4404                                 ProcessStats.ADD_PSS_EXTERNAL_SLOW, endTime - startTime,
4405                                 proc.pkgList.mPkgList);
4406                         for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) {
4407                             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
4408                             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
4409                                     proc.info.uid,
4410                                     holder.state.getName(),
4411                                     holder.state.getPackage(),
4412                                     infos[i].getTotalPss(),
4413                                     infos[i].getTotalUss(),
4414                                     infos[i].getTotalRss(),
4415                                     ProcessStats.ADD_PSS_EXTERNAL_SLOW,
4416                                     endTime-startTime,
4417                                     holder.appVersion);
4418                         }
4419                     }
4420                 }
4421             }
4422         }
4423         return infos;
4424     }
4425 
4426     @Override
getProcessPss(int[] pids)4427     public long[] getProcessPss(int[] pids) {
4428         enforceNotIsolatedCaller("getProcessPss");
4429 
4430         final int callingPid = Binder.getCallingPid();
4431         final int callingUid = Binder.getCallingUid();
4432         final int userId = UserHandle.getUserId(callingUid);
4433         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
4434                 callingUid) == PackageManager.PERMISSION_GRANTED;
4435         // Check REAL_GET_TASKS to see if they are allowed to access other uids
4436         final boolean allUids = mAtmInternal.isGetTasksAllowed(
4437                 "getProcessPss", callingPid, callingUid);
4438 
4439         long[] pss = new long[pids.length];
4440         for (int i=pids.length-1; i>=0; i--) {
4441             ProcessRecord proc;
4442             int oomAdj;
4443             synchronized (this) {
4444                 synchronized (mPidsSelfLocked) {
4445                     proc = mPidsSelfLocked.get(pids[i]);
4446                     oomAdj = proc != null ? proc.setAdj : 0;
4447                 }
4448             }
4449             if (!allUids || (!allUsers && UserHandle.getUserId(proc.uid) != userId)) {
4450                 // The caller is not allow to get information about this other process...
4451                 // just leave it empty.
4452                 continue;
4453             }
4454             long[] tmpUss = new long[3];
4455             long startTime = SystemClock.currentThreadTimeMillis();
4456             pss[i] = Debug.getPss(pids[i], tmpUss, null);
4457             long endTime = SystemClock.currentThreadTimeMillis();
4458             if (proc != null) {
4459                 synchronized (this) {
4460                     if (proc.thread != null && proc.setAdj == oomAdj) {
4461                         // Record this for posterity if the process has been stable.
4462                         proc.baseProcessTracker.addPss(pss[i], tmpUss[0], tmpUss[2], false,
4463                                 ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime, proc.pkgList.mPkgList);
4464                         for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) {
4465                             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
4466                             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
4467                                     proc.info.uid,
4468                                     holder.state.getName(),
4469                                     holder.state.getPackage(),
4470                                     pss[i], tmpUss[0], tmpUss[2],
4471                                     ProcessStats.ADD_PSS_EXTERNAL, endTime-startTime,
4472                                     holder.appVersion);
4473                         }
4474                     }
4475                 }
4476             }
4477         }
4478         return pss;
4479     }
4480 
4481     @Override
killApplicationProcess(String processName, int uid)4482     public void killApplicationProcess(String processName, int uid) {
4483         if (processName == null) {
4484             return;
4485         }
4486 
4487         int callerUid = Binder.getCallingUid();
4488         // Only the system server can kill an application
4489         if (callerUid == SYSTEM_UID) {
4490             synchronized (this) {
4491                 ProcessRecord app = getProcessRecordLocked(processName, uid, true);
4492                 if (app != null && app.thread != null) {
4493                     try {
4494                         app.thread.scheduleSuicide();
4495                     } catch (RemoteException e) {
4496                         // If the other end already died, then our work here is done.
4497                     }
4498                 } else {
4499                     Slog.w(TAG, "Process/uid not found attempting kill of "
4500                             + processName + " / " + uid);
4501                 }
4502             }
4503         } else {
4504             throw new SecurityException(callerUid + " cannot kill app process: " +
4505                     processName);
4506         }
4507     }
4508 
4509     @GuardedBy("this")
forceStopPackageLocked(final String packageName, int uid, String reason)4510     private void forceStopPackageLocked(final String packageName, int uid, String reason) {
4511         forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
4512                 false, true, false, false, UserHandle.getUserId(uid), reason);
4513     }
4514 
4515     @GuardedBy("this")
finishForceStopPackageLocked(final String packageName, int uid)4516     private void finishForceStopPackageLocked(final String packageName, int uid) {
4517         Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
4518                 Uri.fromParts("package", packageName, null));
4519         if (!mProcessesReady) {
4520             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4521                     | Intent.FLAG_RECEIVER_FOREGROUND);
4522         }
4523         intent.putExtra(Intent.EXTRA_UID, uid);
4524         intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
4525         broadcastIntentLocked(null, null, intent,
4526                 null, null, 0, null, null, null, OP_NONE,
4527                 null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
4528                 Binder.getCallingPid(), UserHandle.getUserId(uid));
4529     }
4530 
cleanupDisabledPackageComponentsLocked( String packageName, int userId, String[] changedClasses)4531     private void cleanupDisabledPackageComponentsLocked(
4532             String packageName, int userId, String[] changedClasses) {
4533 
4534         Set<String> disabledClasses = null;
4535         boolean packageDisabled = false;
4536         IPackageManager pm = AppGlobals.getPackageManager();
4537 
4538         if (changedClasses == null) {
4539             // Nothing changed...
4540             return;
4541         }
4542 
4543         // Determine enable/disable state of the package and its components.
4544         int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4545         for (int i = changedClasses.length - 1; i >= 0; i--) {
4546             final String changedClass = changedClasses[i];
4547 
4548             if (changedClass.equals(packageName)) {
4549                 try {
4550                     // Entire package setting changed
4551                     enabled = pm.getApplicationEnabledSetting(packageName,
4552                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4553                 } catch (Exception e) {
4554                     // No such package/component; probably racing with uninstall.  In any
4555                     // event it means we have nothing further to do here.
4556                     return;
4557                 }
4558                 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4559                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
4560                 if (packageDisabled) {
4561                     // Entire package is disabled.
4562                     // No need to continue to check component states.
4563                     disabledClasses = null;
4564                     break;
4565                 }
4566             } else {
4567                 try {
4568                     enabled = pm.getComponentEnabledSetting(
4569                             new ComponentName(packageName, changedClass),
4570                             (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_SYSTEM);
4571                 } catch (Exception e) {
4572                     // As above, probably racing with uninstall.
4573                     return;
4574                 }
4575                 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED
4576                         && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
4577                     if (disabledClasses == null) {
4578                         disabledClasses = new ArraySet<>(changedClasses.length);
4579                     }
4580                     disabledClasses.add(changedClass);
4581                 }
4582             }
4583         }
4584 
4585         if (!packageDisabled && disabledClasses == null) {
4586             // Nothing to do here...
4587             return;
4588         }
4589 
4590         mAtmInternal.cleanupDisabledPackageComponents(
4591                 packageName, disabledClasses, userId, mBooted);
4592 
4593         // Clean-up disabled services.
4594         mServices.bringDownDisabledPackageServicesLocked(
4595                 packageName, disabledClasses, userId, false /* evenPersistent */, true /* doIt */);
4596 
4597         // Clean-up disabled providers.
4598         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4599         mProviderMap.collectPackageProvidersLocked(
4600                 packageName, disabledClasses, true, false, userId, providers);
4601         for (int i = providers.size() - 1; i >= 0; i--) {
4602             removeDyingProviderLocked(null, providers.get(i), true);
4603         }
4604 
4605         // Clean-up disabled broadcast receivers.
4606         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4607             mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4608                     packageName, disabledClasses, userId, true);
4609         }
4610 
4611     }
4612 
clearBroadcastQueueForUserLocked(int userId)4613     final boolean clearBroadcastQueueForUserLocked(int userId) {
4614         boolean didSomething = false;
4615         for (int i = mBroadcastQueues.length - 1; i >= 0; i--) {
4616             didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4617                     null, null, userId, true);
4618         }
4619         return didSomething;
4620     }
4621 
4622     @GuardedBy("this")
forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)4623     final boolean forceStopPackageLocked(String packageName, int appId,
4624             boolean callerWillRestart, boolean purgeCache, boolean doit,
4625             boolean evenPersistent, boolean uninstalling, int userId, String reason) {
4626         int i;
4627 
4628         if (userId == UserHandle.USER_ALL && packageName == null) {
4629             Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
4630         }
4631 
4632         if (appId < 0 && packageName != null) {
4633             try {
4634                 appId = UserHandle.getAppId(AppGlobals.getPackageManager()
4635                         .getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, 0));
4636             } catch (RemoteException e) {
4637             }
4638         }
4639 
4640         if (doit) {
4641             if (packageName != null) {
4642                 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId
4643                         + " user=" + userId + ": " + reason);
4644             } else {
4645                 Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
4646             }
4647 
4648             mAppErrors.resetProcessCrashTimeLocked(packageName == null, appId, userId);
4649         }
4650 
4651         boolean didSomething = mProcessList.killPackageProcessesLocked(packageName, appId, userId,
4652                 ProcessList.INVALID_ADJ, callerWillRestart, true /* allowRestart */, doit,
4653                 evenPersistent, true /* setRemoved */,
4654                 packageName == null ? ("stop user " + userId) : ("stop " + packageName));
4655 
4656         didSomething |=
4657                 mAtmInternal.onForceStopPackage(packageName, doit, evenPersistent, userId);
4658 
4659         if (mServices.bringDownDisabledPackageServicesLocked(
4660                 packageName, null /* filterByClasses */, userId, evenPersistent, doit)) {
4661             if (!doit) {
4662                 return true;
4663             }
4664             didSomething = true;
4665         }
4666 
4667         if (packageName == null) {
4668             // Remove all sticky broadcasts from this user.
4669             mStickyBroadcasts.remove(userId);
4670         }
4671 
4672         ArrayList<ContentProviderRecord> providers = new ArrayList<>();
4673         if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent,
4674                 userId, providers)) {
4675             if (!doit) {
4676                 return true;
4677             }
4678             didSomething = true;
4679         }
4680         for (i = providers.size() - 1; i >= 0; i--) {
4681             removeDyingProviderLocked(null, providers.get(i), true);
4682         }
4683 
4684         // Remove transient permissions granted from/to this package/user
4685         mUgmInternal.removeUriPermissionsForPackage(packageName, userId, false, false);
4686 
4687         if (doit) {
4688             for (i = mBroadcastQueues.length - 1; i >= 0; i--) {
4689                 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked(
4690                         packageName, null, userId, doit);
4691             }
4692         }
4693 
4694         if (packageName == null || uninstalling) {
4695             didSomething |= mPendingIntentController.removePendingIntentsForPackage(
4696                     packageName, userId, appId, doit);
4697         }
4698 
4699         if (doit) {
4700             if (purgeCache && packageName != null) {
4701                 AttributeCache ac = AttributeCache.instance();
4702                 if (ac != null) {
4703                     ac.removePackage(packageName);
4704                 }
4705             }
4706             if (mBooted) {
4707                 mAtmInternal.resumeTopActivities(true /* scheduleIdle */);
4708             }
4709         }
4710 
4711         return didSomething;
4712     }
4713 
4714     @GuardedBy("this")
processContentProviderPublishTimedOutLocked(ProcessRecord app)4715     private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) {
4716         cleanupAppInLaunchingProvidersLocked(app, true);
4717         mProcessList.removeProcessLocked(app, false, true, "timeout publishing content providers");
4718     }
4719 
4720     @GuardedBy("this")
processStartTimedOutLocked(ProcessRecord app)4721     private final void processStartTimedOutLocked(ProcessRecord app) {
4722         final int pid = app.pid;
4723         boolean gone = mPidsSelfLocked.removeIfNoThread(app);
4724 
4725         if (gone) {
4726             Slog.w(TAG, "Process " + app + " failed to attach");
4727             EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4728                     pid, app.uid, app.processName);
4729             mProcessList.removeProcessNameLocked(app.processName, app.uid);
4730             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
4731             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
4732             // Take care of any launching providers waiting for this process.
4733             cleanupAppInLaunchingProvidersLocked(app, true);
4734             // Take care of any services that are waiting for the process.
4735             mServices.processStartTimedOutLocked(app);
4736             app.kill("start timeout", true);
4737             if (app.isolated) {
4738                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
4739             }
4740             removeLruProcessLocked(app);
4741             final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4742             if (backupTarget != null && backupTarget.app.pid == pid) {
4743                 Slog.w(TAG, "Unattached app died before backup, skipping");
4744                 mHandler.post(new Runnable() {
4745                 @Override
4746                     public void run(){
4747                         try {
4748                             IBackupManager bm = IBackupManager.Stub.asInterface(
4749                                     ServiceManager.getService(Context.BACKUP_SERVICE));
4750                             bm.agentDisconnectedForUser(app.userId, app.info.packageName);
4751                         } catch (RemoteException e) {
4752                             // Can't happen; the backup manager is local
4753                         }
4754                     }
4755                 });
4756             }
4757             if (isPendingBroadcastProcessLocked(pid)) {
4758                 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
4759                 skipPendingBroadcastLocked(pid);
4760             }
4761         } else {
4762             Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
4763         }
4764     }
4765 
4766     @GuardedBy("this")
attachApplicationLocked(@onNull IApplicationThread thread, int pid, int callingUid, long startSeq)4767     private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
4768             int pid, int callingUid, long startSeq) {
4769 
4770         // Find the application record that is being attached...  either via
4771         // the pid if we are running in multiple processes, or just pull the
4772         // next app record if we are emulating process with anonymous threads.
4773         ProcessRecord app;
4774         long startTime = SystemClock.uptimeMillis();
4775         long bindApplicationTimeMillis;
4776         if (pid != MY_PID && pid >= 0) {
4777             synchronized (mPidsSelfLocked) {
4778                 app = mPidsSelfLocked.get(pid);
4779             }
4780             if (app != null && (app.startUid != callingUid || app.startSeq != startSeq)) {
4781                 String processName = null;
4782                 final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4783                 if (pending != null) {
4784                     processName = pending.processName;
4785                 }
4786                 final String msg = "attachApplicationLocked process:" + processName
4787                         + " startSeq:" + startSeq
4788                         + " pid:" + pid
4789                         + " belongs to another existing app:" + app.processName
4790                         + " startSeq:" + app.startSeq;
4791                 Slog.wtf(TAG, msg);
4792                 // SafetyNet logging for b/131105245.
4793                 EventLog.writeEvent(0x534e4554, "131105245", app.startUid, msg);
4794                 // If there is already an app occupying that pid that hasn't been cleaned up
4795                 cleanUpApplicationRecordLocked(app, false, false, -1,
4796                             true /*replacingPid*/);
4797                 mPidsSelfLocked.remove(app);
4798                 app = null;
4799             }
4800         } else {
4801             app = null;
4802         }
4803 
4804         // It's possible that process called attachApplication before we got a chance to
4805         // update the internal state.
4806         if (app == null && startSeq > 0) {
4807             final ProcessRecord pending = mProcessList.mPendingStarts.get(startSeq);
4808             if (pending != null && pending.startUid == callingUid && pending.startSeq == startSeq
4809                     && mProcessList.handleProcessStartedLocked(pending, pid, pending
4810                             .isUsingWrapper(),
4811                             startSeq, true)) {
4812                 app = pending;
4813             }
4814         }
4815 
4816         if (app == null) {
4817             Slog.w(TAG, "No pending application record for pid " + pid
4818                     + " (IApplicationThread " + thread + "); dropping process");
4819             EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
4820             if (pid > 0 && pid != MY_PID) {
4821                 killProcessQuiet(pid);
4822                 //TODO: killProcessGroup(app.info.uid, pid);
4823             } else {
4824                 try {
4825                     thread.scheduleExit();
4826                 } catch (Exception e) {
4827                     // Ignore exceptions.
4828                 }
4829             }
4830             return false;
4831         }
4832 
4833         // If this application record is still attached to a previous
4834         // process, clean it up now.
4835         if (app.thread != null) {
4836             handleAppDiedLocked(app, true, true);
4837         }
4838 
4839         // Tell the process all about itself.
4840 
4841         if (DEBUG_ALL) Slog.v(
4842                 TAG, "Binding process pid " + pid + " to record " + app);
4843 
4844         final String processName = app.processName;
4845         try {
4846             AppDeathRecipient adr = new AppDeathRecipient(
4847                     app, pid, thread);
4848             thread.asBinder().linkToDeath(adr, 0);
4849             app.deathRecipient = adr;
4850         } catch (RemoteException e) {
4851             app.resetPackageList(mProcessStats);
4852             mProcessList.startProcessLocked(app,
4853                     new HostingRecord("link fail", processName));
4854             return false;
4855         }
4856 
4857         EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
4858 
4859         app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;
4860         app.setCurrentSchedulingGroup(app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT);
4861         app.forcingToImportant = null;
4862         updateProcessForegroundLocked(app, false, 0, false);
4863         app.hasShownUi = false;
4864         app.setDebugging(false);
4865         app.cached = false;
4866         app.killedByAm = false;
4867         app.killed = false;
4868 
4869 
4870         // We carefully use the same state that PackageManager uses for
4871         // filtering, since we use this flag to decide if we need to install
4872         // providers when user is unlocked later
4873         app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);
4874 
4875         mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4876 
4877         boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
4878         List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
4879 
4880         if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
4881             Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
4882             msg.obj = app;
4883             mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT);
4884         }
4885 
4886         checkTime(startTime, "attachApplicationLocked: before bindApplication");
4887 
4888         if (!normalMode) {
4889             Slog.i(TAG, "Launching preboot mode app: " + app);
4890         }
4891 
4892         if (DEBUG_ALL) Slog.v(
4893             TAG, "New app record " + app
4894             + " thread=" + thread.asBinder() + " pid=" + pid);
4895         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
4896         try {
4897             int testMode = ApplicationThreadConstants.DEBUG_OFF;
4898             if (mDebugApp != null && mDebugApp.equals(processName)) {
4899                 testMode = mWaitForDebugger
4900                     ? ApplicationThreadConstants.DEBUG_WAIT
4901                     : ApplicationThreadConstants.DEBUG_ON;
4902                 app.setDebugging(true);
4903                 if (mDebugTransient) {
4904                     mDebugApp = mOrigDebugApp;
4905                     mWaitForDebugger = mOrigWaitForDebugger;
4906                 }
4907             }
4908 
4909             boolean enableTrackAllocation = false;
4910             if (mTrackAllocationApp != null && mTrackAllocationApp.equals(processName)) {
4911                 enableTrackAllocation = true;
4912                 mTrackAllocationApp = null;
4913             }
4914 
4915             // If the app is being launched for restore or full backup, set it up specially
4916             boolean isRestrictedBackupMode = false;
4917             if (backupTarget != null && backupTarget.appInfo.packageName.equals(processName)) {
4918                 isRestrictedBackupMode = backupTarget.appInfo.uid >= FIRST_APPLICATION_UID
4919                         && ((backupTarget.backupMode == BackupRecord.RESTORE)
4920                                 || (backupTarget.backupMode == BackupRecord.RESTORE_FULL)
4921                                 || (backupTarget.backupMode == BackupRecord.BACKUP_FULL));
4922             }
4923 
4924             final ActiveInstrumentation instr = app.getActiveInstrumentation();
4925 
4926             if (instr != null) {
4927                 notifyPackageUse(instr.mClass.getPackageName(),
4928                                  PackageManager.NOTIFY_PACKAGE_USE_INSTRUMENTATION);
4929             }
4930             if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc "
4931                     + processName + " with config "
4932                     + app.getWindowProcessController().getConfiguration());
4933             ApplicationInfo appInfo = instr != null ? instr.mTargetInfo : app.info;
4934             app.compat = compatibilityInfoForPackage(appInfo);
4935 
4936             ProfilerInfo profilerInfo = null;
4937             String preBindAgent = null;
4938             if (mProfileData.getProfileApp() != null
4939                     && mProfileData.getProfileApp().equals(processName)) {
4940                 mProfileData.setProfileProc(app);
4941                 if (mProfileData.getProfilerInfo() != null) {
4942                     // Send a profiler info object to the app if either a file is given, or
4943                     // an agent should be loaded at bind-time.
4944                     boolean needsInfo = mProfileData.getProfilerInfo().profileFile != null
4945                             || mProfileData.getProfilerInfo().attachAgentDuringBind;
4946                     profilerInfo = needsInfo
4947                             ? new ProfilerInfo(mProfileData.getProfilerInfo()) : null;
4948                     if (mProfileData.getProfilerInfo().agent != null) {
4949                         preBindAgent = mProfileData.getProfilerInfo().agent;
4950                     }
4951                 }
4952             } else if (instr != null && instr.mProfileFile != null) {
4953                 profilerInfo = new ProfilerInfo(instr.mProfileFile, null, 0, false, false,
4954                         null, false);
4955             }
4956             if (mAppAgentMap != null && mAppAgentMap.containsKey(processName)) {
4957                 // We need to do a debuggable check here. See setAgentApp for why the check is
4958                 // postponed to here.
4959                 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
4960                     String agent = mAppAgentMap.get(processName);
4961                     // Do not overwrite already requested agent.
4962                     if (profilerInfo == null) {
4963                         profilerInfo = new ProfilerInfo(null, null, 0, false, false,
4964                                 mAppAgentMap.get(processName), true);
4965                     } else if (profilerInfo.agent == null) {
4966                         profilerInfo = profilerInfo.setAgent(mAppAgentMap.get(processName), true);
4967                     }
4968                 }
4969             }
4970 
4971             if (profilerInfo != null && profilerInfo.profileFd != null) {
4972                 profilerInfo.profileFd = profilerInfo.profileFd.dup();
4973                 if (TextUtils.equals(mProfileData.getProfileApp(), processName)
4974                         && mProfileData.getProfilerInfo() != null) {
4975                     clearProfilerLocked();
4976                 }
4977             }
4978 
4979             // We deprecated Build.SERIAL and it is not accessible to
4980             // Instant Apps and target APIs higher than O MR1. Since access to the serial
4981             // is now behind a permission we push down the value.
4982             final String buildSerial = (!appInfo.isInstantApp()
4983                     && appInfo.targetSdkVersion < Build.VERSION_CODES.P)
4984                             ? sTheRealBuildSerial : Build.UNKNOWN;
4985 
4986             // Check if this is a secondary process that should be incorporated into some
4987             // currently active instrumentation.  (Note we do this AFTER all of the profiling
4988             // stuff above because profiling can currently happen only in the primary
4989             // instrumentation process.)
4990             if (mActiveInstrumentation.size() > 0 && instr == null) {
4991                 for (int i = mActiveInstrumentation.size() - 1;
4992                         i >= 0 && app.getActiveInstrumentation() == null; i--) {
4993                     ActiveInstrumentation aInstr = mActiveInstrumentation.get(i);
4994                     if (!aInstr.mFinished && aInstr.mTargetInfo.uid == app.uid) {
4995                         if (aInstr.mTargetProcesses.length == 0) {
4996                             // This is the wildcard mode, where every process brought up for
4997                             // the target instrumentation should be included.
4998                             if (aInstr.mTargetInfo.packageName.equals(app.info.packageName)) {
4999                                 app.setActiveInstrumentation(aInstr);
5000                                 aInstr.mRunningProcesses.add(app);
5001                             }
5002                         } else {
5003                             for (String proc : aInstr.mTargetProcesses) {
5004                                 if (proc.equals(app.processName)) {
5005                                     app.setActiveInstrumentation(aInstr);
5006                                     aInstr.mRunningProcesses.add(app);
5007                                     break;
5008                                 }
5009                             }
5010                         }
5011                     }
5012                 }
5013             }
5014 
5015             // If we were asked to attach an agent on startup, do so now, before we're binding
5016             // application code.
5017             if (preBindAgent != null) {
5018                 thread.attachAgent(preBindAgent);
5019             }
5020 
5021 
5022             // Figure out whether the app needs to run in autofill compat mode.
5023             AutofillOptions autofillOptions = null;
5024             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
5025                 final AutofillManagerInternal afm = LocalServices.getService(
5026                         AutofillManagerInternal.class);
5027                 if (afm != null) {
5028                     autofillOptions = afm.getAutofillOptions(
5029                             app.info.packageName, app.info.longVersionCode, app.userId);
5030                 }
5031             }
5032             ContentCaptureOptions contentCaptureOptions = null;
5033             if (UserHandle.getAppId(app.info.uid) >= Process.FIRST_APPLICATION_UID) {
5034                 final ContentCaptureManagerInternal ccm =
5035                         LocalServices.getService(ContentCaptureManagerInternal.class);
5036                 if (ccm != null) {
5037                     contentCaptureOptions = ccm.getOptionsForPackage(app.userId,
5038                             app.info.packageName);
5039                 }
5040             }
5041 
5042             checkTime(startTime, "attachApplicationLocked: immediately before bindApplication");
5043             bindApplicationTimeMillis = SystemClock.elapsedRealtime();
5044             mAtmInternal.preBindApplication(app.getWindowProcessController());
5045             final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
5046             if (app.isolatedEntryPoint != null) {
5047                 // This is an isolated process which should just call an entry point instead of
5048                 // being bound to an application.
5049                 thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
5050             } else if (instr2 != null) {
5051                 thread.bindApplication(processName, appInfo, providers,
5052                         instr2.mClass,
5053                         profilerInfo, instr2.mArguments,
5054                         instr2.mWatcher,
5055                         instr2.mUiAutomationConnection, testMode,
5056                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
5057                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
5058                         new Configuration(app.getWindowProcessController().getConfiguration()),
5059                         app.compat, getCommonServicesLocked(app.isolated),
5060                         mCoreSettingsObserver.getCoreSettingsLocked(),
5061                         buildSerial, autofillOptions, contentCaptureOptions);
5062             } else {
5063                 thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
5064                         null, null, null, testMode,
5065                         mBinderTransactionTrackingEnabled, enableTrackAllocation,
5066                         isRestrictedBackupMode || !normalMode, app.isPersistent(),
5067                         new Configuration(app.getWindowProcessController().getConfiguration()),
5068                         app.compat, getCommonServicesLocked(app.isolated),
5069                         mCoreSettingsObserver.getCoreSettingsLocked(),
5070                         buildSerial, autofillOptions, contentCaptureOptions);
5071             }
5072             if (profilerInfo != null) {
5073                 profilerInfo.closeFd();
5074                 profilerInfo = null;
5075             }
5076 
5077             // Make app active after binding application or client may be running requests (e.g
5078             // starting activities) before it is ready.
5079             app.makeActive(thread, mProcessStats);
5080             checkTime(startTime, "attachApplicationLocked: immediately after bindApplication");
5081             mProcessList.updateLruProcessLocked(app, false, null);
5082             checkTime(startTime, "attachApplicationLocked: after updateLruProcessLocked");
5083             app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
5084         } catch (Exception e) {
5085             // todo: Yikes!  What should we do?  For now we will try to
5086             // start another process, but that could easily get us in
5087             // an infinite loop of restarting processes...
5088             Slog.wtf(TAG, "Exception thrown during bind of " + app, e);
5089 
5090             app.resetPackageList(mProcessStats);
5091             app.unlinkDeathRecipient();
5092             mProcessList.startProcessLocked(app, new HostingRecord("bind-fail", processName));
5093             return false;
5094         }
5095 
5096         // Remove this record from the list of starting applications.
5097         mPersistentStartingProcesses.remove(app);
5098         if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES,
5099                 "Attach application locked removing on hold: " + app);
5100         mProcessesOnHold.remove(app);
5101 
5102         boolean badApp = false;
5103         boolean didSomething = false;
5104 
5105         // See if the top visible activity is waiting to run in this process...
5106         if (normalMode) {
5107             try {
5108                 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
5109             } catch (Exception e) {
5110                 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
5111                 badApp = true;
5112             }
5113         }
5114 
5115         // Find any services that should be running in this process...
5116         if (!badApp) {
5117             try {
5118                 didSomething |= mServices.attachApplicationLocked(app, processName);
5119                 checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
5120             } catch (Exception e) {
5121                 Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
5122                 badApp = true;
5123             }
5124         }
5125 
5126         // Check if a next-broadcast receiver is in this process...
5127         if (!badApp && isPendingBroadcastProcessLocked(pid)) {
5128             try {
5129                 didSomething |= sendPendingBroadcastsLocked(app);
5130                 checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
5131             } catch (Exception e) {
5132                 // If the app died trying to launch the receiver we declare it 'bad'
5133                 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
5134                 badApp = true;
5135             }
5136         }
5137 
5138         // Check whether the next backup agent is in this process...
5139         if (!badApp && backupTarget != null && backupTarget.app == app) {
5140             if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
5141                     "New app is backup target, launching agent for " + app);
5142             notifyPackageUse(backupTarget.appInfo.packageName,
5143                              PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
5144             try {
5145                 thread.scheduleCreateBackupAgent(backupTarget.appInfo,
5146                         compatibilityInfoForPackage(backupTarget.appInfo),
5147                         backupTarget.backupMode, backupTarget.userId);
5148             } catch (Exception e) {
5149                 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e);
5150                 badApp = true;
5151             }
5152         }
5153 
5154         if (badApp) {
5155             app.kill("error during init", true);
5156             handleAppDiedLocked(app, false, true);
5157             return false;
5158         }
5159 
5160         if (!didSomething) {
5161             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
5162             checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
5163         }
5164 
5165         StatsLog.write(
5166                 StatsLog.PROCESS_START_TIME,
5167                 app.info.uid,
5168                 app.pid,
5169                 app.info.packageName,
5170                 StatsLog.PROCESS_START_TIME__TYPE__COLD,
5171                 app.startTime,
5172                 (int) (bindApplicationTimeMillis - app.startTime),
5173                 (int) (SystemClock.elapsedRealtime() - app.startTime),
5174                 app.hostingRecord.getType(),
5175                 (app.hostingRecord.getName() != null ? app.hostingRecord.getName() : ""));
5176         return true;
5177     }
5178 
5179     @Override
attachApplication(IApplicationThread thread, long startSeq)5180     public final void attachApplication(IApplicationThread thread, long startSeq) {
5181         if (thread == null) {
5182             throw new SecurityException("Invalid application interface");
5183         }
5184         synchronized (this) {
5185             int callingPid = Binder.getCallingPid();
5186             final int callingUid = Binder.getCallingUid();
5187             final long origId = Binder.clearCallingIdentity();
5188             attachApplicationLocked(thread, callingPid, callingUid, startSeq);
5189             Binder.restoreCallingIdentity(origId);
5190         }
5191     }
5192 
5193     @Override
showBootMessage(final CharSequence msg, final boolean always)5194     public void showBootMessage(final CharSequence msg, final boolean always) {
5195         if (Binder.getCallingUid() != myUid()) {
5196             throw new SecurityException();
5197         }
5198         mWindowManager.showBootMessage(msg, always);
5199     }
5200 
finishBooting()5201     final void finishBooting() {
5202         Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "FinishBooting");
5203 
5204         synchronized (this) {
5205             if (!mBootAnimationComplete) {
5206                 mCallFinishBooting = true;
5207                 return;
5208             }
5209             mCallFinishBooting = false;
5210         }
5211 
5212         ArraySet<String> completedIsas = new ArraySet<String>();
5213         for (String abi : Build.SUPPORTED_ABIS) {
5214             ZYGOTE_PROCESS.establishZygoteConnectionForAbi(abi);
5215             final String instructionSet = VMRuntime.getInstructionSet(abi);
5216             if (!completedIsas.contains(instructionSet)) {
5217                 try {
5218                     mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi));
5219                 } catch (InstallerException e) {
5220                     if (!VMRuntime.didPruneDalvikCache()) {
5221                         // This is technically not the right filter, as different zygotes may
5222                         // have made different pruning decisions. But the log is best effort,
5223                         // anyways.
5224                         Slog.w(TAG, "Unable to mark boot complete for abi: " + abi + " (" +
5225                                 e.getMessage() +")");
5226                     }
5227                 }
5228                 completedIsas.add(instructionSet);
5229             }
5230         }
5231 
5232         IntentFilter pkgFilter = new IntentFilter();
5233         pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
5234         pkgFilter.addDataScheme("package");
5235         mContext.registerReceiver(new BroadcastReceiver() {
5236             @Override
5237             public void onReceive(Context context, Intent intent) {
5238                 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
5239                 if (pkgs != null) {
5240                     for (String pkg : pkgs) {
5241                         synchronized (ActivityManagerService.this) {
5242                             if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
5243                                     0, "query restart")) {
5244                                 setResultCode(Activity.RESULT_OK);
5245                                 return;
5246                             }
5247                         }
5248                     }
5249                 }
5250             }
5251         }, pkgFilter);
5252 
5253         IntentFilter dumpheapFilter = new IntentFilter();
5254         dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
5255         mContext.registerReceiver(new BroadcastReceiver() {
5256             @Override
5257             public void onReceive(Context context, Intent intent) {
5258                 final long delay = intent.getBooleanExtra(
5259                         DumpHeapActivity.EXTRA_DELAY_DELETE, false) ? 5 * 60 * 1000 : 0;
5260                 mHandler.sendEmptyMessageDelayed(DELETE_DUMPHEAP_MSG, delay);
5261             }
5262         }, dumpheapFilter);
5263 
5264         // Inform checkpointing systems of success
5265         try {
5266             IStorageManager storageManager = PackageHelper.getStorageManager();
5267             storageManager.commitChanges();
5268         } catch (Exception e) {
5269             PowerManager pm = (PowerManager)
5270                      mInjector.getContext().getSystemService(Context.POWER_SERVICE);
5271             pm.reboot("Checkpoint commit failed");
5272         }
5273 
5274         // Let system services know.
5275         mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
5276 
5277         synchronized (this) {
5278             // Ensure that any processes we had put on hold are now started
5279             // up.
5280             final int NP = mProcessesOnHold.size();
5281             if (NP > 0) {
5282                 ArrayList<ProcessRecord> procs =
5283                     new ArrayList<ProcessRecord>(mProcessesOnHold);
5284                 for (int ip=0; ip<NP; ip++) {
5285                     if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: "
5286                             + procs.get(ip));
5287                     mProcessList.startProcessLocked(procs.get(ip), new HostingRecord("on-hold"));
5288                 }
5289             }
5290             if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5291                 return;
5292             }
5293             // Start looking for apps that are abusing wake locks.
5294             Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
5295             mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
5296             // Tell anyone interested that we are done booting!
5297             SystemProperties.set("sys.boot_completed", "1");
5298 
5299             // And trigger dev.bootcomplete if we are not showing encryption progress
5300             if (!"trigger_restart_min_framework".equals(VoldProperties.decrypt().orElse(""))
5301                     || "".equals(VoldProperties.encrypt_progress().orElse(""))) {
5302                 SystemProperties.set("dev.bootcomplete", "1");
5303             }
5304             mUserController.sendBootCompleted(
5305                     new IIntentReceiver.Stub() {
5306                         @Override
5307                         public void performReceive(Intent intent, int resultCode,
5308                                 String data, Bundle extras, boolean ordered,
5309                                 boolean sticky, int sendingUser) {
5310                             synchronized (ActivityManagerService.this) {
5311                                 mOomAdjuster.mAppCompact.compactAllSystem();
5312                                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
5313                             }
5314                         }
5315                     });
5316             mUserController.scheduleStartProfiles();
5317         }
5318 
5319         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5320     }
5321 
5322     @Override
bootAnimationComplete()5323     public void bootAnimationComplete() {
5324         final boolean callFinishBooting;
5325         synchronized (this) {
5326             callFinishBooting = mCallFinishBooting;
5327             mBootAnimationComplete = true;
5328         }
5329         if (callFinishBooting) {
5330             finishBooting();
5331         }
5332     }
5333 
ensureBootCompleted()5334     final void ensureBootCompleted() {
5335         boolean booting;
5336         boolean enableScreen;
5337         synchronized (this) {
5338             booting = mBooting;
5339             mBooting = false;
5340             enableScreen = !mBooted;
5341             mBooted = true;
5342         }
5343 
5344         if (booting) {
5345             finishBooting();
5346         }
5347 
5348         if (enableScreen) {
5349             mAtmInternal.enableScreenAfterBoot(mBooted);
5350         }
5351     }
5352 
5353     @Override
getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle bOptions, int userId)5354     public IIntentSender getIntentSender(int type,
5355             String packageName, IBinder token, String resultWho,
5356             int requestCode, Intent[] intents, String[] resolvedTypes,
5357             int flags, Bundle bOptions, int userId) {
5358 
5359         // NOTE: The service lock isn't held in this method because nothing in the method requires
5360         // the service lock to be held.
5361 
5362         enforceNotIsolatedCaller("getIntentSender");
5363         // Refuse possible leaked file descriptors
5364         if (intents != null) {
5365             if (intents.length < 1) {
5366                 throw new IllegalArgumentException("Intents array length must be >= 1");
5367             }
5368             for (int i=0; i<intents.length; i++) {
5369                 Intent intent = intents[i];
5370                 if (intent != null) {
5371                     if (intent.hasFileDescriptors()) {
5372                         throw new IllegalArgumentException("File descriptors passed in Intent");
5373                     }
5374                     if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
5375                             (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5376                         throw new IllegalArgumentException(
5377                                 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5378                     }
5379                     intents[i] = new Intent(intent);
5380                 }
5381             }
5382             if (resolvedTypes != null && resolvedTypes.length != intents.length) {
5383                 throw new IllegalArgumentException(
5384                         "Intent array length does not match resolvedTypes length");
5385             }
5386         }
5387         if (bOptions != null) {
5388             if (bOptions.hasFileDescriptors()) {
5389                 throw new IllegalArgumentException("File descriptors passed in options");
5390             }
5391         }
5392 
5393         int callingUid = Binder.getCallingUid();
5394         int origUserId = userId;
5395         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
5396                 type == ActivityManager.INTENT_SENDER_BROADCAST,
5397                 ALLOW_NON_FULL, "getIntentSender", null);
5398         if (origUserId == UserHandle.USER_CURRENT) {
5399             // We don't want to evaluate this until the pending intent is
5400             // actually executed.  However, we do want to always do the
5401             // security checking for it above.
5402             userId = UserHandle.USER_CURRENT;
5403         }
5404         try {
5405             if (callingUid != 0 && callingUid != SYSTEM_UID) {
5406                 final int uid = AppGlobals.getPackageManager().getPackageUid(packageName,
5407                         MATCH_DEBUG_TRIAGED_MISSING, UserHandle.getUserId(callingUid));
5408                 if (!UserHandle.isSameApp(callingUid, uid)) {
5409                     String msg = "Permission Denial: getIntentSender() from pid="
5410                         + Binder.getCallingPid()
5411                         + ", uid=" + Binder.getCallingUid()
5412                         + ", (need uid=" + uid + ")"
5413                         + " is not allowed to send as package " + packageName;
5414                     Slog.w(TAG, msg);
5415                     throw new SecurityException(msg);
5416                 }
5417             }
5418 
5419             if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5420                 return mAtmInternal.getIntentSender(type, packageName, callingUid, userId,
5421                         token, resultWho, requestCode, intents, resolvedTypes, flags, bOptions);
5422             }
5423             return mPendingIntentController.getIntentSender(type, packageName, callingUid,
5424                     userId, token, resultWho, requestCode, intents, resolvedTypes, flags,
5425                     bOptions);
5426         } catch (RemoteException e) {
5427             throw new SecurityException(e);
5428         }
5429     }
5430 
5431     @Override
sendIntentSender(IIntentSender target, IBinder whitelistToken, int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options)5432     public int sendIntentSender(IIntentSender target, IBinder whitelistToken, int code,
5433             Intent intent, String resolvedType,
5434             IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
5435         if (target instanceof PendingIntentRecord) {
5436             return ((PendingIntentRecord)target).sendWithResult(code, intent, resolvedType,
5437                     whitelistToken, finishedReceiver, requiredPermission, options);
5438         } else {
5439             if (intent == null) {
5440                 // Weird case: someone has given us their own custom IIntentSender, and now
5441                 // they have someone else trying to send to it but of course this isn't
5442                 // really a PendingIntent, so there is no base Intent, and the caller isn't
5443                 // supplying an Intent... but we never want to dispatch a null Intent to
5444                 // a receiver, so um...  let's make something up.
5445                 Slog.wtf(TAG, "Can't use null intent with direct IIntentSender call");
5446                 intent = new Intent(Intent.ACTION_MAIN);
5447             }
5448             try {
5449                 target.send(code, intent, resolvedType, whitelistToken, null,
5450                         requiredPermission, options);
5451             } catch (RemoteException e) {
5452             }
5453             // Platform code can rely on getting a result back when the send is done, but if
5454             // this intent sender is from outside of the system we can't rely on it doing that.
5455             // So instead we don't give it the result receiver, and instead just directly
5456             // report the finish immediately.
5457             if (finishedReceiver != null) {
5458                 try {
5459                     finishedReceiver.performReceive(intent, 0,
5460                             null, null, false, false, UserHandle.getCallingUserId());
5461                 } catch (RemoteException e) {
5462                 }
5463             }
5464             return 0;
5465         }
5466     }
5467 
5468     @Override
cancelIntentSender(IIntentSender sender)5469     public void cancelIntentSender(IIntentSender sender) {
5470         mPendingIntentController.cancelIntentSender(sender);
5471     }
5472 
5473     @Override
getPackageForIntentSender(IIntentSender pendingResult)5474     public String getPackageForIntentSender(IIntentSender pendingResult) {
5475         if (!(pendingResult instanceof PendingIntentRecord)) {
5476             return null;
5477         }
5478         try {
5479             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5480             return res.key.packageName;
5481         } catch (ClassCastException e) {
5482         }
5483         return null;
5484     }
5485 
5486     @Override
registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5487     public void registerIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver) {
5488         mPendingIntentController.registerIntentSenderCancelListener(sender, receiver);
5489     }
5490 
5491     @Override
unregisterIntentSenderCancelListener(IIntentSender sender, IResultReceiver receiver)5492     public void unregisterIntentSenderCancelListener(IIntentSender sender,
5493             IResultReceiver receiver) {
5494         mPendingIntentController.unregisterIntentSenderCancelListener(sender, receiver);
5495     }
5496 
5497     @Override
getUidForIntentSender(IIntentSender sender)5498     public int getUidForIntentSender(IIntentSender sender) {
5499         if (sender instanceof PendingIntentRecord) {
5500             try {
5501                 PendingIntentRecord res = (PendingIntentRecord)sender;
5502                 return res.uid;
5503             } catch (ClassCastException e) {
5504             }
5505         }
5506         return -1;
5507     }
5508 
5509     @Override
isIntentSenderTargetedToPackage(IIntentSender pendingResult)5510     public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
5511         if (!(pendingResult instanceof PendingIntentRecord)) {
5512             return false;
5513         }
5514         try {
5515             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5516             if (res.key.allIntents == null) {
5517                 return false;
5518             }
5519             for (int i=0; i<res.key.allIntents.length; i++) {
5520                 Intent intent = res.key.allIntents[i];
5521                 if (intent.getPackage() != null && intent.getComponent() != null) {
5522                     return false;
5523                 }
5524             }
5525             return true;
5526         } catch (ClassCastException e) {
5527         }
5528         return false;
5529     }
5530 
5531     @Override
isIntentSenderAnActivity(IIntentSender pendingResult)5532     public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
5533         if (!(pendingResult instanceof PendingIntentRecord)) {
5534             return false;
5535         }
5536         try {
5537             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5538             if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
5539                 return true;
5540             }
5541             return false;
5542         } catch (ClassCastException e) {
5543         }
5544         return false;
5545     }
5546 
5547     @Override
isIntentSenderAForegroundService(IIntentSender pendingResult)5548     public boolean isIntentSenderAForegroundService(IIntentSender pendingResult) {
5549         if (pendingResult instanceof PendingIntentRecord) {
5550             final PendingIntentRecord res = (PendingIntentRecord) pendingResult;
5551             return res.key.type == ActivityManager.INTENT_SENDER_FOREGROUND_SERVICE;
5552         }
5553         return false;
5554     }
5555 
5556     @Override
isIntentSenderABroadcast(IIntentSender pendingResult)5557     public boolean isIntentSenderABroadcast(IIntentSender pendingResult) {
5558         if (pendingResult instanceof PendingIntentRecord) {
5559             final PendingIntentRecord res = (PendingIntentRecord) pendingResult;
5560             return res.key.type == ActivityManager.INTENT_SENDER_BROADCAST;
5561         }
5562         return false;
5563     }
5564 
5565     @Override
getIntentForIntentSender(IIntentSender pendingResult)5566     public Intent getIntentForIntentSender(IIntentSender pendingResult) {
5567         enforceCallingPermission(Manifest.permission.GET_INTENT_SENDER_INTENT,
5568                 "getIntentForIntentSender()");
5569         if (!(pendingResult instanceof PendingIntentRecord)) {
5570             return null;
5571         }
5572         try {
5573             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5574             return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
5575         } catch (ClassCastException e) {
5576         }
5577         return null;
5578     }
5579 
5580     @Override
getTagForIntentSender(IIntentSender pendingResult, String prefix)5581     public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
5582         if (!(pendingResult instanceof PendingIntentRecord)) {
5583             return null;
5584         }
5585         try {
5586             PendingIntentRecord res = (PendingIntentRecord)pendingResult;
5587             synchronized (this) {
5588                 return getTagForIntentSenderLocked(res, prefix);
5589             }
5590         } catch (ClassCastException e) {
5591         }
5592         return null;
5593     }
5594 
getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)5595     String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) {
5596         final Intent intent = res.key.requestIntent;
5597         if (intent != null) {
5598             if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
5599                     || res.lastTagPrefix.equals(prefix))) {
5600                 return res.lastTag;
5601             }
5602             res.lastTagPrefix = prefix;
5603             final StringBuilder sb = new StringBuilder(128);
5604             if (prefix != null) {
5605                 sb.append(prefix);
5606             }
5607             if (intent.getAction() != null) {
5608                 sb.append(intent.getAction());
5609             } else if (intent.getComponent() != null) {
5610                 intent.getComponent().appendShortString(sb);
5611             } else {
5612                 sb.append("?");
5613             }
5614             return res.lastTag = sb.toString();
5615         }
5616         return null;
5617     }
5618 
5619     @Override
setProcessLimit(int max)5620     public void setProcessLimit(int max) {
5621         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5622                 "setProcessLimit()");
5623         synchronized (this) {
5624             mConstants.setOverrideMaxCachedProcesses(max);
5625         }
5626         trimApplications(OomAdjuster.OOM_ADJ_REASON_PROCESS_END);
5627     }
5628 
5629     @Override
getProcessLimit()5630     public int getProcessLimit() {
5631         synchronized (this) {
5632             return mConstants.getOverrideMaxCachedProcesses();
5633         }
5634     }
5635 
importanceTokenDied(ImportanceToken token)5636     void importanceTokenDied(ImportanceToken token) {
5637         synchronized (ActivityManagerService.this) {
5638             synchronized (mPidsSelfLocked) {
5639                 ImportanceToken cur
5640                     = mImportantProcesses.get(token.pid);
5641                 if (cur != token) {
5642                     return;
5643                 }
5644                 mImportantProcesses.remove(token.pid);
5645                 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
5646                 if (pr == null) {
5647                     return;
5648                 }
5649                 pr.forcingToImportant = null;
5650                 updateProcessForegroundLocked(pr, false, 0, false);
5651             }
5652             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5653         }
5654     }
5655 
5656     @Override
setProcessImportant(IBinder token, int pid, boolean isForeground, String reason)5657     public void setProcessImportant(IBinder token, int pid, boolean isForeground, String reason) {
5658         enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
5659                 "setProcessImportant()");
5660         synchronized(this) {
5661             boolean changed = false;
5662 
5663             synchronized (mPidsSelfLocked) {
5664                 ProcessRecord pr = mPidsSelfLocked.get(pid);
5665                 if (pr == null && isForeground) {
5666                     Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
5667                     return;
5668                 }
5669                 ImportanceToken oldToken = mImportantProcesses.get(pid);
5670                 if (oldToken != null) {
5671                     oldToken.token.unlinkToDeath(oldToken, 0);
5672                     mImportantProcesses.remove(pid);
5673                     if (pr != null) {
5674                         pr.forcingToImportant = null;
5675                     }
5676                     changed = true;
5677                 }
5678                 if (isForeground && token != null) {
5679                     ImportanceToken newToken = new ImportanceToken(pid, token, reason) {
5680                         @Override
5681                         public void binderDied() {
5682                             importanceTokenDied(this);
5683                         }
5684                     };
5685                     try {
5686                         token.linkToDeath(newToken, 0);
5687                         mImportantProcesses.put(pid, newToken);
5688                         pr.forcingToImportant = newToken;
5689                         changed = true;
5690                     } catch (RemoteException e) {
5691                         // If the process died while doing this, we will later
5692                         // do the cleanup with the process death link.
5693                     }
5694                 }
5695             }
5696 
5697             if (changed) {
5698                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
5699             }
5700         }
5701     }
5702 
isAppForeground(int uid)5703     private boolean isAppForeground(int uid) {
5704         synchronized (this) {
5705             UidRecord uidRec = mProcessList.mActiveUids.get(uid);
5706             if (uidRec == null || uidRec.idle) {
5707                 return false;
5708             }
5709             return uidRec.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
5710         }
5711     }
5712 
isAppBad(ApplicationInfo info)5713     private boolean isAppBad(ApplicationInfo info) {
5714         synchronized (this) {
5715             return mAppErrors.isBadProcessLocked(info);
5716         }
5717     }
5718 
5719     // NOTE: this is an internal method used by the OnShellCommand implementation only and should
5720     // be guarded by permission checking.
getUidState(int uid)5721     int getUidState(int uid) {
5722         synchronized (this) {
5723             return mProcessList.getUidProcStateLocked(uid);
5724         }
5725     }
5726 
5727     // =========================================================
5728     // PROCESS INFO
5729     // =========================================================
5730 
5731     static class ProcessInfoService extends IProcessInfoService.Stub {
5732         final ActivityManagerService mActivityManagerService;
ProcessInfoService(ActivityManagerService activityManagerService)5733         ProcessInfoService(ActivityManagerService activityManagerService) {
5734             mActivityManagerService = activityManagerService;
5735         }
5736 
5737         @Override
getProcessStatesFromPids( int[] pids, int[] states)5738         public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) {
5739             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5740                     /*in*/ pids, /*out*/ states, null);
5741         }
5742 
5743         @Override
getProcessStatesAndOomScoresFromPids( int[] pids, int[] states, int[] scores)5744         public void getProcessStatesAndOomScoresFromPids(
5745                 /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5746             mActivityManagerService.getProcessStatesAndOomScoresForPIDs(
5747                     /*in*/ pids, /*out*/ states, /*out*/ scores);
5748         }
5749     }
5750 
5751     /**
5752      * For each PID in the given input array, write the current process state
5753      * for that process into the states array, or -1 to indicate that no
5754      * process with the given PID exists. If scores array is provided, write
5755      * the oom score for the process into the scores array, with INVALID_ADJ
5756      * indicating the PID doesn't exist.
5757      */
getProcessStatesAndOomScoresForPIDs( int[] pids, int[] states, int[] scores)5758     public void getProcessStatesAndOomScoresForPIDs(
5759             /*in*/ int[] pids, /*out*/ int[] states, /*out*/ int[] scores) {
5760         if (scores != null) {
5761             enforceCallingPermission(android.Manifest.permission.GET_PROCESS_STATE_AND_OOM_SCORE,
5762                     "getProcessStatesAndOomScoresForPIDs()");
5763         }
5764 
5765         if (pids == null) {
5766             throw new NullPointerException("pids");
5767         } else if (states == null) {
5768             throw new NullPointerException("states");
5769         } else if (pids.length != states.length) {
5770             throw new IllegalArgumentException("pids and states arrays have different lengths!");
5771         } else if (scores != null && pids.length != scores.length) {
5772             throw new IllegalArgumentException("pids and scores arrays have different lengths!");
5773         }
5774 
5775         synchronized (mPidsSelfLocked) {
5776             for (int i = 0; i < pids.length; i++) {
5777                 ProcessRecord pr = mPidsSelfLocked.get(pids[i]);
5778                 states[i] = (pr == null) ? PROCESS_STATE_NONEXISTENT : pr.getCurProcState();
5779                 if (scores != null) {
5780                     scores[i] = (pr == null) ? ProcessList.INVALID_ADJ : pr.curAdj;
5781                 }
5782             }
5783         }
5784     }
5785 
5786     // =========================================================
5787     // PERMISSIONS
5788     // =========================================================
5789 
5790     static class PermissionController extends IPermissionController.Stub {
5791         ActivityManagerService mActivityManagerService;
PermissionController(ActivityManagerService activityManagerService)5792         PermissionController(ActivityManagerService activityManagerService) {
5793             mActivityManagerService = activityManagerService;
5794         }
5795 
5796         @Override
checkPermission(String permission, int pid, int uid)5797         public boolean checkPermission(String permission, int pid, int uid) {
5798             return mActivityManagerService.checkPermission(permission, pid,
5799                     uid) == PackageManager.PERMISSION_GRANTED;
5800         }
5801 
5802         @Override
noteOp(String op, int uid, String packageName)5803         public int noteOp(String op, int uid, String packageName) {
5804             return mActivityManagerService.mAppOpsService
5805                     .noteOperation(AppOpsManager.strOpToOp(op), uid, packageName);
5806         }
5807 
5808         @Override
getPackagesForUid(int uid)5809         public String[] getPackagesForUid(int uid) {
5810             return mActivityManagerService.mContext.getPackageManager()
5811                     .getPackagesForUid(uid);
5812         }
5813 
5814         @Override
isRuntimePermission(String permission)5815         public boolean isRuntimePermission(String permission) {
5816             try {
5817                 PermissionInfo info = mActivityManagerService.mContext.getPackageManager()
5818                         .getPermissionInfo(permission, 0);
5819                 return (info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
5820                         == PermissionInfo.PROTECTION_DANGEROUS;
5821             } catch (NameNotFoundException nnfe) {
5822                 Slog.e(TAG, "No such permission: "+ permission, nnfe);
5823             }
5824             return false;
5825         }
5826 
5827         @Override
getPackageUid(String packageName, int flags)5828         public int getPackageUid(String packageName, int flags) {
5829             try {
5830                 return mActivityManagerService.mContext.getPackageManager()
5831                         .getPackageUid(packageName, flags);
5832             } catch (NameNotFoundException nnfe) {
5833                 return -1;
5834             }
5835         }
5836     }
5837 
5838     class IntentFirewallInterface implements IntentFirewall.AMSInterface {
5839         @Override
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5840         public int checkComponentPermission(String permission, int pid, int uid,
5841                 int owningUid, boolean exported) {
5842             return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
5843                     owningUid, exported);
5844         }
5845 
5846         @Override
getAMSLock()5847         public Object getAMSLock() {
5848             return ActivityManagerService.this;
5849         }
5850     }
5851 
checkComponentPermission(String permission, int pid, int uid, int owningUid, boolean exported)5852     public static int checkComponentPermission(String permission, int pid, int uid,
5853             int owningUid, boolean exported) {
5854         if (pid == MY_PID) {
5855             return PackageManager.PERMISSION_GRANTED;
5856         }
5857         return ActivityManager.checkComponentPermission(permission, uid,
5858                 owningUid, exported);
5859     }
5860 
5861     /**
5862      * As the only public entry point for permissions checking, this method
5863      * can enforce the semantic that requesting a check on a null global
5864      * permission is automatically denied.  (Internally a null permission
5865      * string is used when calling {@link #checkComponentPermission} in cases
5866      * when only uid-based security is needed.)
5867      *
5868      * This can be called with or without the global lock held.
5869      */
5870     @Override
checkPermission(String permission, int pid, int uid)5871     public int checkPermission(String permission, int pid, int uid) {
5872         if (permission == null) {
5873             return PackageManager.PERMISSION_DENIED;
5874         }
5875         return checkComponentPermission(permission, pid, uid, -1, true);
5876     }
5877 
5878     @Override
checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken)5879     public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) {
5880         if (permission == null) {
5881             return PackageManager.PERMISSION_DENIED;
5882         }
5883 
5884         // We might be performing an operation on behalf of an indirect binder
5885         // invocation, e.g. via {@link #openContentUri}.  Check and adjust the
5886         // client identity accordingly before proceeding.
5887         Identity tlsIdentity = sCallerIdentity.get();
5888         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
5889             Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
5890                     + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
5891             uid = tlsIdentity.uid;
5892             pid = tlsIdentity.pid;
5893         }
5894 
5895         return checkComponentPermission(permission, pid, uid, -1, true);
5896     }
5897 
5898     /**
5899      * Binder IPC calls go through the public entry point.
5900      * This can be called with or without the global lock held.
5901      */
checkCallingPermission(String permission)5902     int checkCallingPermission(String permission) {
5903         return checkPermission(permission,
5904                 Binder.getCallingPid(),
5905                 Binder.getCallingUid());
5906     }
5907 
5908     /**
5909      * This can be called with or without the global lock held.
5910      */
enforceCallingPermission(String permission, String func)5911     void enforceCallingPermission(String permission, String func) {
5912         if (checkCallingPermission(permission)
5913                 == PackageManager.PERMISSION_GRANTED) {
5914             return;
5915         }
5916 
5917         String msg = "Permission Denial: " + func + " from pid="
5918                 + Binder.getCallingPid()
5919                 + ", uid=" + Binder.getCallingUid()
5920                 + " requires " + permission;
5921         Slog.w(TAG, msg);
5922         throw new SecurityException(msg);
5923     }
5924 
5925     /**
5926      * This can be called with or without the global lock held.
5927      */
enforcePermission(String permission, int pid, int uid, String func)5928     void enforcePermission(String permission, int pid, int uid, String func) {
5929         if (checkPermission(permission, pid, uid) == PackageManager.PERMISSION_GRANTED) {
5930             return;
5931         }
5932 
5933         String msg = "Permission Denial: " + func + " from pid=" + pid + ", uid=" + uid
5934                 + " requires " + permission;
5935         Slog.w(TAG, msg);
5936         throw new SecurityException(msg);
5937     }
5938 
isAppStartModeDisabled(int uid, String packageName)5939     public boolean isAppStartModeDisabled(int uid, String packageName) {
5940         synchronized (this) {
5941             return getAppStartModeLocked(uid, packageName, 0, -1, false, true, false)
5942                     == ActivityManager.APP_START_MODE_DISABLED;
5943         }
5944     }
5945 
5946     // Unified app-op and target sdk check
appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)5947     int appRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
5948         // Apps that target O+ are always subject to background check
5949         if (packageTargetSdk >= Build.VERSION_CODES.O) {
5950             if (DEBUG_BACKGROUND_CHECK) {
5951                 Slog.i(TAG, "App " + uid + "/" + packageName + " targets O+, restricted");
5952             }
5953             return ActivityManager.APP_START_MODE_DELAYED_RIGID;
5954         }
5955         // ...and legacy apps get an AppOp check
5956         int appop = mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
5957                 uid, packageName);
5958         if (DEBUG_BACKGROUND_CHECK) {
5959             Slog.i(TAG, "Legacy app " + uid + "/" + packageName + " bg appop " + appop);
5960         }
5961         switch (appop) {
5962             case AppOpsManager.MODE_ALLOWED:
5963                 // If force-background-check is enabled, restrict all apps that aren't whitelisted.
5964                 if (mForceBackgroundCheck &&
5965                         !UserHandle.isCore(uid) &&
5966                         !isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ true)) {
5967                     if (DEBUG_BACKGROUND_CHECK) {
5968                         Slog.i(TAG, "Force background check: " +
5969                                 uid + "/" + packageName + " restricted");
5970                     }
5971                     return ActivityManager.APP_START_MODE_DELAYED;
5972                 }
5973                 return ActivityManager.APP_START_MODE_NORMAL;
5974             case AppOpsManager.MODE_IGNORED:
5975                 return ActivityManager.APP_START_MODE_DELAYED;
5976             default:
5977                 return ActivityManager.APP_START_MODE_DELAYED_RIGID;
5978         }
5979     }
5980 
5981     // Service launch is available to apps with run-in-background exemptions but
5982     // some other background operations are not.  If we're doing a check
5983     // of service-launch policy, allow those callers to proceed unrestricted.
appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk)5984     int appServicesRestrictedInBackgroundLocked(int uid, String packageName, int packageTargetSdk) {
5985         // Persistent app?
5986         if (mPackageManagerInt.isPackagePersistent(packageName)) {
5987             if (DEBUG_BACKGROUND_CHECK) {
5988                 Slog.i(TAG, "App " + uid + "/" + packageName
5989                         + " is persistent; not restricted in background");
5990             }
5991             return ActivityManager.APP_START_MODE_NORMAL;
5992         }
5993 
5994         // Non-persistent but background whitelisted?
5995         if (uidOnBackgroundWhitelist(uid)) {
5996             if (DEBUG_BACKGROUND_CHECK) {
5997                 Slog.i(TAG, "App " + uid + "/" + packageName
5998                         + " on background whitelist; not restricted in background");
5999             }
6000             return ActivityManager.APP_START_MODE_NORMAL;
6001         }
6002 
6003         // Is this app on the battery whitelist?
6004         if (isOnDeviceIdleWhitelistLocked(uid, /*allowExceptIdleToo=*/ false)) {
6005             if (DEBUG_BACKGROUND_CHECK) {
6006                 Slog.i(TAG, "App " + uid + "/" + packageName
6007                         + " on idle whitelist; not restricted in background");
6008             }
6009             return ActivityManager.APP_START_MODE_NORMAL;
6010         }
6011 
6012         // None of the service-policy criteria apply, so we apply the common criteria
6013         return appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk);
6014     }
6015 
getAppStartModeLocked(int uid, String packageName, int packageTargetSdk, int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby)6016     int getAppStartModeLocked(int uid, String packageName, int packageTargetSdk,
6017             int callingPid, boolean alwaysRestrict, boolean disabledOnly, boolean forcedStandby) {
6018         UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
6019         if (DEBUG_BACKGROUND_CHECK) Slog.d(TAG, "checkAllowBackground: uid=" + uid + " pkg="
6020                 + packageName + " rec=" + uidRec + " always=" + alwaysRestrict + " idle="
6021                 + (uidRec != null ? uidRec.idle : false));
6022         if (uidRec == null || alwaysRestrict || forcedStandby || uidRec.idle) {
6023             boolean ephemeral;
6024             if (uidRec == null) {
6025                 ephemeral = getPackageManagerInternalLocked().isPackageEphemeral(
6026                         UserHandle.getUserId(uid), packageName);
6027             } else {
6028                 ephemeral = uidRec.ephemeral;
6029             }
6030 
6031             if (ephemeral) {
6032                 // We are hard-core about ephemeral apps not running in the background.
6033                 return ActivityManager.APP_START_MODE_DISABLED;
6034             } else {
6035                 if (disabledOnly) {
6036                     // The caller is only interested in whether app starts are completely
6037                     // disabled for the given package (that is, it is an instant app).  So
6038                     // we don't need to go further, which is all just seeing if we should
6039                     // apply a "delayed" mode for a regular app.
6040                     return ActivityManager.APP_START_MODE_NORMAL;
6041                 }
6042                 final int startMode = (alwaysRestrict)
6043                         ? appRestrictedInBackgroundLocked(uid, packageName, packageTargetSdk)
6044                         : appServicesRestrictedInBackgroundLocked(uid, packageName,
6045                                 packageTargetSdk);
6046                 if (DEBUG_BACKGROUND_CHECK) {
6047                     Slog.d(TAG, "checkAllowBackground: uid=" + uid
6048                             + " pkg=" + packageName + " startMode=" + startMode
6049                             + " onwhitelist=" + isOnDeviceIdleWhitelistLocked(uid, false)
6050                             + " onwhitelist(ei)=" + isOnDeviceIdleWhitelistLocked(uid, true));
6051                 }
6052                 if (startMode == ActivityManager.APP_START_MODE_DELAYED) {
6053                     // This is an old app that has been forced into a "compatible as possible"
6054                     // mode of background check.  To increase compatibility, we will allow other
6055                     // foreground apps to cause its services to start.
6056                     if (callingPid >= 0) {
6057                         ProcessRecord proc;
6058                         synchronized (mPidsSelfLocked) {
6059                             proc = mPidsSelfLocked.get(callingPid);
6060                         }
6061                         if (proc != null &&
6062                                 !ActivityManager.isProcStateBackground(proc.getCurProcState())) {
6063                             // Whoever is instigating this is in the foreground, so we will allow it
6064                             // to go through.
6065                             return ActivityManager.APP_START_MODE_NORMAL;
6066                         }
6067                     }
6068                 }
6069                 return startMode;
6070             }
6071         }
6072         return ActivityManager.APP_START_MODE_NORMAL;
6073     }
6074 
6075     /**
6076      * @return whether a UID is in the system, user or temp doze whitelist.
6077      */
isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo)6078     boolean isOnDeviceIdleWhitelistLocked(int uid, boolean allowExceptIdleToo) {
6079         final int appId = UserHandle.getAppId(uid);
6080 
6081         final int[] whitelist = allowExceptIdleToo
6082                 ? mDeviceIdleExceptIdleWhitelist
6083                 : mDeviceIdleWhitelist;
6084 
6085         return Arrays.binarySearch(whitelist, appId) >= 0
6086                 || Arrays.binarySearch(mDeviceIdleTempWhitelist, appId) >= 0
6087                 || mPendingTempWhitelist.indexOfKey(uid) >= 0;
6088     }
6089 
6090     /**
6091      * @return whitelist tag for a uid from mPendingTempWhitelist, null if not currently on
6092      * the whitelist
6093      */
getPendingTempWhitelistTagForUidLocked(int uid)6094     String getPendingTempWhitelistTagForUidLocked(int uid) {
6095         final PendingTempWhitelist ptw = mPendingTempWhitelist.get(uid);
6096         return ptw != null ? ptw.tag : null;
6097     }
6098 
getProviderInfoLocked(String authority, int userHandle, int pmFlags)6099     private ProviderInfo getProviderInfoLocked(String authority, int userHandle, int pmFlags) {
6100         ProviderInfo pi = null;
6101         ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
6102         if (cpr != null) {
6103             pi = cpr.info;
6104         } else {
6105             try {
6106                 pi = AppGlobals.getPackageManager().resolveContentProvider(
6107                         authority, PackageManager.GET_URI_PERMISSION_PATTERNS | pmFlags,
6108                         userHandle);
6109             } catch (RemoteException ex) {
6110             }
6111         }
6112         return pi;
6113     }
6114 
6115     @VisibleForTesting
grantEphemeralAccessLocked(int userId, Intent intent, int targetAppId, int ephemeralAppId)6116     public void grantEphemeralAccessLocked(int userId, Intent intent,
6117             int targetAppId, int ephemeralAppId) {
6118         getPackageManagerInternalLocked().
6119                 grantEphemeralAccess(userId, intent, targetAppId, ephemeralAppId);
6120     }
6121 
6122     /**
6123      * @param uri This uri must NOT contain an embedded userId.
6124      * @param userId The userId in which the uri is to be resolved.
6125      */
6126     @Override
checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)6127     public int checkUriPermission(Uri uri, int pid, int uid,
6128             final int modeFlags, int userId, IBinder callerToken) {
6129         enforceNotIsolatedCaller("checkUriPermission");
6130 
6131         // Another redirected-binder-call permissions check as in
6132         // {@link checkPermissionWithToken}.
6133         Identity tlsIdentity = sCallerIdentity.get();
6134         if (tlsIdentity != null && tlsIdentity.token == callerToken) {
6135             uid = tlsIdentity.uid;
6136             pid = tlsIdentity.pid;
6137         }
6138 
6139         // Our own process gets to do everything.
6140         if (pid == MY_PID) {
6141             return PackageManager.PERMISSION_GRANTED;
6142         }
6143         return mUgmInternal.checkUriPermission(new GrantUri(userId, uri, false), uid, modeFlags)
6144                 ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED;
6145     }
6146 
6147     /**
6148      * @param uri This uri must NOT contain an embedded userId.
6149      * @param userId The userId in which the uri is to be resolved.
6150      */
6151     @Override
grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)6152     public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
6153             final int modeFlags, int userId) {
6154         enforceNotIsolatedCaller("grantUriPermission");
6155         GrantUri grantUri = new GrantUri(userId, uri, false);
6156         synchronized(this) {
6157             final ProcessRecord r = getRecordForAppLocked(caller);
6158             if (r == null) {
6159                 throw new SecurityException("Unable to find app for caller "
6160                         + caller
6161                         + " when granting permission to uri " + grantUri);
6162             }
6163             if (targetPkg == null) {
6164                 throw new IllegalArgumentException("null target");
6165             }
6166             if (grantUri == null) {
6167                 throw new IllegalArgumentException("null uri");
6168             }
6169 
6170             Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
6171                     | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
6172                     | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
6173                     | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
6174 
6175             mUgmInternal.grantUriPermission(r.uid, targetPkg, grantUri, modeFlags, null,
6176                     UserHandle.getUserId(r.uid));
6177         }
6178     }
6179 
6180     /**
6181      * @param uri This uri must NOT contain an embedded userId.
6182      * @param userId The userId in which the uri is to be resolved.
6183      */
6184     @Override
revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri, final int modeFlags, int userId)6185     public void revokeUriPermission(IApplicationThread caller, String targetPackage, Uri uri,
6186             final int modeFlags, int userId) {
6187         enforceNotIsolatedCaller("revokeUriPermission");
6188         synchronized(this) {
6189             final ProcessRecord r = getRecordForAppLocked(caller);
6190             if (r == null) {
6191                 throw new SecurityException("Unable to find app for caller "
6192                         + caller
6193                         + " when revoking permission to uri " + uri);
6194             }
6195             if (uri == null) {
6196                 Slog.w(TAG, "revokeUriPermission: null uri");
6197                 return;
6198             }
6199 
6200             if (!Intent.isAccessUriMode(modeFlags)) {
6201                 return;
6202             }
6203 
6204             final String authority = uri.getAuthority();
6205             final ProviderInfo pi = getProviderInfoLocked(authority, userId,
6206                     MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE);
6207             if (pi == null) {
6208                 Slog.w(TAG, "No content provider found for permission revoke: "
6209                         + uri.toSafeString());
6210                 return;
6211             }
6212 
6213             mUgmInternal.revokeUriPermission(targetPackage, r.uid, new GrantUri(userId, uri, false),
6214                     modeFlags);
6215         }
6216     }
6217 
6218     @Override
showWaitingForDebugger(IApplicationThread who, boolean waiting)6219     public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
6220         synchronized (this) {
6221             ProcessRecord app =
6222                 who != null ? getRecordForAppLocked(who) : null;
6223             if (app == null) return;
6224 
6225             Message msg = Message.obtain();
6226             msg.what = WAIT_FOR_DEBUGGER_UI_MSG;
6227             msg.obj = app;
6228             msg.arg1 = waiting ? 1 : 0;
6229             mUiHandler.sendMessage(msg);
6230         }
6231     }
6232 
6233     @Override
getMemoryInfo(ActivityManager.MemoryInfo outInfo)6234     public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
6235         mProcessList.getMemoryInfo(outInfo);
6236     }
6237 
6238     // =========================================================
6239     // TASK MANAGEMENT
6240     // =========================================================
6241 
6242     @Override
getTasks(int maxNum)6243     public List<RunningTaskInfo> getTasks(int maxNum) {
6244         return mActivityTaskManager.getTasks(maxNum);
6245     }
6246 
6247     @Override
getFilteredTasks(int maxNum, @ActivityType int ignoreActivityType, @WindowingMode int ignoreWindowingMode)6248     public List<RunningTaskInfo> getFilteredTasks(int maxNum, @ActivityType int ignoreActivityType,
6249             @WindowingMode int ignoreWindowingMode) {
6250         return mActivityTaskManager.getFilteredTasks(
6251                 maxNum, ignoreActivityType, ignoreWindowingMode);
6252     }
6253 
6254     @Override
cancelTaskWindowTransition(int taskId)6255     public void cancelTaskWindowTransition(int taskId) {
6256         mActivityTaskManager.cancelTaskWindowTransition(taskId);
6257     }
6258 
6259     @Override
setTaskResizeable(int taskId, int resizeableMode)6260     public void setTaskResizeable(int taskId, int resizeableMode) {
6261         mActivityTaskManager.setTaskResizeable(taskId, resizeableMode);
6262     }
6263 
6264     @Override
getTaskSnapshot(int taskId, boolean reducedResolution)6265     public ActivityManager.TaskSnapshot getTaskSnapshot(int taskId, boolean reducedResolution) {
6266         return mActivityTaskManager.getTaskSnapshot(taskId, reducedResolution);
6267     }
6268 
6269     @Override
resizeTask(int taskId, Rect bounds, int resizeMode)6270     public void resizeTask(int taskId, Rect bounds, int resizeMode) {
6271         mActivityTaskManager.resizeTask(taskId, bounds, resizeMode);
6272     }
6273 
6274     @Override
getTaskBounds(int taskId)6275     public Rect getTaskBounds(int taskId) {
6276         return mActivityTaskManager.getTaskBounds(taskId);
6277     }
6278 
6279     @Override
removeStack(int stackId)6280     public void removeStack(int stackId) {
6281         mActivityTaskManager.removeStack(stackId);
6282     }
6283 
6284     @Override
removeTask(int taskId)6285     public boolean removeTask(int taskId) {
6286         return mActivityTaskManager.removeTask(taskId);
6287     }
6288 
6289     @Override
moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId, int flags, Bundle bOptions)6290     public void moveTaskToFront(IApplicationThread appThread, String callingPackage, int taskId,
6291             int flags, Bundle bOptions) {
6292         mActivityTaskManager.moveTaskToFront(appThread, callingPackage, taskId, flags, bOptions);
6293     }
6294 
6295     /**
6296      * Attempts to move a task backwards in z-order (the order of activities within the task is
6297      * unchanged).
6298      *
6299      * There are several possible results of this call:
6300      * - if the task is locked, then we will show the lock toast
6301      * - if there is a task behind the provided task, then that task is made visible and resumed as
6302      *   this task is moved to the back
6303      * - otherwise, if there are no other tasks in the stack:
6304      *     - if this task is in the pinned stack, then we remove the stack completely, which will
6305      *       have the effect of moving the task to the top or bottom of the fullscreen stack
6306      *       (depending on whether it is visible)
6307      *     - otherwise, we simply return home and hide this task
6308      *
6309      * @param token A reference to the activity we wish to move
6310      * @param nonRoot If false then this only works if the activity is the root
6311      *                of a task; if true it will work for any activity in a task.
6312      * @return Returns true if the move completed, false if not.
6313      */
6314     @Override
moveActivityTaskToBack(IBinder token, boolean nonRoot)6315     public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
6316         return mActivityTaskManager.moveActivityTaskToBack(token, nonRoot);
6317     }
6318 
6319     @Override
moveTaskToStack(int taskId, int stackId, boolean toTop)6320     public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
6321         mActivityTaskManager.moveTaskToStack(taskId, stackId, toTop);
6322     }
6323 
6324     @Override
resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode, boolean preserveWindows, boolean animate, int animationDuration)6325     public void resizeStack(int stackId, Rect destBounds, boolean allowResizeInDockedMode,
6326             boolean preserveWindows, boolean animate, int animationDuration) {
6327         mActivityTaskManager.resizeStack(stackId, destBounds, allowResizeInDockedMode,
6328                 preserveWindows, animate, animationDuration);
6329     }
6330 
6331     @Override
getRecentTasks(int maxNum, int flags, int userId)6332     public ParceledListSlice<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags,
6333             int userId) {
6334         return mActivityTaskManager.getRecentTasks(maxNum, flags, userId);
6335     }
6336 
6337     /**
6338      * Moves the top activity in the input stackId to the pinned stack.
6339      *
6340      * @param stackId Id of stack to move the top activity to pinned stack.
6341      * @param bounds Bounds to use for pinned stack.
6342      *
6343      * @return True if the top activity of the input stack was successfully moved to the pinned
6344      *          stack.
6345      */
6346     @Override
moveTopActivityToPinnedStack(int stackId, Rect bounds)6347     public boolean moveTopActivityToPinnedStack(int stackId, Rect bounds) {
6348         return mActivityTaskManager.moveTopActivityToPinnedStack(stackId, bounds);
6349     }
6350 
6351     @Override
resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds, Rect tempDockedTaskInsetBounds, Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds)6352     public void resizeDockedStack(Rect dockedBounds, Rect tempDockedTaskBounds,
6353             Rect tempDockedTaskInsetBounds,
6354             Rect tempOtherTaskBounds, Rect tempOtherTaskInsetBounds) {
6355         mActivityTaskManager.resizeDockedStack(dockedBounds, tempDockedTaskBounds,
6356                 tempDockedTaskInsetBounds, tempOtherTaskBounds, tempOtherTaskInsetBounds);
6357     }
6358 
6359     @Override
positionTaskInStack(int taskId, int stackId, int position)6360     public void positionTaskInStack(int taskId, int stackId, int position) {
6361         mActivityTaskManager.positionTaskInStack(taskId, stackId, position);
6362     }
6363 
6364     @Override
getAllStackInfos()6365     public List<StackInfo> getAllStackInfos() {
6366         return mActivityTaskManager.getAllStackInfos();
6367     }
6368 
6369     @Override
getTaskForActivity(IBinder token, boolean onlyRoot)6370     public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6371         return mActivityTaskManager.getTaskForActivity(token, onlyRoot);
6372     }
6373 
6374     @Override
updateDeviceOwner(String packageName)6375     public void updateDeviceOwner(String packageName) {
6376         final int callingUid = Binder.getCallingUid();
6377         if (callingUid != 0 && callingUid != SYSTEM_UID) {
6378             throw new SecurityException("updateDeviceOwner called from non-system process");
6379         }
6380         synchronized (this) {
6381             mDeviceOwnerName = packageName;
6382         }
6383     }
6384 
6385     @Override
updateLockTaskPackages(int userId, String[] packages)6386     public void updateLockTaskPackages(int userId, String[] packages) {
6387         mActivityTaskManager.updateLockTaskPackages(userId, packages);
6388     }
6389 
6390     @Override
isInLockTaskMode()6391     public boolean isInLockTaskMode() {
6392         return mActivityTaskManager.isInLockTaskMode();
6393     }
6394 
6395     @Override
getLockTaskModeState()6396     public int getLockTaskModeState() {
6397         return mActivityTaskManager.getLockTaskModeState();
6398     }
6399 
6400     @Override
startSystemLockTaskMode(int taskId)6401     public void startSystemLockTaskMode(int taskId) throws RemoteException {
6402         mActivityTaskManager.startSystemLockTaskMode(taskId);
6403     }
6404 
6405     // =========================================================
6406     // CONTENT PROVIDERS
6407     // =========================================================
6408 
generateApplicationProvidersLocked(ProcessRecord app)6409     private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6410         List<ProviderInfo> providers = null;
6411         try {
6412             providers = AppGlobals.getPackageManager()
6413                     .queryContentProviders(app.processName, app.uid,
6414                             STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6415                                     | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
6416                     .getList();
6417         } catch (RemoteException ex) {
6418         }
6419         if (DEBUG_MU) Slog.v(TAG_MU,
6420                 "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6421         int userId = app.userId;
6422         if (providers != null) {
6423             int N = providers.size();
6424             app.pubProviders.ensureCapacity(N + app.pubProviders.size());
6425             for (int i=0; i<N; i++) {
6426                 // TODO: keep logic in sync with installEncryptionUnawareProviders
6427                 ProviderInfo cpi =
6428                     (ProviderInfo)providers.get(i);
6429                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6430                         cpi.name, cpi.flags);
6431                 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) {
6432                     // This is a singleton provider, but a user besides the
6433                     // default user is asking to initialize a process it runs
6434                     // in...  well, no, it doesn't actually run in this process,
6435                     // it runs in the process of the default user.  Get rid of it.
6436                     providers.remove(i);
6437                     N--;
6438                     i--;
6439                     continue;
6440                 }
6441 
6442                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
6443                 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
6444                 if (cpr == null) {
6445                     cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
6446                     mProviderMap.putProviderByClass(comp, cpr);
6447                 }
6448                 if (DEBUG_MU) Slog.v(TAG_MU,
6449                         "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
6450                 app.pubProviders.put(cpi.name, cpr);
6451                 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
6452                     // Don't add this if it is a platform component that is marked
6453                     // to run in multiple processes, because this is actually
6454                     // part of the framework so doesn't make sense to track as a
6455                     // separate apk in the process.
6456                     app.addPackage(cpi.applicationInfo.packageName,
6457                             cpi.applicationInfo.longVersionCode, mProcessStats);
6458                 }
6459                 notifyPackageUse(cpi.applicationInfo.packageName,
6460                                  PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
6461             }
6462         }
6463         return providers;
6464     }
6465 
6466     /**
6467      * Check if the calling UID has a possible chance at accessing the provider
6468      * at the given authority and user.
6469      */
checkContentProviderAccess(String authority, int userId)6470     public String checkContentProviderAccess(String authority, int userId) {
6471         if (userId == UserHandle.USER_ALL) {
6472             mContext.enforceCallingOrSelfPermission(
6473                     Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
6474             userId = UserHandle.getCallingUserId();
6475         }
6476 
6477         ProviderInfo cpi = null;
6478         try {
6479             cpi = AppGlobals.getPackageManager().resolveContentProvider(authority,
6480                     STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6481                             | PackageManager.MATCH_DISABLED_COMPONENTS
6482                             | PackageManager.MATCH_DIRECT_BOOT_AWARE
6483                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
6484                     userId);
6485         } catch (RemoteException ignored) {
6486         }
6487         if (cpi == null) {
6488             return "Failed to find provider " + authority + " for user " + userId
6489                     + "; expected to find a valid ContentProvider for this authority";
6490         }
6491 
6492         ProcessRecord r = null;
6493         synchronized (mPidsSelfLocked) {
6494             r = mPidsSelfLocked.get(Binder.getCallingPid());
6495         }
6496         if (r == null) {
6497             return "Failed to find PID " + Binder.getCallingPid();
6498         }
6499 
6500         synchronized (this) {
6501             return checkContentProviderPermissionLocked(cpi, r, userId, true);
6502         }
6503     }
6504 
6505     /**
6506      * Check if {@link ProcessRecord} has a possible chance at accessing the
6507      * given {@link ProviderInfo}. Final permission checking is always done
6508      * in {@link ContentProvider}.
6509      */
checkContentProviderPermissionLocked( ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser)6510     private final String checkContentProviderPermissionLocked(
6511             ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) {
6512         final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
6513         final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
6514         boolean checkedGrants = false;
6515         if (checkUser) {
6516             // Looking for cross-user grants before enforcing the typical cross-users permissions
6517             int tmpTargetUserId = mUserController.unsafeConvertIncomingUser(userId);
6518             if (tmpTargetUserId != UserHandle.getUserId(callingUid)) {
6519                 if (mUgmInternal.checkAuthorityGrants(
6520                         callingUid, cpi, tmpTargetUserId, checkUser)) {
6521                     return null;
6522                 }
6523                 checkedGrants = true;
6524             }
6525             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
6526                     ALLOW_NON_FULL, "checkContentProviderPermissionLocked " + cpi.authority, null);
6527             if (userId != tmpTargetUserId) {
6528                 // When we actually went to determine the final targer user ID, this ended
6529                 // up different than our initial check for the authority.  This is because
6530                 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to
6531                 // SELF.  So we need to re-check the grants again.
6532                 checkedGrants = false;
6533             }
6534         }
6535         if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
6536                 cpi.applicationInfo.uid, cpi.exported)
6537                 == PackageManager.PERMISSION_GRANTED) {
6538             return null;
6539         }
6540         if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
6541                 cpi.applicationInfo.uid, cpi.exported)
6542                 == PackageManager.PERMISSION_GRANTED) {
6543             return null;
6544         }
6545 
6546         PathPermission[] pps = cpi.pathPermissions;
6547         if (pps != null) {
6548             int i = pps.length;
6549             while (i > 0) {
6550                 i--;
6551                 PathPermission pp = pps[i];
6552                 String pprperm = pp.getReadPermission();
6553                 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid,
6554                         cpi.applicationInfo.uid, cpi.exported)
6555                         == PackageManager.PERMISSION_GRANTED) {
6556                     return null;
6557                 }
6558                 String ppwperm = pp.getWritePermission();
6559                 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid,
6560                         cpi.applicationInfo.uid, cpi.exported)
6561                         == PackageManager.PERMISSION_GRANTED) {
6562                     return null;
6563                 }
6564             }
6565         }
6566         if (!checkedGrants
6567                 && mUgmInternal.checkAuthorityGrants(callingUid, cpi, userId, checkUser)) {
6568             return null;
6569         }
6570 
6571         final String suffix;
6572         if (!cpi.exported) {
6573             suffix = " that is not exported from UID " + cpi.applicationInfo.uid;
6574         } else if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(cpi.readPermission)) {
6575             suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
6576         } else {
6577             suffix = " requires " + cpi.readPermission + " or " + cpi.writePermission;
6578         }
6579         final String msg = "Permission Denial: opening provider " + cpi.name
6580                 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6581                 + ", uid=" + callingUid + ")" + suffix;
6582         Slog.w(TAG, msg);
6583         return msg;
6584     }
6585 
incProviderCountLocked(ProcessRecord r, final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid, String callingPackage, String callingTag, boolean stable)6586     ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6587             final ContentProviderRecord cpr, IBinder externalProcessToken, int callingUid,
6588             String callingPackage, String callingTag, boolean stable) {
6589         if (r != null) {
6590             for (int i=0; i<r.conProviders.size(); i++) {
6591                 ContentProviderConnection conn = r.conProviders.get(i);
6592                 if (conn.provider == cpr) {
6593                     if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
6594                             "Adding provider requested by "
6595                             + r.processName + " from process "
6596                             + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6597                             + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6598                     if (stable) {
6599                         conn.stableCount++;
6600                         conn.numStableIncs++;
6601                     } else {
6602                         conn.unstableCount++;
6603                         conn.numUnstableIncs++;
6604                     }
6605                     return conn;
6606                 }
6607             }
6608             ContentProviderConnection conn = new ContentProviderConnection(cpr, r, callingPackage);
6609             conn.startAssociationIfNeeded();
6610             if (stable) {
6611                 conn.stableCount = 1;
6612                 conn.numStableIncs = 1;
6613             } else {
6614                 conn.unstableCount = 1;
6615                 conn.numUnstableIncs = 1;
6616             }
6617             cpr.connections.add(conn);
6618             r.conProviders.add(conn);
6619             startAssociationLocked(r.uid, r.processName, r.getCurProcState(),
6620                     cpr.uid, cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
6621             return conn;
6622         }
6623         cpr.addExternalProcessHandleLocked(externalProcessToken, callingUid, callingTag);
6624         return null;
6625     }
6626 
decProviderCountLocked(ContentProviderConnection conn, ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable)6627     boolean decProviderCountLocked(ContentProviderConnection conn,
6628             ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6629         if (conn != null) {
6630             cpr = conn.provider;
6631             if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER,
6632                     "Removing provider requested by "
6633                     + conn.client.processName + " from process "
6634                     + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6635                     + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6636             if (stable) {
6637                 conn.stableCount--;
6638             } else {
6639                 conn.unstableCount--;
6640             }
6641             if (conn.stableCount == 0 && conn.unstableCount == 0) {
6642                 conn.stopAssociation();
6643                 cpr.connections.remove(conn);
6644                 conn.client.conProviders.remove(conn);
6645                 if (conn.client.setProcState < PROCESS_STATE_LAST_ACTIVITY) {
6646                     // The client is more important than last activity -- note the time this
6647                     // is happening, so we keep the old provider process around a bit as last
6648                     // activity to avoid thrashing it.
6649                     if (cpr.proc != null) {
6650                         cpr.proc.lastProviderTime = SystemClock.uptimeMillis();
6651                     }
6652                 }
6653                 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid,
6654                         cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
6655                 return true;
6656             }
6657             return false;
6658         }
6659         cpr.removeExternalProcessHandleLocked(externalProcessToken);
6660         return false;
6661     }
6662 
checkTime(long startTime, String where)6663     void checkTime(long startTime, String where) {
6664         long now = SystemClock.uptimeMillis();
6665         if ((now-startTime) > 50) {
6666             // If we are taking more than 50ms, log about it.
6667             Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where);
6668         }
6669     }
6670 
6671     private static final int[] PROCESS_STATE_STATS_FORMAT = new int[] {
6672             PROC_SPACE_TERM,
6673             PROC_SPACE_TERM|PROC_PARENS,
6674             PROC_SPACE_TERM|PROC_CHAR|PROC_OUT_LONG,        // 3: process state
6675     };
6676 
6677     private final long[] mProcessStateStatsLongs = new long[1];
6678 
isProcessAliveLocked(ProcessRecord proc)6679     private boolean isProcessAliveLocked(ProcessRecord proc) {
6680         if (proc.pid <= 0) {
6681             if (DEBUG_OOM_ADJ) Slog.d(TAG, "Process hasn't started yet: " + proc);
6682             return false;
6683         }
6684         if (proc.procStatFile == null) {
6685             proc.procStatFile = "/proc/" + proc.pid + "/stat";
6686         }
6687         mProcessStateStatsLongs[0] = 0;
6688         if (!readProcFile(proc.procStatFile, PROCESS_STATE_STATS_FORMAT, null,
6689                 mProcessStateStatsLongs, null)) {
6690             if (DEBUG_OOM_ADJ) Slog.d(TAG, "UNABLE TO RETRIEVE STATE FOR " + proc.procStatFile);
6691             return false;
6692         }
6693         final long state = mProcessStateStatsLongs[0];
6694         if (DEBUG_OOM_ADJ) Slog.d(TAG, "RETRIEVED STATE FOR " + proc.procStatFile + ": "
6695                 + (char)state);
6696         return state != 'Z' && state != 'X' && state != 'x' && state != 'K';
6697     }
6698 
checkContentProviderAssociation(ProcessRecord callingApp, int callingUid, ProviderInfo cpi)6699     private String checkContentProviderAssociation(ProcessRecord callingApp, int callingUid,
6700             ProviderInfo cpi) {
6701         if (callingApp == null) {
6702             return validateAssociationAllowedLocked(cpi.packageName, cpi.applicationInfo.uid,
6703                     null, callingUid) ? null : "<null>";
6704         }
6705         for (int i = callingApp.pkgList.size() - 1; i >= 0; i--) {
6706             if (!validateAssociationAllowedLocked(callingApp.pkgList.keyAt(i), callingApp.uid,
6707                     cpi.packageName, cpi.applicationInfo.uid)) {
6708                 return cpi.packageName;
6709             }
6710         }
6711         return null;
6712     }
6713 
getContentProviderImpl(IApplicationThread caller, String name, IBinder token, int callingUid, String callingPackage, String callingTag, boolean stable, int userId)6714     private ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
6715             String name, IBinder token, int callingUid, String callingPackage, String callingTag,
6716             boolean stable, int userId) {
6717         ContentProviderRecord cpr;
6718         ContentProviderConnection conn = null;
6719         ProviderInfo cpi = null;
6720         boolean providerRunning = false;
6721 
6722         synchronized(this) {
6723             long startTime = SystemClock.uptimeMillis();
6724 
6725             ProcessRecord r = null;
6726             if (caller != null) {
6727                 r = getRecordForAppLocked(caller);
6728                 if (r == null) {
6729                     throw new SecurityException(
6730                             "Unable to find app for caller " + caller
6731                           + " (pid=" + Binder.getCallingPid()
6732                           + ") when getting content provider " + name);
6733                 }
6734             }
6735 
6736             boolean checkCrossUser = true;
6737 
6738             checkTime(startTime, "getContentProviderImpl: getProviderByName");
6739 
6740             // First check if this content provider has been published...
6741             cpr = mProviderMap.getProviderByName(name, userId);
6742             // If that didn't work, check if it exists for user 0 and then
6743             // verify that it's a singleton provider before using it.
6744             if (cpr == null && userId != UserHandle.USER_SYSTEM) {
6745                 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_SYSTEM);
6746                 if (cpr != null) {
6747                     cpi = cpr.info;
6748                     if (isSingleton(cpi.processName, cpi.applicationInfo,
6749                             cpi.name, cpi.flags)
6750                             && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) {
6751                         userId = UserHandle.USER_SYSTEM;
6752                         checkCrossUser = false;
6753                     } else {
6754                         cpr = null;
6755                         cpi = null;
6756                     }
6757                 }
6758             }
6759 
6760             if (cpr != null && cpr.proc != null) {
6761                 providerRunning = !cpr.proc.killed;
6762 
6763                 // Note if killedByAm is also set, this means the provider process has just been
6764                 // killed by AM (in ProcessRecord.kill()), but appDiedLocked() hasn't been called
6765                 // yet. So we need to call appDiedLocked() here and let it clean up.
6766                 // (See the commit message on I2c4ba1e87c2d47f2013befff10c49b3dc337a9a7 to see
6767                 // how to test this case.)
6768                 if (cpr.proc.killed && cpr.proc.killedByAm) {
6769                     checkTime(startTime, "getContentProviderImpl: before appDied (killedByAm)");
6770                     final long iden = Binder.clearCallingIdentity();
6771                     try {
6772                         appDiedLocked(cpr.proc);
6773                     } finally {
6774                         Binder.restoreCallingIdentity(iden);
6775                     }
6776                     checkTime(startTime, "getContentProviderImpl: after appDied (killedByAm)");
6777                 }
6778             }
6779 
6780             if (providerRunning) {
6781                 cpi = cpr.info;
6782                 String msg;
6783 
6784                 if (r != null && cpr.canRunHere(r)) {
6785                     if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
6786                         throw new SecurityException("Content provider lookup "
6787                                 + cpr.name.flattenToShortString()
6788                                 + " failed: association not allowed with package " + msg);
6789                     }
6790                     checkTime(startTime,
6791                             "getContentProviderImpl: before checkContentProviderPermission");
6792                     if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
6793                             != null) {
6794                         throw new SecurityException(msg);
6795                     }
6796                     checkTime(startTime,
6797                             "getContentProviderImpl: after checkContentProviderPermission");
6798 
6799                     // This provider has been published or is in the process
6800                     // of being published...  but it is also allowed to run
6801                     // in the caller's process, so don't make a connection
6802                     // and just let the caller instantiate its own instance.
6803                     ContentProviderHolder holder = cpr.newHolder(null);
6804                     // don't give caller the provider object, it needs
6805                     // to make its own.
6806                     holder.provider = null;
6807                     return holder;
6808                 }
6809 
6810                 // Don't expose providers between normal apps and instant apps
6811                 try {
6812                     if (AppGlobals.getPackageManager()
6813                             .resolveContentProvider(name, 0 /*flags*/, userId) == null) {
6814                         return null;
6815                     }
6816                 } catch (RemoteException e) {
6817                 }
6818 
6819                 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
6820                     throw new SecurityException("Content provider lookup "
6821                             + cpr.name.flattenToShortString()
6822                             + " failed: association not allowed with package " + msg);
6823                 }
6824                 checkTime(startTime,
6825                         "getContentProviderImpl: before checkContentProviderPermission");
6826                 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
6827                         != null) {
6828                     throw new SecurityException(msg);
6829                 }
6830                 checkTime(startTime,
6831                         "getContentProviderImpl: after checkContentProviderPermission");
6832 
6833                 final long origId = Binder.clearCallingIdentity();
6834 
6835                 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked");
6836 
6837                 // In this case the provider instance already exists, so we can
6838                 // return it right away.
6839                 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag,
6840                         stable);
6841                 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
6842                     if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_LOW_APP_ADJ) {
6843                         // If this is a perceptible app accessing the provider,
6844                         // make sure to count it as being accessed and thus
6845                         // back up on the LRU list.  This is good because
6846                         // content providers are often expensive to start.
6847                         checkTime(startTime, "getContentProviderImpl: before updateLruProcess");
6848                         mProcessList.updateLruProcessLocked(cpr.proc, false, null);
6849                         checkTime(startTime, "getContentProviderImpl: after updateLruProcess");
6850                     }
6851                 }
6852 
6853                 checkTime(startTime, "getContentProviderImpl: before updateOomAdj");
6854                 final int verifiedAdj = cpr.proc.verifiedAdj;
6855                 boolean success = updateOomAdjLocked(cpr.proc, true,
6856                         OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
6857                 // XXX things have changed so updateOomAdjLocked doesn't actually tell us
6858                 // if the process has been successfully adjusted.  So to reduce races with
6859                 // it, we will check whether the process still exists.  Note that this doesn't
6860                 // completely get rid of races with LMK killing the process, but should make
6861                 // them much smaller.
6862                 if (success && verifiedAdj != cpr.proc.setAdj && !isProcessAliveLocked(cpr.proc)) {
6863                     success = false;
6864                 }
6865                 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name);
6866                 checkTime(startTime, "getContentProviderImpl: after updateOomAdj");
6867                 if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success);
6868                 // NOTE: there is still a race here where a signal could be
6869                 // pending on the process even though we managed to update its
6870                 // adj level.  Not sure what to do about this, but at least
6871                 // the race is now smaller.
6872                 if (!success) {
6873                     // Uh oh...  it looks like the provider's process
6874                     // has been killed on us.  We need to wait for a new
6875                     // process to be started, and make sure its death
6876                     // doesn't kill our process.
6877                     Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString()
6878                             + " is crashing; detaching " + r);
6879                     boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
6880                     checkTime(startTime, "getContentProviderImpl: before appDied");
6881                     appDiedLocked(cpr.proc);
6882                     checkTime(startTime, "getContentProviderImpl: after appDied");
6883                     if (!lastRef) {
6884                         // This wasn't the last ref our process had on
6885                         // the provider...  we have now been killed, bail.
6886                         return null;
6887                     }
6888                     providerRunning = false;
6889                     conn = null;
6890                 } else {
6891                     cpr.proc.verifiedAdj = cpr.proc.setAdj;
6892                 }
6893 
6894                 Binder.restoreCallingIdentity(origId);
6895             }
6896 
6897             if (!providerRunning) {
6898                 try {
6899                     checkTime(startTime, "getContentProviderImpl: before resolveContentProvider");
6900                     cpi = AppGlobals.getPackageManager().
6901                         resolveContentProvider(name,
6902                             STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
6903                     checkTime(startTime, "getContentProviderImpl: after resolveContentProvider");
6904                 } catch (RemoteException ex) {
6905                 }
6906                 if (cpi == null) {
6907                     return null;
6908                 }
6909                 // If the provider is a singleton AND
6910                 // (it's a call within the same user || the provider is a
6911                 // privileged app)
6912                 // Then allow connecting to the singleton provider
6913                 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6914                         cpi.name, cpi.flags)
6915                         && isValidSingletonCall(r.uid, cpi.applicationInfo.uid);
6916                 if (singleton) {
6917                     userId = UserHandle.USER_SYSTEM;
6918                 }
6919                 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
6920                 checkTime(startTime, "getContentProviderImpl: got app info for user");
6921 
6922                 String msg;
6923                 if ((msg = checkContentProviderAssociation(r, callingUid, cpi)) != null) {
6924                     throw new SecurityException("Content provider lookup " + name
6925                             + " failed: association not allowed with package " + msg);
6926                 }
6927                 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission");
6928                 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton))
6929                         != null) {
6930                     throw new SecurityException(msg);
6931                 }
6932                 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission");
6933 
6934                 if (!mProcessesReady
6935                         && !cpi.processName.equals("system")) {
6936                     // If this content provider does not run in the system
6937                     // process, and the system is not yet ready to run other
6938                     // processes, then fail fast instead of hanging.
6939                     throw new IllegalArgumentException(
6940                             "Attempt to launch content provider before system ready");
6941                 }
6942 
6943                 // If system providers are not installed yet we aggressively crash to avoid
6944                 // creating multiple instance of these providers and then bad things happen!
6945                 if (!mSystemProvidersInstalled && cpi.applicationInfo.isSystemApp()
6946                         && "system".equals(cpi.processName)) {
6947                     throw new IllegalStateException("Cannot access system provider: '"
6948                             + cpi.authority + "' before system providers are installed!");
6949                 }
6950 
6951                 // Make sure that the user who owns this provider is running.  If not,
6952                 // we don't want to allow it to run.
6953                 if (!mUserController.isUserRunning(userId, 0)) {
6954                     Slog.w(TAG, "Unable to launch app "
6955                             + cpi.applicationInfo.packageName + "/"
6956                             + cpi.applicationInfo.uid + " for provider "
6957                             + name + ": user " + userId + " is stopped");
6958                     return null;
6959                 }
6960 
6961                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
6962                 checkTime(startTime, "getContentProviderImpl: before getProviderByClass");
6963                 cpr = mProviderMap.getProviderByClass(comp, userId);
6964                 checkTime(startTime, "getContentProviderImpl: after getProviderByClass");
6965                 final boolean firstClass = cpr == null;
6966                 if (firstClass) {
6967                     final long ident = Binder.clearCallingIdentity();
6968 
6969                     // If permissions need a review before any of the app components can run,
6970                     // we return no provider and launch a review activity if the calling app
6971                     // is in the foreground.
6972                     if (!requestTargetProviderPermissionsReviewIfNeededLocked(cpi, r, userId)) {
6973                         return null;
6974                     }
6975 
6976                     try {
6977                         checkTime(startTime, "getContentProviderImpl: before getApplicationInfo");
6978                         ApplicationInfo ai =
6979                             AppGlobals.getPackageManager().
6980                                 getApplicationInfo(
6981                                         cpi.applicationInfo.packageName,
6982                                         STOCK_PM_FLAGS, userId);
6983                         checkTime(startTime, "getContentProviderImpl: after getApplicationInfo");
6984                         if (ai == null) {
6985                             Slog.w(TAG, "No package info for content provider "
6986                                     + cpi.name);
6987                             return null;
6988                         }
6989                         ai = getAppInfoForUser(ai, userId);
6990                         cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
6991                     } catch (RemoteException ex) {
6992                         // pm is in same process, this will never happen.
6993                     } finally {
6994                         Binder.restoreCallingIdentity(ident);
6995                     }
6996                 }
6997 
6998                 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord");
6999 
7000                 if (r != null && cpr.canRunHere(r)) {
7001                     // If this is a multiprocess provider, then just return its
7002                     // info and allow the caller to instantiate it.  Only do
7003                     // this if the provider is the same user as the caller's
7004                     // process, or can run as root (so can be in any process).
7005                     return cpr.newHolder(null);
7006                 }
7007 
7008                 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid "
7009                             + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): "
7010                             + cpr.info.name + " callers=" + Debug.getCallers(6));
7011 
7012                 // This is single process, and our app is now connecting to it.
7013                 // See if we are already in the process of launching this
7014                 // provider.
7015                 final int N = mLaunchingProviders.size();
7016                 int i;
7017                 for (i = 0; i < N; i++) {
7018                     if (mLaunchingProviders.get(i) == cpr) {
7019                         break;
7020                     }
7021                 }
7022 
7023                 // If the provider is not already being launched, then get it
7024                 // started.
7025                 if (i >= N) {
7026                     final long origId = Binder.clearCallingIdentity();
7027 
7028                     try {
7029                         // Content provider is now in use, its package can't be stopped.
7030                         try {
7031                             checkTime(startTime, "getContentProviderImpl: before set stopped state");
7032                             AppGlobals.getPackageManager().setPackageStoppedState(
7033                                     cpr.appInfo.packageName, false, userId);
7034                             checkTime(startTime, "getContentProviderImpl: after set stopped state");
7035                         } catch (RemoteException e) {
7036                         } catch (IllegalArgumentException e) {
7037                             Slog.w(TAG, "Failed trying to unstop package "
7038                                     + cpr.appInfo.packageName + ": " + e);
7039                         }
7040 
7041                         // Use existing process if already started
7042                         checkTime(startTime, "getContentProviderImpl: looking for process record");
7043                         ProcessRecord proc = getProcessRecordLocked(
7044                                 cpi.processName, cpr.appInfo.uid, false);
7045                         if (proc != null && proc.thread != null && !proc.killed) {
7046                             if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER,
7047                                     "Installing in existing process " + proc);
7048                             if (!proc.pubProviders.containsKey(cpi.name)) {
7049                                 checkTime(startTime, "getContentProviderImpl: scheduling install");
7050                                 proc.pubProviders.put(cpi.name, cpr);
7051                                 try {
7052                                     proc.thread.scheduleInstallProvider(cpi);
7053                                 } catch (RemoteException e) {
7054                                 }
7055                             }
7056                         } else {
7057                             checkTime(startTime, "getContentProviderImpl: before start process");
7058                             proc = startProcessLocked(cpi.processName,
7059                                     cpr.appInfo, false, 0,
7060                                     new HostingRecord("content provider",
7061                                     new ComponentName(cpi.applicationInfo.packageName,
7062                                             cpi.name)), false, false, false);
7063                             checkTime(startTime, "getContentProviderImpl: after start process");
7064                             if (proc == null) {
7065                                 Slog.w(TAG, "Unable to launch app "
7066                                         + cpi.applicationInfo.packageName + "/"
7067                                         + cpi.applicationInfo.uid + " for provider "
7068                                         + name + ": process is bad");
7069                                 return null;
7070                             }
7071                         }
7072                         cpr.launchingApp = proc;
7073                         mLaunchingProviders.add(cpr);
7074                     } finally {
7075                         Binder.restoreCallingIdentity(origId);
7076                     }
7077                 }
7078 
7079                 checkTime(startTime, "getContentProviderImpl: updating data structures");
7080 
7081                 // Make sure the provider is published (the same provider class
7082                 // may be published under multiple names).
7083                 if (firstClass) {
7084                     mProviderMap.putProviderByClass(comp, cpr);
7085                 }
7086 
7087                 mProviderMap.putProviderByName(name, cpr);
7088                 conn = incProviderCountLocked(r, cpr, token, callingUid, callingPackage, callingTag,
7089                         stable);
7090                 if (conn != null) {
7091                     conn.waiting = true;
7092                 }
7093             }
7094             checkTime(startTime, "getContentProviderImpl: done!");
7095 
7096             grantEphemeralAccessLocked(userId, null /*intent*/,
7097                     UserHandle.getAppId(cpi.applicationInfo.uid),
7098                     UserHandle.getAppId(Binder.getCallingUid()));
7099         }
7100 
7101         // Wait for the provider to be published...
7102         final long timeout = SystemClock.uptimeMillis() + CONTENT_PROVIDER_WAIT_TIMEOUT;
7103         boolean timedOut = false;
7104         synchronized (cpr) {
7105             while (cpr.provider == null) {
7106                 if (cpr.launchingApp == null) {
7107                     Slog.w(TAG, "Unable to launch app "
7108                             + cpi.applicationInfo.packageName + "/"
7109                             + cpi.applicationInfo.uid + " for provider "
7110                             + name + ": launching app became null");
7111                     EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
7112                             UserHandle.getUserId(cpi.applicationInfo.uid),
7113                             cpi.applicationInfo.packageName,
7114                             cpi.applicationInfo.uid, name);
7115                     return null;
7116                 }
7117                 try {
7118                     final long wait = Math.max(0L, timeout - SystemClock.uptimeMillis());
7119                     if (DEBUG_MU) Slog.v(TAG_MU,
7120                             "Waiting to start provider " + cpr
7121                             + " launchingApp=" + cpr.launchingApp + " for " + wait + " ms");
7122                     if (conn != null) {
7123                         conn.waiting = true;
7124                     }
7125                     cpr.wait(wait);
7126                     if (cpr.provider == null) {
7127                         timedOut = true;
7128                         break;
7129                     }
7130                 } catch (InterruptedException ex) {
7131                 } finally {
7132                     if (conn != null) {
7133                         conn.waiting = false;
7134                     }
7135                 }
7136             }
7137         }
7138         if (timedOut) {
7139             // Note we do it afer releasing the lock.
7140             String callerName = "unknown";
7141             synchronized (this) {
7142                 final ProcessRecord record = mProcessList.getLRURecordForAppLocked(caller);
7143                 if (record != null) {
7144                     callerName = record.processName;
7145                 }
7146             }
7147 
7148             Slog.wtf(TAG, "Timeout waiting for provider "
7149                     + cpi.applicationInfo.packageName + "/"
7150                     + cpi.applicationInfo.uid + " for provider "
7151                     + name
7152                     + " providerRunning=" + providerRunning
7153                     + " caller=" + callerName + "/" + Binder.getCallingUid());
7154             return null;
7155         }
7156 
7157         return cpr.newHolder(conn);
7158     }
7159 
7160     private static final class StartActivityRunnable implements Runnable {
7161         private final Context mContext;
7162         private final Intent mIntent;
7163         private final UserHandle mUserHandle;
7164 
StartActivityRunnable(Context context, Intent intent, UserHandle userHandle)7165         StartActivityRunnable(Context context, Intent intent, UserHandle userHandle) {
7166             this.mContext = context;
7167             this.mIntent = intent;
7168             this.mUserHandle = userHandle;
7169         }
7170 
7171         @Override
run()7172         public void run() {
7173             mContext.startActivityAsUser(mIntent, mUserHandle);
7174         }
7175     }
7176 
requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi, ProcessRecord r, final int userId)7177     private boolean requestTargetProviderPermissionsReviewIfNeededLocked(ProviderInfo cpi,
7178             ProcessRecord r, final int userId) {
7179         if (getPackageManagerInternalLocked().isPermissionsReviewRequired(
7180                 cpi.packageName, userId)) {
7181 
7182             final boolean callerForeground = r == null || r.setSchedGroup
7183                     != ProcessList.SCHED_GROUP_BACKGROUND;
7184 
7185             // Show a permission review UI only for starting from a foreground app
7186             if (!callerForeground) {
7187                 Slog.w(TAG, "u" + userId + " Instantiating a provider in package"
7188                         + cpi.packageName + " requires a permissions review");
7189                 return false;
7190             }
7191 
7192             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
7193             intent.addFlags(FLAG_ACTIVITY_NEW_TASK
7194                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
7195             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, cpi.packageName);
7196 
7197             if (DEBUG_PERMISSIONS_REVIEW) {
7198                 Slog.i(TAG, "u" + userId + " Launching permission review "
7199                         + "for package " + cpi.packageName);
7200             }
7201 
7202             final UserHandle userHandle = new UserHandle(userId);
7203             mHandler.post(new StartActivityRunnable(mContext, intent, userHandle));
7204 
7205             return false;
7206         }
7207 
7208         return true;
7209     }
7210 
7211     /**
7212      * Returns the PackageManager. Used by classes hosted by {@link ActivityManagerService}. The
7213      * PackageManager could be unavailable at construction time and therefore needs to be accessed
7214      * on demand.
7215      */
7216     @VisibleForTesting
getPackageManager()7217     public IPackageManager getPackageManager() {
7218         return AppGlobals.getPackageManager();
7219     }
7220 
7221     @VisibleForTesting
getPackageManagerInternalLocked()7222     public PackageManagerInternal getPackageManagerInternalLocked() {
7223         if (mPackageManagerInt == null) {
7224             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
7225         }
7226         return mPackageManagerInt;
7227     }
7228 
7229     @Override
getContentProvider( IApplicationThread caller, String callingPackage, String name, int userId, boolean stable)7230     public final ContentProviderHolder getContentProvider(
7231             IApplicationThread caller, String callingPackage, String name, int userId,
7232             boolean stable) {
7233         enforceNotIsolatedCaller("getContentProvider");
7234         if (caller == null) {
7235             String msg = "null IApplicationThread when getting content provider "
7236                     + name;
7237             Slog.w(TAG, msg);
7238             throw new SecurityException(msg);
7239         }
7240         // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal
7241         // with cross-user grant.
7242         final int callingUid = Binder.getCallingUid();
7243         if (callingPackage != null && mAppOpsService.checkPackage(callingUid, callingPackage)
7244                 != AppOpsManager.MODE_ALLOWED) {
7245             throw new SecurityException("Given calling package " + callingPackage
7246                     + " does not match caller's uid " + callingUid);
7247         }
7248         return getContentProviderImpl(caller, name, null, callingUid, callingPackage,
7249                 null, stable, userId);
7250     }
7251 
getContentProviderExternal( String name, int userId, IBinder token, String tag)7252     public ContentProviderHolder getContentProviderExternal(
7253             String name, int userId, IBinder token, String tag) {
7254         enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
7255             "Do not have permission in call getContentProviderExternal()");
7256         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
7257                 userId, false, ALLOW_FULL_ONLY, "getContentProvider", null);
7258         return getContentProviderExternalUnchecked(name, token, Binder.getCallingUid(),
7259                 tag != null ? tag : "*external*", userId);
7260     }
7261 
getContentProviderExternalUnchecked(String name, IBinder token, int callingUid, String callingTag, int userId)7262     private ContentProviderHolder getContentProviderExternalUnchecked(String name,
7263             IBinder token, int callingUid, String callingTag, int userId) {
7264         return getContentProviderImpl(null, name, token, callingUid, null, callingTag,
7265                 true, userId);
7266     }
7267 
7268     /**
7269      * Drop a content provider from a ProcessRecord's bookkeeping
7270      */
removeContentProvider(IBinder connection, boolean stable)7271     public void removeContentProvider(IBinder connection, boolean stable) {
7272         enforceNotIsolatedCaller("removeContentProvider");
7273         long ident = Binder.clearCallingIdentity();
7274         try {
7275             synchronized (this) {
7276                 ContentProviderConnection conn;
7277                 try {
7278                     conn = (ContentProviderConnection)connection;
7279                 } catch (ClassCastException e) {
7280                     String msg ="removeContentProvider: " + connection
7281                             + " not a ContentProviderConnection";
7282                     Slog.w(TAG, msg);
7283                     throw new IllegalArgumentException(msg);
7284                 }
7285                 if (conn == null) {
7286                     throw new NullPointerException("connection is null");
7287                 }
7288                 if (decProviderCountLocked(conn, null, null, stable)) {
7289                     updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER);
7290                 }
7291             }
7292         } finally {
7293             Binder.restoreCallingIdentity(ident);
7294         }
7295     }
7296 
7297     /** @deprecated - Use {@link #removeContentProviderExternalAsUser} which takes a user ID. */
7298     @Deprecated
7299     @Override
removeContentProviderExternal(String name, IBinder token)7300     public void removeContentProviderExternal(String name, IBinder token) {
7301         removeContentProviderExternalAsUser(name, token, UserHandle.getCallingUserId());
7302     }
7303 
7304     @Override
removeContentProviderExternalAsUser(String name, IBinder token, int userId)7305     public void removeContentProviderExternalAsUser(String name, IBinder token, int userId) {
7306         enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
7307             "Do not have permission in call removeContentProviderExternal()");
7308         long ident = Binder.clearCallingIdentity();
7309         try {
7310             removeContentProviderExternalUnchecked(name, token, userId);
7311         } finally {
7312             Binder.restoreCallingIdentity(ident);
7313         }
7314     }
7315 
removeContentProviderExternalUnchecked(String name, IBinder token, int userId)7316     private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
7317         synchronized (this) {
7318             ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
7319             if(cpr == null) {
7320                 //remove from mProvidersByClass
7321                 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list");
7322                 return;
7323             }
7324 
7325             //update content provider record entry info
7326             ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
7327             ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
7328             if (localCpr.hasExternalProcessHandles()) {
7329                 if (localCpr.removeExternalProcessHandleLocked(token)) {
7330                     updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_REMOVE_PROVIDER);
7331                 } else {
7332                     Slog.e(TAG, "Attmpt to remove content provider " + localCpr
7333                             + " with no external reference for token: "
7334                             + token + ".");
7335                 }
7336             } else {
7337                 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
7338                         + " with no external references.");
7339             }
7340         }
7341     }
7342 
publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)7343     public final void publishContentProviders(IApplicationThread caller,
7344             List<ContentProviderHolder> providers) {
7345         if (providers == null) {
7346             return;
7347         }
7348 
7349         enforceNotIsolatedCaller("publishContentProviders");
7350         synchronized (this) {
7351             final ProcessRecord r = getRecordForAppLocked(caller);
7352             if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
7353             if (r == null) {
7354                 throw new SecurityException(
7355                         "Unable to find app for caller " + caller
7356                       + " (pid=" + Binder.getCallingPid()
7357                       + ") when publishing content providers");
7358             }
7359 
7360             final long origId = Binder.clearCallingIdentity();
7361 
7362             final int N = providers.size();
7363             for (int i = 0; i < N; i++) {
7364                 ContentProviderHolder src = providers.get(i);
7365                 if (src == null || src.info == null || src.provider == null) {
7366                     continue;
7367                 }
7368                 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
7369                 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
7370                 if (dst != null) {
7371                     ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
7372                     mProviderMap.putProviderByClass(comp, dst);
7373                     String names[] = dst.info.authority.split(";");
7374                     for (int j = 0; j < names.length; j++) {
7375                         mProviderMap.putProviderByName(names[j], dst);
7376                     }
7377 
7378                     int launchingCount = mLaunchingProviders.size();
7379                     int j;
7380                     boolean wasInLaunchingProviders = false;
7381                     for (j = 0; j < launchingCount; j++) {
7382                         if (mLaunchingProviders.get(j) == dst) {
7383                             mLaunchingProviders.remove(j);
7384                             wasInLaunchingProviders = true;
7385                             j--;
7386                             launchingCount--;
7387                         }
7388                     }
7389                     if (wasInLaunchingProviders) {
7390                         mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
7391                     }
7392                     // Make sure the package is associated with the process.
7393                     // XXX We shouldn't need to do this, since we have added the package
7394                     // when we generated the providers in generateApplicationProvidersLocked().
7395                     // But for some reason in some cases we get here with the package no longer
7396                     // added...  for now just patch it in to make things happy.
7397                     r.addPackage(dst.info.applicationInfo.packageName,
7398                             dst.info.applicationInfo.longVersionCode, mProcessStats);
7399                     synchronized (dst) {
7400                         dst.provider = src.provider;
7401                         dst.setProcess(r);
7402                         dst.notifyAll();
7403                     }
7404                     updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
7405                     maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
7406                             src.info.authority);
7407                 }
7408             }
7409 
7410             Binder.restoreCallingIdentity(origId);
7411         }
7412     }
7413 
refContentProvider(IBinder connection, int stable, int unstable)7414     public boolean refContentProvider(IBinder connection, int stable, int unstable) {
7415         ContentProviderConnection conn;
7416         try {
7417             conn = (ContentProviderConnection)connection;
7418         } catch (ClassCastException e) {
7419             String msg ="refContentProvider: " + connection
7420                     + " not a ContentProviderConnection";
7421             Slog.w(TAG, msg);
7422             throw new IllegalArgumentException(msg);
7423         }
7424         if (conn == null) {
7425             throw new NullPointerException("connection is null");
7426         }
7427 
7428         synchronized (this) {
7429             if (stable > 0) {
7430                 conn.numStableIncs += stable;
7431             }
7432             stable = conn.stableCount + stable;
7433             if (stable < 0) {
7434                 throw new IllegalStateException("stableCount < 0: " + stable);
7435             }
7436 
7437             if (unstable > 0) {
7438                 conn.numUnstableIncs += unstable;
7439             }
7440             unstable = conn.unstableCount + unstable;
7441             if (unstable < 0) {
7442                 throw new IllegalStateException("unstableCount < 0: " + unstable);
7443             }
7444 
7445             if ((stable+unstable) <= 0) {
7446                 throw new IllegalStateException("ref counts can't go to zero here: stable="
7447                         + stable + " unstable=" + unstable);
7448             }
7449             conn.stableCount = stable;
7450             conn.unstableCount = unstable;
7451             return !conn.dead;
7452         }
7453     }
7454 
unstableProviderDied(IBinder connection)7455     public void unstableProviderDied(IBinder connection) {
7456         ContentProviderConnection conn;
7457         try {
7458             conn = (ContentProviderConnection)connection;
7459         } catch (ClassCastException e) {
7460             String msg ="refContentProvider: " + connection
7461                     + " not a ContentProviderConnection";
7462             Slog.w(TAG, msg);
7463             throw new IllegalArgumentException(msg);
7464         }
7465         if (conn == null) {
7466             throw new NullPointerException("connection is null");
7467         }
7468 
7469         // Safely retrieve the content provider associated with the connection.
7470         IContentProvider provider;
7471         synchronized (this) {
7472             provider = conn.provider.provider;
7473         }
7474 
7475         if (provider == null) {
7476             // Um, yeah, we're way ahead of you.
7477             return;
7478         }
7479 
7480         // Make sure the caller is being honest with us.
7481         if (provider.asBinder().pingBinder()) {
7482             // Er, no, still looks good to us.
7483             synchronized (this) {
7484                 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
7485                         + " says " + conn + " died, but we don't agree");
7486                 return;
7487             }
7488         }
7489 
7490         // Well look at that!  It's dead!
7491         synchronized (this) {
7492             if (conn.provider.provider != provider) {
7493                 // But something changed...  good enough.
7494                 return;
7495             }
7496 
7497             ProcessRecord proc = conn.provider.proc;
7498             if (proc == null || proc.thread == null) {
7499                 // Seems like the process is already cleaned up.
7500                 return;
7501             }
7502 
7503             // As far as we're concerned, this is just like receiving a
7504             // death notification...  just a bit prematurely.
7505             reportUidInfoMessageLocked(TAG,
7506                     "Process " + proc.processName + " (pid " + proc.pid
7507                             + ") early provider death",
7508                     proc.info.uid);
7509             final long ident = Binder.clearCallingIdentity();
7510             try {
7511                 appDiedLocked(proc);
7512             } finally {
7513                 Binder.restoreCallingIdentity(ident);
7514             }
7515         }
7516     }
7517 
7518     @Override
appNotRespondingViaProvider(IBinder connection)7519     public void appNotRespondingViaProvider(IBinder connection) {
7520         enforceCallingPermission(REMOVE_TASKS, "appNotRespondingViaProvider()");
7521 
7522         final ContentProviderConnection conn = (ContentProviderConnection) connection;
7523         if (conn == null) {
7524             Slog.w(TAG, "ContentProviderConnection is null");
7525             return;
7526         }
7527 
7528         final ProcessRecord host = conn.provider.proc;
7529         if (host == null) {
7530             Slog.w(TAG, "Failed to find hosting ProcessRecord");
7531             return;
7532         }
7533 
7534         mHandler.post(new Runnable() {
7535             @Override
7536             public void run() {
7537                 host.appNotResponding(
7538                         null, null, null, null, false, "ContentProvider not responding");
7539             }
7540         });
7541     }
7542 
installSystemProviders()7543     public final void installSystemProviders() {
7544         List<ProviderInfo> providers;
7545         synchronized (this) {
7546             ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
7547             providers = generateApplicationProvidersLocked(app);
7548             if (providers != null) {
7549                 for (int i=providers.size()-1; i>=0; i--) {
7550                     ProviderInfo pi = (ProviderInfo)providers.get(i);
7551                     if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7552                         Slog.w(TAG, "Not installing system proc provider " + pi.name
7553                                 + ": not system .apk");
7554                         providers.remove(i);
7555                     }
7556                 }
7557             }
7558         }
7559         if (providers != null) {
7560             mSystemThread.installSystemProviders(providers);
7561         }
7562 
7563         synchronized (this) {
7564             mSystemProvidersInstalled = true;
7565         }
7566         mConstants.start(mContext.getContentResolver());
7567         mCoreSettingsObserver = new CoreSettingsObserver(this);
7568         mActivityTaskManager.installSystemProviders();
7569         mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
7570         SettingsToPropertiesMapper.start(mContext.getContentResolver());
7571         mOomAdjuster.initSettings();
7572 
7573         // Now that the settings provider is published we can consider sending
7574         // in a rescue party.
7575         RescueParty.onSettingsProviderPublished(mContext);
7576 
7577         //mUsageStatsService.monitorPackages();
7578     }
7579 
startPersistentApps(int matchFlags)7580     void startPersistentApps(int matchFlags) {
7581         if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
7582 
7583         synchronized (this) {
7584             try {
7585                 final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
7586                         .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
7587                 for (ApplicationInfo app : apps) {
7588                     if (!"android".equals(app.packageName)) {
7589                         addAppLocked(app, null, false, null /* ABI override */);
7590                     }
7591                 }
7592             } catch (RemoteException ex) {
7593             }
7594         }
7595     }
7596 
7597     /**
7598      * When a user is unlocked, we need to install encryption-unaware providers
7599      * belonging to any running apps.
7600      */
installEncryptionUnawareProviders(int userId)7601     void installEncryptionUnawareProviders(int userId) {
7602         // We're only interested in providers that are encryption unaware, and
7603         // we don't care about uninstalled apps, since there's no way they're
7604         // running at this point.
7605         final int matchFlags = GET_PROVIDERS | MATCH_DIRECT_BOOT_UNAWARE;
7606 
7607         synchronized (this) {
7608             final int NP = mProcessList.mProcessNames.getMap().size();
7609             for (int ip = 0; ip < NP; ip++) {
7610                 final SparseArray<ProcessRecord> apps = mProcessList.mProcessNames.getMap().valueAt
7611                         (ip);
7612                 final int NA = apps.size();
7613                 for (int ia = 0; ia < NA; ia++) {
7614                     final ProcessRecord app = apps.valueAt(ia);
7615                     if (app.userId != userId || app.thread == null || app.unlocked) continue;
7616 
7617                     final int NG = app.pkgList.size();
7618                     for (int ig = 0; ig < NG; ig++) {
7619                         try {
7620                             final String pkgName = app.pkgList.keyAt(ig);
7621                             final PackageInfo pkgInfo = AppGlobals.getPackageManager()
7622                                     .getPackageInfo(pkgName, matchFlags, userId);
7623                             if (pkgInfo != null && !ArrayUtils.isEmpty(pkgInfo.providers)) {
7624                                 for (ProviderInfo pi : pkgInfo.providers) {
7625                                     // TODO: keep in sync with generateApplicationProvidersLocked
7626                                     final boolean processMatch = Objects.equals(pi.processName,
7627                                             app.processName) || pi.multiprocess;
7628                                     final boolean userMatch = isSingleton(pi.processName,
7629                                             pi.applicationInfo, pi.name, pi.flags)
7630                                                     ? (app.userId == UserHandle.USER_SYSTEM) : true;
7631                                     if (processMatch && userMatch) {
7632                                         Log.v(TAG, "Installing " + pi);
7633                                         app.thread.scheduleInstallProvider(pi);
7634                                     } else {
7635                                         Log.v(TAG, "Skipping " + pi);
7636                                     }
7637                                 }
7638                             }
7639                         } catch (RemoteException ignored) {
7640                         }
7641                     }
7642                 }
7643             }
7644         }
7645     }
7646 
7647     /**
7648      * Allows apps to retrieve the MIME type of a URI.
7649      * If an app is in the same user as the ContentProvider, or if it is allowed to interact across
7650      * users, then it does not need permission to access the ContentProvider.
7651      * Either, it needs cross-user uri grants.
7652      *
7653      * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7654      *
7655      * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7656      *     src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7657      */
getProviderMimeType(Uri uri, int userId)7658     public String getProviderMimeType(Uri uri, int userId) {
7659         enforceNotIsolatedCaller("getProviderMimeType");
7660         final String name = uri.getAuthority();
7661         int callingUid = Binder.getCallingUid();
7662         int callingPid = Binder.getCallingPid();
7663         long ident = 0;
7664         boolean clearedIdentity = false;
7665         userId = mUserController.unsafeConvertIncomingUser(userId);
7666         if (canClearIdentity(callingPid, callingUid, userId)) {
7667             clearedIdentity = true;
7668             ident = Binder.clearCallingIdentity();
7669         }
7670         ContentProviderHolder holder = null;
7671         try {
7672             holder = getContentProviderExternalUnchecked(name, null, callingUid,
7673                     "*getmimetype*", userId);
7674             if (holder != null) {
7675                 return holder.provider.getType(uri);
7676             }
7677         } catch (RemoteException e) {
7678             Log.w(TAG, "Content provider dead retrieving " + uri, e);
7679             return null;
7680         } catch (Exception e) {
7681             Log.w(TAG, "Exception while determining type of " + uri, e);
7682             return null;
7683         } finally {
7684             // We need to clear the identity to call removeContentProviderExternalUnchecked
7685             if (!clearedIdentity) {
7686                 ident = Binder.clearCallingIdentity();
7687             }
7688             try {
7689                 if (holder != null) {
7690                     removeContentProviderExternalUnchecked(name, null, userId);
7691                 }
7692             } finally {
7693                 Binder.restoreCallingIdentity(ident);
7694             }
7695         }
7696 
7697         return null;
7698     }
7699 
canClearIdentity(int callingPid, int callingUid, int userId)7700     private boolean canClearIdentity(int callingPid, int callingUid, int userId) {
7701         if (UserHandle.getUserId(callingUid) == userId) {
7702             return true;
7703         }
7704         if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
7705                 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED
7706                 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
7707                 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
7708                 return true;
7709         }
7710         return false;
7711     }
7712 
7713     // =========================================================
7714     // GLOBAL MANAGEMENT
7715     // =========================================================
7716 
uidOnBackgroundWhitelist(final int uid)7717     private boolean uidOnBackgroundWhitelist(final int uid) {
7718         final int appId = UserHandle.getAppId(uid);
7719         final int[] whitelist = mBackgroundAppIdWhitelist;
7720         final int N = whitelist.length;
7721         for (int i = 0; i < N; i++) {
7722             if (appId == whitelist[i]) {
7723                 return true;
7724             }
7725         }
7726         return false;
7727     }
7728 
7729     @Override
isBackgroundRestricted(String packageName)7730     public boolean isBackgroundRestricted(String packageName) {
7731         final int callingUid = Binder.getCallingUid();
7732         final IPackageManager pm = AppGlobals.getPackageManager();
7733         try {
7734             final int packageUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING,
7735                     UserHandle.getUserId(callingUid));
7736             if (packageUid != callingUid) {
7737                 throw new IllegalArgumentException("Uid " + callingUid
7738                         + " cannot query restriction state for package " + packageName);
7739             }
7740         } catch (RemoteException exc) {
7741             // Ignore.
7742         }
7743         return isBackgroundRestrictedNoCheck(callingUid, packageName);
7744     }
7745 
isBackgroundRestrictedNoCheck(final int uid, final String packageName)7746     boolean isBackgroundRestrictedNoCheck(final int uid, final String packageName) {
7747         final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
7748                 uid, packageName);
7749         return mode != AppOpsManager.MODE_ALLOWED;
7750     }
7751 
7752     @Override
backgroundWhitelistUid(final int uid)7753     public void backgroundWhitelistUid(final int uid) {
7754         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7755             throw new SecurityException("Only the OS may call backgroundWhitelistUid()");
7756         }
7757 
7758         if (DEBUG_BACKGROUND_CHECK) {
7759             Slog.i(TAG, "Adding uid " + uid + " to bg uid whitelist");
7760         }
7761         synchronized (this) {
7762             final int N = mBackgroundAppIdWhitelist.length;
7763             int[] newList = new int[N+1];
7764             System.arraycopy(mBackgroundAppIdWhitelist, 0, newList, 0, N);
7765             newList[N] = UserHandle.getAppId(uid);
7766             mBackgroundAppIdWhitelist = newList;
7767         }
7768     }
7769 
7770     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, String abiOverride)7771     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7772             String abiOverride) {
7773         return addAppLocked(info, customProcess, isolated, false /* disableHiddenApiChecks */,
7774                 false /* mountExtStorageFull */, abiOverride);
7775     }
7776 
7777     // TODO: Move to ProcessList?
7778     @GuardedBy("this")
addAppLocked(ApplicationInfo info, String customProcess, boolean isolated, boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride)7779     final ProcessRecord addAppLocked(ApplicationInfo info, String customProcess, boolean isolated,
7780             boolean disableHiddenApiChecks, boolean mountExtStorageFull, String abiOverride) {
7781         ProcessRecord app;
7782         if (!isolated) {
7783             app = getProcessRecordLocked(customProcess != null ? customProcess : info.processName,
7784                     info.uid, true);
7785         } else {
7786             app = null;
7787         }
7788 
7789         if (app == null) {
7790             app = mProcessList.newProcessRecordLocked(info, customProcess, isolated, 0,
7791                     new HostingRecord("added application",
7792                             customProcess != null ? customProcess : info.processName));
7793             mProcessList.updateLruProcessLocked(app, false, null);
7794             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_BEGIN);
7795         }
7796 
7797         // This package really, really can not be stopped.
7798         try {
7799             AppGlobals.getPackageManager().setPackageStoppedState(
7800                     info.packageName, false, UserHandle.getUserId(app.uid));
7801         } catch (RemoteException e) {
7802         } catch (IllegalArgumentException e) {
7803             Slog.w(TAG, "Failed trying to unstop package "
7804                     + info.packageName + ": " + e);
7805         }
7806 
7807         if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) {
7808             app.setPersistent(true);
7809             app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
7810         }
7811         if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7812             mPersistentStartingProcesses.add(app);
7813             mProcessList.startProcessLocked(app, new HostingRecord("added application",
7814                     customProcess != null ? customProcess : app.processName),
7815                     disableHiddenApiChecks, mountExtStorageFull, abiOverride);
7816         }
7817 
7818         return app;
7819     }
7820 
unhandledBack()7821     public void unhandledBack() {
7822         mActivityTaskManager.unhandledBack();
7823     }
7824 
openContentUri(String uriString)7825     public ParcelFileDescriptor openContentUri(String uriString) throws RemoteException {
7826         enforceNotIsolatedCaller("openContentUri");
7827         final int userId = UserHandle.getCallingUserId();
7828         final Uri uri = Uri.parse(uriString);
7829         String name = uri.getAuthority();
7830         ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null,
7831                 Binder.getCallingUid(), "*opencontent*", userId);
7832         ParcelFileDescriptor pfd = null;
7833         if (cph != null) {
7834             // We record the binder invoker's uid in thread-local storage before
7835             // going to the content provider to open the file.  Later, in the code
7836             // that handles all permissions checks, we look for this uid and use
7837             // that rather than the Activity Manager's own uid.  The effect is that
7838             // we do the check against the caller's permissions even though it looks
7839             // to the content provider like the Activity Manager itself is making
7840             // the request.
7841             Binder token = new Binder();
7842             sCallerIdentity.set(new Identity(
7843                     token, Binder.getCallingPid(), Binder.getCallingUid()));
7844             try {
7845                 pfd = cph.provider.openFile(null, uri, "r", null, token);
7846             } catch (FileNotFoundException e) {
7847                 // do nothing; pfd will be returned null
7848             } finally {
7849                 // Ensure that whatever happens, we clean up the identity state
7850                 sCallerIdentity.remove();
7851                 // Ensure we're done with the provider.
7852                 removeContentProviderExternalUnchecked(name, null, userId);
7853             }
7854         } else {
7855             Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
7856         }
7857         return pfd;
7858     }
7859 
reportGlobalUsageEventLocked(int event)7860     void reportGlobalUsageEventLocked(int event) {
7861         mUsageStatsService.reportEvent("android", mUserController.getCurrentUserId(), event);
7862         int[] profiles = mUserController.getCurrentProfileIds();
7863         if (profiles != null) {
7864             for (int i = profiles.length - 1; i >= 0; i--) {
7865                 mUsageStatsService.reportEvent((String)null, profiles[i], event);
7866             }
7867         }
7868     }
7869 
reportCurWakefulnessUsageEventLocked()7870     void reportCurWakefulnessUsageEventLocked() {
7871         reportGlobalUsageEventLocked(mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE
7872                 ? UsageEvents.Event.SCREEN_INTERACTIVE
7873                 : UsageEvents.Event.SCREEN_NON_INTERACTIVE);
7874     }
7875 
onWakefulnessChanged(int wakefulness)7876     void onWakefulnessChanged(int wakefulness) {
7877         synchronized(this) {
7878             boolean wasAwake = mWakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
7879             boolean isAwake = wakefulness == PowerManagerInternal.WAKEFULNESS_AWAKE;
7880             mWakefulness = wakefulness;
7881 
7882             if (wasAwake != isAwake) {
7883                 // Also update state in a special way for running foreground services UI.
7884                 mServices.updateScreenStateLocked(isAwake);
7885                 reportCurWakefulnessUsageEventLocked();
7886                 mActivityTaskManager.onScreenAwakeChanged(isAwake);
7887                 mOomAdjProfiler.onWakefulnessChanged(wakefulness);
7888             }
7889             updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
7890         }
7891     }
7892 
7893     @Override
notifyCleartextNetwork(int uid, byte[] firstPacket)7894     public void notifyCleartextNetwork(int uid, byte[] firstPacket) {
7895         mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget();
7896     }
7897 
7898     @Override
shutdown(int timeout)7899     public boolean shutdown(int timeout) {
7900         if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7901                 != PackageManager.PERMISSION_GRANTED) {
7902             throw new SecurityException("Requires permission "
7903                     + android.Manifest.permission.SHUTDOWN);
7904         }
7905 
7906         final boolean timedout = mAtmInternal.shuttingDown(mBooted, timeout);
7907 
7908         mAppOpsService.shutdown();
7909         if (mUsageStatsService != null) {
7910             mUsageStatsService.prepareShutdown();
7911         }
7912         mBatteryStatsService.shutdown();
7913         synchronized (this) {
7914             mProcessStats.shutdownLocked();
7915         }
7916 
7917         return timedout;
7918     }
7919 
7920     @Override
notifyLockedProfile(@serIdInt int userId)7921     public void notifyLockedProfile(@UserIdInt int userId) {
7922         mAtmInternal.notifyLockedProfile(userId, mUserController.getCurrentUserId());
7923     }
7924 
7925     @Override
startConfirmDeviceCredentialIntent(Intent intent, Bundle options)7926     public void startConfirmDeviceCredentialIntent(Intent intent, Bundle options) {
7927         mAtmInternal.startConfirmDeviceCredentialIntent(intent, options);
7928     }
7929 
7930     @Override
stopAppSwitches()7931     public void stopAppSwitches() {
7932         mActivityTaskManager.stopAppSwitches();
7933     }
7934 
7935     @Override
resumeAppSwitches()7936     public void resumeAppSwitches() {
7937         mActivityTaskManager.resumeAppSwitches();
7938     }
7939 
setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)7940     public void setDebugApp(String packageName, boolean waitForDebugger,
7941             boolean persistent) {
7942         enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7943                 "setDebugApp()");
7944 
7945         long ident = Binder.clearCallingIdentity();
7946         try {
7947             // Note that this is not really thread safe if there are multiple
7948             // callers into it at the same time, but that's not a situation we
7949             // care about.
7950             if (persistent) {
7951                 final ContentResolver resolver = mContext.getContentResolver();
7952                 Settings.Global.putString(
7953                     resolver, Settings.Global.DEBUG_APP,
7954                     packageName);
7955                 Settings.Global.putInt(
7956                     resolver, Settings.Global.WAIT_FOR_DEBUGGER,
7957                     waitForDebugger ? 1 : 0);
7958             }
7959 
7960             synchronized (this) {
7961                 if (!persistent) {
7962                     mOrigDebugApp = mDebugApp;
7963                     mOrigWaitForDebugger = mWaitForDebugger;
7964                 }
7965                 mDebugApp = packageName;
7966                 mWaitForDebugger = waitForDebugger;
7967                 mDebugTransient = !persistent;
7968                 if (packageName != null) {
7969                     forceStopPackageLocked(packageName, -1, false, false, true, true,
7970                             false, UserHandle.USER_ALL, "set debug app");
7971                 }
7972             }
7973         } finally {
7974             Binder.restoreCallingIdentity(ident);
7975         }
7976     }
7977 
7978     /**
7979      * Set or remove an agent to be run whenever an app with the given process name starts.
7980      *
7981      * This method will not check whether the given process name matches a debuggable app. That
7982      * would require scanning all current packages, and a rescan when new packages are installed
7983      * or updated.
7984      *
7985      * Instead, do the check when an application is started and matched to a stored agent.
7986      *
7987      * @param packageName the process name of the app.
7988      * @param agent the agent string to be used, or null to remove any previously set agent.
7989      */
7990     @Override
setAgentApp(@onNull String packageName, @Nullable String agent)7991     public void setAgentApp(@NonNull String packageName, @Nullable String agent) {
7992         synchronized (this) {
7993             // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
7994             // its own permission.
7995             if (checkCallingPermission(
7996                     android.Manifest.permission.SET_ACTIVITY_WATCHER) !=
7997                         PackageManager.PERMISSION_GRANTED) {
7998                 throw new SecurityException(
7999                         "Requires permission " + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8000             }
8001 
8002             if (agent == null) {
8003                 if (mAppAgentMap != null) {
8004                     mAppAgentMap.remove(packageName);
8005                     if (mAppAgentMap.isEmpty()) {
8006                         mAppAgentMap = null;
8007                     }
8008                 }
8009             } else {
8010                 if (mAppAgentMap == null) {
8011                     mAppAgentMap = new HashMap<>();
8012                 }
8013                 if (mAppAgentMap.size() >= 100) {
8014                     // Limit the size of the map, to avoid OOMEs.
8015                     Slog.e(TAG, "App agent map has too many entries, cannot add " + packageName
8016                             + "/" + agent);
8017                     return;
8018                 }
8019                 mAppAgentMap.put(packageName, agent);
8020             }
8021         }
8022     }
8023 
setTrackAllocationApp(ApplicationInfo app, String processName)8024     void setTrackAllocationApp(ApplicationInfo app, String processName) {
8025         synchronized (this) {
8026             boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8027             if (!isDebuggable) {
8028                 if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
8029                     throw new SecurityException("Process not debuggable: " + app.packageName);
8030                 }
8031             }
8032 
8033             mTrackAllocationApp = processName;
8034         }
8035     }
8036 
setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)8037     void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) {
8038         synchronized (this) {
8039             boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8040             if (!isDebuggable) {
8041                 if (!app.isProfileableByShell()) {
8042                     throw new SecurityException("Process not debuggable, "
8043                             + "and not profileable by shell: " + app.packageName);
8044                 }
8045             }
8046             mProfileData.setProfileApp(processName);
8047 
8048             if (mProfileData.getProfilerInfo() != null) {
8049                 if (mProfileData.getProfilerInfo().profileFd != null) {
8050                     try {
8051                         mProfileData.getProfilerInfo().profileFd.close();
8052                     } catch (IOException e) {
8053                     }
8054                 }
8055             }
8056             mProfileData.setProfilerInfo(new ProfilerInfo(profilerInfo));
8057             mProfileType = 0;
8058         }
8059     }
8060 
setNativeDebuggingAppLocked(ApplicationInfo app, String processName)8061     void setNativeDebuggingAppLocked(ApplicationInfo app, String processName) {
8062         boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
8063         if (!isDebuggable) {
8064             if ((app.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
8065                 throw new SecurityException("Process not debuggable: " + app.packageName);
8066             }
8067         }
8068         mNativeDebuggingApp = processName;
8069     }
8070 
8071     @Override
setAlwaysFinish(boolean enabled)8072     public void setAlwaysFinish(boolean enabled) {
8073         enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
8074                 "setAlwaysFinish()");
8075 
8076         long ident = Binder.clearCallingIdentity();
8077         try {
8078             Settings.Global.putInt(
8079                     mContext.getContentResolver(),
8080                     Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
8081 
8082             synchronized (this) {
8083                 mAlwaysFinishActivities = enabled;
8084             }
8085         } finally {
8086             Binder.restoreCallingIdentity(ident);
8087         }
8088     }
8089 
8090     @Override
setActivityController(IActivityController controller, boolean imAMonkey)8091     public void setActivityController(IActivityController controller, boolean imAMonkey) {
8092         mActivityTaskManager.setActivityController(controller, imAMonkey);
8093     }
8094 
8095     @Override
setUserIsMonkey(boolean userIsMonkey)8096     public void setUserIsMonkey(boolean userIsMonkey) {
8097         synchronized (this) {
8098             synchronized (mPidsSelfLocked) {
8099                 final int callingPid = Binder.getCallingPid();
8100                 ProcessRecord proc = mPidsSelfLocked.get(callingPid);
8101                 if (proc == null) {
8102                     throw new SecurityException("Unknown process: " + callingPid);
8103                 }
8104                 if (proc.getActiveInstrumentation() == null
8105                         || proc.getActiveInstrumentation().mUiAutomationConnection == null) {
8106                     throw new SecurityException("Only an instrumentation process "
8107                             + "with a UiAutomation can call setUserIsMonkey");
8108                 }
8109             }
8110             mUserIsMonkey = userIsMonkey;
8111         }
8112     }
8113 
8114     @Override
isUserAMonkey()8115     public boolean isUserAMonkey() {
8116         synchronized (this) {
8117             // If there is a controller also implies the user is a monkey.
8118             return mUserIsMonkey || mActivityTaskManager.isControllerAMonkey();
8119         }
8120     }
8121 
8122     @Override
requestSystemServerHeapDump()8123     public void requestSystemServerHeapDump() {
8124         if (!Build.IS_DEBUGGABLE) {
8125             Slog.wtf(TAG, "requestSystemServerHeapDump called on a user build");
8126             return;
8127         }
8128         if (Binder.getCallingUid() != SYSTEM_UID) {
8129             // This also intentionally excludes secondary profiles from calling this.
8130             throw new SecurityException(
8131                     "Only the system process is allowed to request a system heap dump");
8132         }
8133         ProcessRecord pr;
8134         synchronized (mPidsSelfLocked) {
8135             pr = mPidsSelfLocked.get(myPid());
8136         }
8137         if (pr == null) {
8138             Slog.w(TAG, "system process not in mPidsSelfLocked: " + myPid());
8139             return;
8140         }
8141         synchronized (this) {
8142             startHeapDumpLocked(pr, true);
8143         }
8144     }
8145 
8146     /**
8147      * @deprecated This method is only used by a few internal components and it will soon be
8148      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8149      * No new code should be calling it.
8150      */
8151     @Deprecated
8152     @Override
requestBugReport(int bugreportType)8153     public void requestBugReport(int bugreportType) {
8154         String extraOptions = null;
8155         switch (bugreportType) {
8156             case ActivityManager.BUGREPORT_OPTION_FULL:
8157                 extraOptions = "bugreportfull";
8158                 break;
8159             case ActivityManager.BUGREPORT_OPTION_INTERACTIVE:
8160                 extraOptions = "bugreportplus";
8161                 break;
8162             case ActivityManager.BUGREPORT_OPTION_REMOTE:
8163                 extraOptions = "bugreportremote";
8164                 break;
8165             case ActivityManager.BUGREPORT_OPTION_WEAR:
8166                 extraOptions = "bugreportwear";
8167                 break;
8168             case ActivityManager.BUGREPORT_OPTION_TELEPHONY:
8169                 extraOptions = "bugreporttelephony";
8170                 break;
8171             case ActivityManager.BUGREPORT_OPTION_WIFI:
8172                 extraOptions = "bugreportwifi";
8173                 break;
8174             default:
8175                 throw new IllegalArgumentException("Provided bugreport type is not correct, value: "
8176                         + bugreportType);
8177         }
8178         // Always log caller, even if it does not have permission to dump.
8179         String type = extraOptions == null ? "bugreport" : extraOptions;
8180         Slog.i(TAG, type + " requested by UID " + Binder.getCallingUid());
8181 
8182         enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
8183         if (extraOptions != null) {
8184             SystemProperties.set("dumpstate.options", extraOptions);
8185         }
8186         SystemProperties.set("ctl.start", "bugreport");
8187     }
8188 
8189     /**
8190      * @deprecated This method is only used by a few internal components and it will soon be
8191      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8192      * No new code should be calling it.
8193      */
8194     @Deprecated
requestBugReportWithDescription(String shareTitle, String shareDescription, int bugreportType)8195     private void requestBugReportWithDescription(String shareTitle, String shareDescription,
8196                                                  int bugreportType) {
8197         if (!TextUtils.isEmpty(shareTitle)) {
8198             if (shareTitle.length() > MAX_BUGREPORT_TITLE_SIZE) {
8199                 String errorStr = "shareTitle should be less than " +
8200                         MAX_BUGREPORT_TITLE_SIZE + " characters";
8201                 throw new IllegalArgumentException(errorStr);
8202             } else {
8203                 if (!TextUtils.isEmpty(shareDescription)) {
8204                     int length;
8205                     try {
8206                         length = shareDescription.getBytes("UTF-8").length;
8207                     } catch (UnsupportedEncodingException e) {
8208                         String errorStr = "shareDescription: UnsupportedEncodingException";
8209                         throw new IllegalArgumentException(errorStr);
8210                     }
8211                     if (length > SystemProperties.PROP_VALUE_MAX) {
8212                         String errorStr = "shareTitle should be less than " +
8213                                 SystemProperties.PROP_VALUE_MAX + " bytes";
8214                         throw new IllegalArgumentException(errorStr);
8215                     } else {
8216                         SystemProperties.set("dumpstate.options.description", shareDescription);
8217                     }
8218                 }
8219                 SystemProperties.set("dumpstate.options.title", shareTitle);
8220             }
8221         }
8222 
8223         Slog.d(TAG, "Bugreport notification title " + shareTitle
8224                 + " description " + shareDescription);
8225         requestBugReport(bugreportType);
8226     }
8227 
8228     /**
8229      * @deprecated This method is only used by a few internal components and it will soon be
8230      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8231      * No new code should be calling it.
8232      */
8233     @Deprecated
8234     @Override
requestTelephonyBugReport(String shareTitle, String shareDescription)8235     public void requestTelephonyBugReport(String shareTitle, String shareDescription) {
8236         requestBugReportWithDescription(shareTitle, shareDescription,
8237                 ActivityManager.BUGREPORT_OPTION_TELEPHONY);
8238     }
8239 
8240     /**
8241      * @deprecated This method is only used by a few internal components and it will soon be
8242      * replaced by a proper bug report API (which will be restricted to a few, pre-defined apps).
8243      * No new code should be calling it.
8244      */
8245     @Deprecated
8246     @Override
requestWifiBugReport(String shareTitle, String shareDescription)8247     public void requestWifiBugReport(String shareTitle, String shareDescription) {
8248         requestBugReportWithDescription(shareTitle, shareDescription,
8249                 ActivityManager.BUGREPORT_OPTION_WIFI);
8250     }
8251 
registerProcessObserver(IProcessObserver observer)8252     public void registerProcessObserver(IProcessObserver observer) {
8253         enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
8254                 "registerProcessObserver()");
8255         synchronized (this) {
8256             mProcessObservers.register(observer);
8257         }
8258     }
8259 
8260     @Override
unregisterProcessObserver(IProcessObserver observer)8261     public void unregisterProcessObserver(IProcessObserver observer) {
8262         synchronized (this) {
8263             mProcessObservers.unregister(observer);
8264         }
8265     }
8266 
8267     @Override
getUidProcessState(int uid, String callingPackage)8268     public int getUidProcessState(int uid, String callingPackage) {
8269         if (!hasUsageStatsPermission(callingPackage)) {
8270             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8271                     "getUidProcessState");
8272         }
8273 
8274         synchronized (this) {
8275             return mProcessList.getUidProcStateLocked(uid);
8276         }
8277     }
8278 
8279     @Override
registerUidObserver(IUidObserver observer, int which, int cutpoint, String callingPackage)8280     public void registerUidObserver(IUidObserver observer, int which, int cutpoint,
8281             String callingPackage) {
8282         if (!hasUsageStatsPermission(callingPackage)) {
8283             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8284                     "registerUidObserver");
8285         }
8286         synchronized (this) {
8287             mUidObservers.register(observer, new UidObserverRegistration(Binder.getCallingUid(),
8288                     callingPackage, which, cutpoint));
8289         }
8290     }
8291 
8292     @Override
unregisterUidObserver(IUidObserver observer)8293     public void unregisterUidObserver(IUidObserver observer) {
8294         synchronized (this) {
8295             mUidObservers.unregister(observer);
8296         }
8297     }
8298 
8299     @Override
isUidActive(int uid, String callingPackage)8300     public boolean isUidActive(int uid, String callingPackage) {
8301         if (!hasUsageStatsPermission(callingPackage)) {
8302             enforceCallingPermission(android.Manifest.permission.PACKAGE_USAGE_STATS,
8303                     "isUidActive");
8304         }
8305         synchronized (this) {
8306             return isUidActiveLocked(uid);
8307         }
8308     }
8309 
isUidActiveLocked(int uid)8310     boolean isUidActiveLocked(int uid) {
8311         final UidRecord uidRecord = mProcessList.getUidRecordLocked(uid);
8312         return uidRecord != null && !uidRecord.setIdle;
8313     }
8314 
8315     @Override
setPersistentVrThread(int tid)8316     public void setPersistentVrThread(int tid) {
8317         mActivityTaskManager.setPersistentVrThread(tid);
8318     }
8319 
8320     /**
8321      * Schedule the given thread a normal scheduling priority.
8322      *
8323      * @param tid the tid of the thread to adjust the scheduling of.
8324      * @param suppressLogs {@code true} if any error logging should be disabled.
8325      *
8326      * @return {@code true} if this succeeded.
8327      */
scheduleAsRegularPriority(int tid, boolean suppressLogs)8328     public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
8329         try {
8330             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
8331             return true;
8332         } catch (IllegalArgumentException e) {
8333             if (!suppressLogs) {
8334                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
8335             }
8336         } catch (SecurityException e) {
8337             if (!suppressLogs) {
8338                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
8339             }
8340         }
8341         return false;
8342     }
8343 
8344     /**
8345      * Schedule the given thread an FIFO scheduling priority.
8346      *
8347      * @param tid the tid of the thread to adjust the scheduling of.
8348      * @param suppressLogs {@code true} if any error logging should be disabled.
8349      *
8350      * @return {@code true} if this succeeded.
8351      */
scheduleAsFifoPriority(int tid, boolean suppressLogs)8352     public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
8353         try {
8354             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
8355             return true;
8356         } catch (IllegalArgumentException e) {
8357             if (!suppressLogs) {
8358                 Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
8359             }
8360         } catch (SecurityException e) {
8361             if (!suppressLogs) {
8362                 Slog.w(TAG, "Failed to set scheduling policy, not allowed:\n" + e);
8363             }
8364         }
8365         return false;
8366     }
8367 
8368     @Override
setRenderThread(int tid)8369     public void setRenderThread(int tid) {
8370         synchronized (this) {
8371             ProcessRecord proc;
8372             int pid = Binder.getCallingPid();
8373             if (pid == Process.myPid()) {
8374                 demoteSystemServerRenderThread(tid);
8375                 return;
8376             }
8377             synchronized (mPidsSelfLocked) {
8378                 proc = mPidsSelfLocked.get(pid);
8379                 if (proc != null && proc.renderThreadTid == 0 && tid > 0) {
8380                     // ensure the tid belongs to the process
8381                     if (!isThreadInProcess(pid, tid)) {
8382                         throw new IllegalArgumentException(
8383                             "Render thread does not belong to process");
8384                     }
8385                     proc.renderThreadTid = tid;
8386                     if (DEBUG_OOM_ADJ) {
8387                         Slog.d("UI_FIFO", "Set RenderThread tid " + tid + " for pid " + pid);
8388                     }
8389                     // promote to FIFO now
8390                     if (proc.getCurrentSchedulingGroup() == ProcessList.SCHED_GROUP_TOP_APP) {
8391                         if (DEBUG_OOM_ADJ) Slog.d("UI_FIFO", "Promoting " + tid + "out of band");
8392                         if (mUseFifoUiScheduling) {
8393                             setThreadScheduler(proc.renderThreadTid,
8394                                 SCHED_FIFO | SCHED_RESET_ON_FORK, 1);
8395                         } else {
8396                             setThreadPriority(proc.renderThreadTid, TOP_APP_PRIORITY_BOOST);
8397                         }
8398                     }
8399                 } else {
8400                     if (DEBUG_OOM_ADJ) {
8401                         Slog.d("UI_FIFO", "Didn't set thread from setRenderThread? " +
8402                                "PID: " + pid + ", TID: " + tid + " FIFO: " +
8403                                mUseFifoUiScheduling);
8404                     }
8405                 }
8406             }
8407         }
8408     }
8409 
8410     /**
8411      * We only use RenderThread in system_server to store task snapshots to the disk, which should
8412      * happen in the background. Thus, demote render thread from system_server to a lower priority.
8413      *
8414      * @param tid the tid of the RenderThread
8415      */
demoteSystemServerRenderThread(int tid)8416     private void demoteSystemServerRenderThread(int tid) {
8417         setThreadPriority(tid, Process.THREAD_PRIORITY_BACKGROUND);
8418     }
8419 
8420     @Override
isVrModePackageEnabled(ComponentName packageName)8421     public boolean isVrModePackageEnabled(ComponentName packageName) {
8422         mActivityTaskManager.enforceSystemHasVrFeature();
8423 
8424         final VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class);
8425 
8426         return vrService.hasVrPackage(packageName, UserHandle.getCallingUserId()) ==
8427                 VrManagerInternal.NO_ERROR;
8428     }
8429 
isTopActivityImmersive()8430     public boolean isTopActivityImmersive() {
8431         return mActivityTaskManager.isTopActivityImmersive();
8432     }
8433 
8434     @Override
isTopOfTask(IBinder token)8435     public boolean isTopOfTask(IBinder token) {
8436         return mActivityTaskManager.isTopOfTask(token);
8437     }
8438 
8439     @Override
setHasTopUi(boolean hasTopUi)8440     public void setHasTopUi(boolean hasTopUi) throws RemoteException {
8441         if (checkCallingPermission(permission.INTERNAL_SYSTEM_WINDOW) != PERMISSION_GRANTED) {
8442             String msg = "Permission Denial: setHasTopUi() from pid="
8443                     + Binder.getCallingPid()
8444                     + ", uid=" + Binder.getCallingUid()
8445                     + " requires " + permission.INTERNAL_SYSTEM_WINDOW;
8446             Slog.w(TAG, msg);
8447             throw new SecurityException(msg);
8448         }
8449         final int pid = Binder.getCallingPid();
8450         final long origId = Binder.clearCallingIdentity();
8451         try {
8452             synchronized (this) {
8453                 boolean changed = false;
8454                 ProcessRecord pr;
8455                 synchronized (mPidsSelfLocked) {
8456                     pr = mPidsSelfLocked.get(pid);
8457                     if (pr == null) {
8458                         Slog.w(TAG, "setHasTopUi called on unknown pid: " + pid);
8459                         return;
8460                     }
8461                     if (pr.hasTopUi() != hasTopUi) {
8462                         if (DEBUG_OOM_ADJ) {
8463                             Slog.d(TAG, "Setting hasTopUi=" + hasTopUi + " for pid=" + pid);
8464                         }
8465                         pr.setHasTopUi(hasTopUi);
8466                         changed = true;
8467                     }
8468                 }
8469                 if (changed) {
8470                     updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
8471                 }
8472             }
8473         } finally {
8474             Binder.restoreCallingIdentity(origId);
8475         }
8476     }
8477 
setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation)8478     void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) {
8479         if (pid == Process.myPid()) {
8480             Slog.wtf(TAG, "system can't run remote animation");
8481             return;
8482         }
8483         synchronized (ActivityManagerService.this) {
8484             final ProcessRecord pr;
8485             synchronized (mPidsSelfLocked) {
8486                 pr = mPidsSelfLocked.get(pid);
8487                 if (pr == null) {
8488                     Slog.w(TAG, "setRunningRemoteAnimation called on unknown pid: " + pid);
8489                     return;
8490                 }
8491             }
8492             if (pr.runningRemoteAnimation == runningRemoteAnimation) {
8493                 return;
8494             }
8495             pr.runningRemoteAnimation = runningRemoteAnimation;
8496             if (DEBUG_OOM_ADJ) {
8497                 Slog.i(TAG, "Setting runningRemoteAnimation=" + pr.runningRemoteAnimation
8498                         + " for pid=" + pid);
8499             }
8500             updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
8501         }
8502     }
8503 
enterSafeMode()8504     public final void enterSafeMode() {
8505         synchronized(this) {
8506             // It only makes sense to do this before the system is ready
8507             // and started launching other packages.
8508             if (!mSystemReady) {
8509                 try {
8510                     AppGlobals.getPackageManager().enterSafeMode();
8511                 } catch (RemoteException e) {
8512                 }
8513             }
8514 
8515             mSafeMode = true;
8516         }
8517     }
8518 
showSafeModeOverlay()8519     public final void showSafeModeOverlay() {
8520         View v = LayoutInflater.from(mContext).inflate(
8521                 com.android.internal.R.layout.safe_mode, null);
8522         WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
8523         lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
8524         lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
8525         lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
8526         lp.gravity = Gravity.BOTTOM | Gravity.START;
8527         lp.format = v.getBackground().getOpacity();
8528         lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
8529                 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
8530         lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
8531         ((WindowManager)mContext.getSystemService(
8532                 Context.WINDOW_SERVICE)).addView(v, lp);
8533     }
8534 
8535     @Override
noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid, String sourcePkg, String tag)8536     public void noteWakeupAlarm(IIntentSender sender, WorkSource workSource, int sourceUid,
8537             String sourcePkg, String tag) {
8538         if (workSource != null && workSource.isEmpty()) {
8539             workSource = null;
8540         }
8541 
8542         if (sourceUid <= 0 && workSource == null) {
8543             // Try and derive a UID to attribute things to based on the caller.
8544             if (sender != null) {
8545                 if (!(sender instanceof PendingIntentRecord)) {
8546                     return;
8547                 }
8548 
8549                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8550                 final int callerUid = Binder.getCallingUid();
8551                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8552             } else {
8553                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8554                 // haven't been able to derive a UID to attribute things to.
8555                 return;
8556             }
8557         }
8558 
8559         int standbyBucket = 0;
8560 
8561         mBatteryStatsService.noteWakupAlarm(sourcePkg, sourceUid, workSource, tag);
8562         if (workSource != null) {
8563             String workSourcePackage = workSource.getName(0);
8564             int workSourceUid = workSource.getAttributionUid();
8565             if (workSourcePackage == null) {
8566                 workSourcePackage = sourcePkg;
8567                 workSourceUid = sourceUid;
8568             }
8569 
8570             if (mUsageStatsService != null) {
8571                 standbyBucket = mUsageStatsService.getAppStandbyBucket(workSourcePackage,
8572                         UserHandle.getUserId(workSourceUid), SystemClock.elapsedRealtime());
8573             }
8574 
8575             StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, workSource, tag, sourcePkg,
8576                     standbyBucket);
8577             if (DEBUG_POWER) {
8578                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8579                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8580                         + standbyBucket + " wsName=" + workSourcePackage + ")]");
8581             }
8582         } else {
8583             if (mUsageStatsService != null) {
8584                 standbyBucket = mUsageStatsService.getAppStandbyBucket(sourcePkg,
8585                         UserHandle.getUserId(sourceUid), SystemClock.elapsedRealtime());
8586             }
8587             StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, sourceUid, null, tag,
8588                     sourcePkg, standbyBucket);
8589             if (DEBUG_POWER) {
8590                 Slog.w(TAG, "noteWakeupAlarm[ sourcePkg=" + sourcePkg + ", sourceUid=" + sourceUid
8591                         + ", workSource=" + workSource + ", tag=" + tag + ", standbyBucket="
8592                         + standbyBucket + "]");
8593             }
8594         }
8595 
8596     }
8597 
8598     @Override
noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8599     public void noteAlarmStart(IIntentSender sender, WorkSource workSource, int sourceUid,
8600             String tag) {
8601         if (workSource != null && workSource.isEmpty()) {
8602             workSource = null;
8603         }
8604 
8605         if (sourceUid <= 0 && workSource == null) {
8606             // Try and derive a UID to attribute things to based on the caller.
8607             if (sender != null) {
8608                 if (!(sender instanceof PendingIntentRecord)) {
8609                     return;
8610                 }
8611 
8612                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8613                 final int callerUid = Binder.getCallingUid();
8614                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8615             } else {
8616                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8617                 // haven't been able to derive a UID to attribute things to.
8618                 return;
8619             }
8620         }
8621 
8622         if (DEBUG_POWER) {
8623             Slog.w(TAG, "noteAlarmStart[sourceUid=" + sourceUid + ", workSource=" + workSource +
8624                     ", tag=" + tag + "]");
8625         }
8626 
8627         mBatteryStatsService.noteAlarmStart(tag, workSource, sourceUid);
8628     }
8629 
8630     @Override
noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid, String tag)8631     public void noteAlarmFinish(IIntentSender sender, WorkSource workSource, int sourceUid,
8632             String tag) {
8633         if (workSource != null && workSource.isEmpty()) {
8634             workSource = null;
8635         }
8636 
8637         if (sourceUid <= 0 && workSource == null) {
8638             // Try and derive a UID to attribute things to based on the caller.
8639             if (sender != null) {
8640                 if (!(sender instanceof PendingIntentRecord)) {
8641                     return;
8642                 }
8643 
8644                 final PendingIntentRecord rec = (PendingIntentRecord) sender;
8645                 final int callerUid = Binder.getCallingUid();
8646                 sourceUid = rec.uid == callerUid ? SYSTEM_UID : rec.uid;
8647             } else {
8648                 // TODO(narayan): Should we throw an exception in this case ? It means that we
8649                 // haven't been able to derive a UID to attribute things to.
8650                 return;
8651             }
8652         }
8653 
8654         if (DEBUG_POWER) {
8655             Slog.w(TAG, "noteAlarmFinish[sourceUid=" + sourceUid + ", workSource=" + workSource +
8656                     ", tag=" + tag + "]");
8657         }
8658 
8659         mBatteryStatsService.noteAlarmFinish(tag, workSource, sourceUid);
8660     }
8661 
killPids(int[] pids, String pReason, boolean secure)8662     public boolean killPids(int[] pids, String pReason, boolean secure) {
8663         if (Binder.getCallingUid() != SYSTEM_UID) {
8664             throw new SecurityException("killPids only available to the system");
8665         }
8666         String reason = (pReason == null) ? "Unknown" : pReason;
8667         // XXX Note: don't acquire main activity lock here, because the window
8668         // manager calls in with its locks held.
8669 
8670         boolean killed = false;
8671         synchronized (mPidsSelfLocked) {
8672             int worstType = 0;
8673             for (int i=0; i<pids.length; i++) {
8674                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8675                 if (proc != null) {
8676                     int type = proc.setAdj;
8677                     if (type > worstType) {
8678                         worstType = type;
8679                     }
8680                 }
8681             }
8682 
8683             // If the worst oom_adj is somewhere in the cached proc LRU range,
8684             // then constrain it so we will kill all cached procs.
8685             if (worstType < ProcessList.CACHED_APP_MAX_ADJ
8686                     && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
8687                 worstType = ProcessList.CACHED_APP_MIN_ADJ;
8688             }
8689 
8690             // If this is not a secure call, don't let it kill processes that
8691             // are important.
8692             if (!secure && worstType < ProcessList.SERVICE_ADJ) {
8693                 worstType = ProcessList.SERVICE_ADJ;
8694             }
8695 
8696             Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
8697             for (int i=0; i<pids.length; i++) {
8698                 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
8699                 if (proc == null) {
8700                     continue;
8701                 }
8702                 int adj = proc.setAdj;
8703                 if (adj >= worstType && !proc.killedByAm) {
8704                     proc.kill(reason, true);
8705                     killed = true;
8706                 }
8707             }
8708         }
8709         return killed;
8710     }
8711 
8712     @Override
killUid(int appId, int userId, String reason)8713     public void killUid(int appId, int userId, String reason) {
8714         enforceCallingPermission(Manifest.permission.KILL_UID, "killUid");
8715         synchronized (this) {
8716             final long identity = Binder.clearCallingIdentity();
8717             try {
8718                 mProcessList.killPackageProcessesLocked(null /* packageName */, appId, userId,
8719                         ProcessList.PERSISTENT_PROC_ADJ, false /* callerWillRestart */,
8720                         true /* callerWillRestart */, true /* doit */, true /* evenPersistent */,
8721                         false /* setRemoved */, reason != null ? reason : "kill uid");
8722             } finally {
8723                 Binder.restoreCallingIdentity(identity);
8724             }
8725         }
8726     }
8727 
8728     @Override
killProcessesBelowForeground(String reason)8729     public boolean killProcessesBelowForeground(String reason) {
8730         if (Binder.getCallingUid() != SYSTEM_UID) {
8731             throw new SecurityException("killProcessesBelowForeground() only available to system");
8732         }
8733 
8734         return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
8735     }
8736 
killProcessesBelowAdj(int belowAdj, String reason)8737     private boolean killProcessesBelowAdj(int belowAdj, String reason) {
8738         if (Binder.getCallingUid() != SYSTEM_UID) {
8739             throw new SecurityException("killProcessesBelowAdj() only available to system");
8740         }
8741 
8742         boolean killed = false;
8743         synchronized (mPidsSelfLocked) {
8744             final int size = mPidsSelfLocked.size();
8745             for (int i = 0; i < size; i++) {
8746                 final int pid = mPidsSelfLocked.keyAt(i);
8747                 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8748                 if (proc == null) continue;
8749 
8750                 final int adj = proc.setAdj;
8751                 if (adj > belowAdj && !proc.killedByAm) {
8752                     proc.kill(reason, true);
8753                     killed = true;
8754                 }
8755             }
8756         }
8757         return killed;
8758     }
8759 
8760     @Override
hang(final IBinder who, boolean allowRestart)8761     public void hang(final IBinder who, boolean allowRestart) {
8762         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8763                 != PackageManager.PERMISSION_GRANTED) {
8764             throw new SecurityException("Requires permission "
8765                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8766         }
8767 
8768         final IBinder.DeathRecipient death = new DeathRecipient() {
8769             @Override
8770             public void binderDied() {
8771                 synchronized (this) {
8772                     notifyAll();
8773                 }
8774             }
8775         };
8776 
8777         try {
8778             who.linkToDeath(death, 0);
8779         } catch (RemoteException e) {
8780             Slog.w(TAG, "hang: given caller IBinder is already dead.");
8781             return;
8782         }
8783 
8784         synchronized (this) {
8785             Watchdog.getInstance().setAllowRestart(allowRestart);
8786             Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
8787             synchronized (death) {
8788                 while (who.isBinderAlive()) {
8789                     try {
8790                         death.wait();
8791                     } catch (InterruptedException e) {
8792                     }
8793                 }
8794             }
8795             Watchdog.getInstance().setAllowRestart(true);
8796         }
8797     }
8798 
8799     @Override
restart()8800     public void restart() {
8801         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8802                 != PackageManager.PERMISSION_GRANTED) {
8803             throw new SecurityException("Requires permission "
8804                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8805         }
8806 
8807         Log.i(TAG, "Sending shutdown broadcast...");
8808 
8809         BroadcastReceiver br = new BroadcastReceiver() {
8810             @Override public void onReceive(Context context, Intent intent) {
8811                 // Now the broadcast is done, finish up the low-level shutdown.
8812                 Log.i(TAG, "Shutting down activity manager...");
8813                 shutdown(10000);
8814                 Log.i(TAG, "Shutdown complete, restarting!");
8815                 killProcess(myPid());
8816                 System.exit(10);
8817             }
8818         };
8819 
8820         // First send the high-level shut down broadcast.
8821         Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
8822         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8823         intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
8824         /* For now we are not doing a clean shutdown, because things seem to get unhappy.
8825         mContext.sendOrderedBroadcastAsUser(intent,
8826                 UserHandle.ALL, null, br, mHandler, 0, null, null);
8827         */
8828         br.onReceive(mContext, intent);
8829     }
8830 
getLowRamTimeSinceIdle(long now)8831     private long getLowRamTimeSinceIdle(long now) {
8832         return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0);
8833     }
8834 
8835     @Override
performIdleMaintenance()8836     public void performIdleMaintenance() {
8837         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8838                 != PackageManager.PERMISSION_GRANTED) {
8839             throw new SecurityException("Requires permission "
8840                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8841         }
8842 
8843         synchronized (this) {
8844             final long now = SystemClock.uptimeMillis();
8845             final long timeSinceLastIdle = now - mLastIdleTime;
8846 
8847             // Compact all non-zygote processes to freshen up the page cache.
8848             mOomAdjuster.mAppCompact.compactAllSystem();
8849 
8850             final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
8851             mLastIdleTime = now;
8852             mLowRamTimeSinceLastIdle = 0;
8853             if (mLowRamStartTime != 0) {
8854                 mLowRamStartTime = now;
8855             }
8856 
8857             StringBuilder sb = new StringBuilder(128);
8858             sb.append("Idle maintenance over ");
8859             TimeUtils.formatDuration(timeSinceLastIdle, sb);
8860             sb.append(" low RAM for ");
8861             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
8862             Slog.i(TAG, sb.toString());
8863 
8864             // If at least 1/3 of our time since the last idle period has been spent
8865             // with RAM low, then we want to kill processes.
8866             boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
8867             // If the processes' memory has increased by more than 1% of the total memory,
8868             // or 10 MB, whichever is greater, then the processes' are eligible to be killed.
8869             final long totalMemoryInKb = getTotalMemory() / 1000;
8870             final long memoryGrowthThreshold =
8871                     Math.max(totalMemoryInKb / 100, MINIMUM_MEMORY_GROWTH_THRESHOLD);
8872 
8873             for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) {
8874                 ProcessRecord proc = mProcessList.mLruProcesses.get(i);
8875                 if (proc.notCachedSinceIdle) {
8876                     if (proc.setProcState >= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
8877                             && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
8878                         if (doKilling && proc.initialIdlePss != 0
8879                                 && proc.lastPss > ((proc.initialIdlePss * 3) / 2)
8880                                 && proc.lastPss > (proc.initialIdlePss + memoryGrowthThreshold)) {
8881                             sb = new StringBuilder(128);
8882                             sb.append("Kill");
8883                             sb.append(proc.processName);
8884                             sb.append(" in idle maint: pss=");
8885                             sb.append(proc.lastPss);
8886                             sb.append(", swapPss=");
8887                             sb.append(proc.lastSwapPss);
8888                             sb.append(", initialPss=");
8889                             sb.append(proc.initialIdlePss);
8890                             sb.append(", period=");
8891                             TimeUtils.formatDuration(timeSinceLastIdle, sb);
8892                             sb.append(", lowRamPeriod=");
8893                             TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
8894                             Slog.wtfQuiet(TAG, sb.toString());
8895                             proc.kill("idle maint (pss " + proc.lastPss
8896                                     + " from " + proc.initialIdlePss + ")", true);
8897                         }
8898                     }
8899                 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME
8900                         && proc.setProcState >= ActivityManager.PROCESS_STATE_PERSISTENT) {
8901                     proc.notCachedSinceIdle = true;
8902                     proc.initialIdlePss = 0;
8903                     proc.nextPssTime = ProcessList.computeNextPssTime(proc.setProcState, null,
8904                             mTestPssMode, mAtmInternal.isSleeping(), now);
8905                 }
8906             }
8907         }
8908     }
8909 
8910     @Override
sendIdleJobTrigger()8911     public void sendIdleJobTrigger() {
8912         if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
8913                 != PackageManager.PERMISSION_GRANTED) {
8914             throw new SecurityException("Requires permission "
8915                     + android.Manifest.permission.SET_ACTIVITY_WATCHER);
8916         }
8917 
8918         final long ident = Binder.clearCallingIdentity();
8919         try {
8920             Intent intent = new Intent(ACTION_TRIGGER_IDLE)
8921                     .setPackage("android")
8922                     .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8923             broadcastIntent(null, intent, null, null, 0, null, null, null,
8924                     OP_NONE, null, false, false, UserHandle.USER_ALL);
8925         } finally {
8926             Binder.restoreCallingIdentity(ident);
8927         }
8928     }
8929 
retrieveSettings()8930     private void retrieveSettings() {
8931         final ContentResolver resolver = mContext.getContentResolver();
8932         mActivityTaskManager.retrieveSettings(resolver);
8933 
8934         final String debugApp = Settings.Global.getString(resolver, DEBUG_APP);
8935         final boolean waitForDebugger = Settings.Global.getInt(resolver, WAIT_FOR_DEBUGGER, 0) != 0;
8936         final boolean alwaysFinishActivities =
8937                 Settings.Global.getInt(resolver, ALWAYS_FINISH_ACTIVITIES, 0) != 0;
8938         final long waitForNetworkTimeoutMs = Settings.Global.getLong(resolver,
8939                 NETWORK_ACCESS_TIMEOUT_MS, NETWORK_ACCESS_TIMEOUT_DEFAULT_MS);
8940         mHiddenApiBlacklist.registerObserver();
8941 
8942         final long pssDeferralMs = DeviceConfig.getLong(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
8943                 ACTIVITY_START_PSS_DEFER_CONFIG, 0L);
8944         DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_ACTIVITY_MANAGER,
8945                 ActivityThread.currentApplication().getMainExecutor(),
8946                 mPssDelayConfigListener);
8947 
8948         synchronized (this) {
8949             mDebugApp = mOrigDebugApp = debugApp;
8950             mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
8951             mAlwaysFinishActivities = alwaysFinishActivities;
8952             // Load resources only after the current configuration has been set.
8953             final Resources res = mContext.getResources();
8954             mAppErrors.loadAppsNotReportingCrashesFromConfigLocked(res.getString(
8955                     com.android.internal.R.string.config_appsNotReportingCrashes));
8956             mUserController.mUserSwitchUiEnabled = !res.getBoolean(
8957                     com.android.internal.R.bool.config_customUserSwitchUi);
8958             mUserController.mMaxRunningUsers = res.getInteger(
8959                     com.android.internal.R.integer.config_multiuserMaxRunningUsers);
8960             mUserController.mDelayUserDataLocking = res.getBoolean(
8961                     com.android.internal.R.bool.config_multiuserDelayUserDataLocking);
8962 
8963             mWaitForNetworkTimeoutMs = waitForNetworkTimeoutMs;
8964             mPssDeferralTime = pssDeferralMs;
8965         }
8966     }
8967 
systemReady(final Runnable goingCallback, TimingsTraceLog traceLog)8968     public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
8969         traceLog.traceBegin("PhaseActivityManagerReady");
8970         synchronized(this) {
8971             if (mSystemReady) {
8972                 // If we're done calling all the receivers, run the next "boot phase" passed in
8973                 // by the SystemServer
8974                 if (goingCallback != null) {
8975                     goingCallback.run();
8976                 }
8977                 return;
8978             }
8979 
8980             mLocalDeviceIdleController
8981                     = LocalServices.getService(DeviceIdleController.LocalService.class);
8982             mActivityTaskManager.onSystemReady();
8983             // Make sure we have the current profile info, since it is needed for security checks.
8984             mUserController.onSystemReady();
8985             mAppOpsService.systemReady();
8986             mSystemReady = true;
8987         }
8988 
8989         try {
8990             sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
8991                     ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
8992                     .getSerial();
8993         } catch (RemoteException e) {}
8994 
8995         ArrayList<ProcessRecord> procsToKill = null;
8996         synchronized(mPidsSelfLocked) {
8997             for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
8998                 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8999                 if (!isAllowedWhileBooting(proc.info)){
9000                     if (procsToKill == null) {
9001                         procsToKill = new ArrayList<ProcessRecord>();
9002                     }
9003                     procsToKill.add(proc);
9004                 }
9005             }
9006         }
9007 
9008         synchronized(this) {
9009             if (procsToKill != null) {
9010                 for (int i=procsToKill.size()-1; i>=0; i--) {
9011                     ProcessRecord proc = procsToKill.get(i);
9012                     Slog.i(TAG, "Removing system update proc: " + proc);
9013                     mProcessList.removeProcessLocked(proc, true, false, "system update done");
9014                 }
9015             }
9016 
9017             // Now that we have cleaned up any update processes, we
9018             // are ready to start launching real processes and know that
9019             // we won't trample on them any more.
9020             mProcessesReady = true;
9021         }
9022 
9023         Slog.i(TAG, "System now ready");
9024         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());
9025 
9026         mAtmInternal.updateTopComponentForFactoryTest();
9027         mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
9028 
9029         watchDeviceProvisioning(mContext);
9030 
9031         retrieveSettings();
9032         mUgmInternal.onSystemReady();
9033 
9034         final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
9035         if (pmi != null) {
9036             pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
9037                     state -> updateForceBackgroundCheck(state.batterySaverEnabled));
9038             updateForceBackgroundCheck(
9039                     pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
9040         } else {
9041             Slog.wtf(TAG, "PowerManagerInternal not found.");
9042         }
9043 
9044         if (goingCallback != null) goingCallback.run();
9045         // Check the current user here as a user can be started inside goingCallback.run() from
9046         // other system services.
9047         final int currentUserId = mUserController.getCurrentUserId();
9048         Slog.i(TAG, "Current user:" + currentUserId);
9049         if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
9050             // User other than system user has started. Make sure that system user is already
9051             // started before switching user.
9052             throw new RuntimeException("System user not started while current user is:"
9053                     + currentUserId);
9054         }
9055         traceLog.traceBegin("ActivityManagerStartApps");
9056         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
9057                 Integer.toString(currentUserId), currentUserId);
9058         mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
9059                 Integer.toString(currentUserId), currentUserId);
9060         mSystemServiceManager.startUser(currentUserId);
9061 
9062         synchronized (this) {
9063             // Only start up encryption-aware persistent apps; once user is
9064             // unlocked we'll come back around and start unaware apps
9065             startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
9066 
9067             // Start up initial activity.
9068             mBooting = true;
9069             // Enable home activity for system user, so that the system can always boot. We don't
9070             // do this when the system user is not setup since the setup wizard should be the one
9071             // to handle home activity in this case.
9072             if (UserManager.isSplitSystemUser() &&
9073                     Settings.Secure.getInt(mContext.getContentResolver(),
9074                          Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
9075                 ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
9076                 try {
9077                     AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
9078                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
9079                             UserHandle.USER_SYSTEM);
9080                 } catch (RemoteException e) {
9081                     throw e.rethrowAsRuntimeException();
9082                 }
9083             }
9084             mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
9085 
9086             mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
9087 
9088             final int callingUid = Binder.getCallingUid();
9089             final int callingPid = Binder.getCallingPid();
9090             long ident = Binder.clearCallingIdentity();
9091             try {
9092                 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
9093                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
9094                         | Intent.FLAG_RECEIVER_FOREGROUND);
9095                 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9096                 broadcastIntentLocked(null, null, intent,
9097                         null, null, 0, null, null, null, OP_NONE,
9098                         null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9099                         currentUserId);
9100                 intent = new Intent(Intent.ACTION_USER_STARTING);
9101                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
9102                 intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9103                 broadcastIntentLocked(null, null, intent,
9104                         null, new IIntentReceiver.Stub() {
9105                             @Override
9106                             public void performReceive(Intent intent, int resultCode, String data,
9107                                     Bundle extras, boolean ordered, boolean sticky, int sendingUser)
9108                                     throws RemoteException {
9109                             }
9110                         }, 0, null, null,
9111                         new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
9112                         null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9113                         UserHandle.USER_ALL);
9114             } catch (Throwable t) {
9115                 Slog.wtf(TAG, "Failed sending first user broadcasts", t);
9116             } finally {
9117                 Binder.restoreCallingIdentity(ident);
9118             }
9119             mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
9120             mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
9121 
9122             BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
9123                     BINDER_PROXY_LOW_WATERMARK);
9124             BinderInternal.nSetBinderProxyCountEnabled(true);
9125             BinderInternal.setBinderProxyCountCallback(
9126                     new BinderInternal.BinderProxyLimitListener() {
9127                         @Override
9128                         public void onLimitReached(int uid) {
9129                             Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
9130                                     + Process.myUid());
9131                             BinderProxy.dumpProxyDebugInfo();
9132                             if (uid == Process.SYSTEM_UID) {
9133                                 Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
9134                             } else {
9135                                 killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
9136                                         "Too many Binders sent to SYSTEM");
9137                             }
9138                         }
9139                     }, mHandler);
9140 
9141             traceLog.traceEnd(); // ActivityManagerStartApps
9142             traceLog.traceEnd(); // PhaseActivityManagerReady
9143         }
9144     }
9145 
watchDeviceProvisioning(Context context)9146     private void watchDeviceProvisioning(Context context) {
9147         // setting system property based on whether device is provisioned
9148 
9149         if (isDeviceProvisioned(context)) {
9150             SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
9151         } else {
9152             // watch for device provisioning change
9153             context.getContentResolver().registerContentObserver(
9154                     Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), false,
9155                     new ContentObserver(new Handler(Looper.getMainLooper())) {
9156                         @Override
9157                         public void onChange(boolean selfChange) {
9158                             if (isDeviceProvisioned(context)) {
9159                                 SystemProperties.set(SYSTEM_PROPERTY_DEVICE_PROVISIONED, "1");
9160                                 context.getContentResolver().unregisterContentObserver(this);
9161                             }
9162                         }
9163                     });
9164         }
9165     }
9166 
isDeviceProvisioned(Context context)9167     private boolean isDeviceProvisioned(Context context) {
9168         return Settings.Global.getInt(context.getContentResolver(),
9169                 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
9170     }
9171 
startBroadcastObservers()9172     private void startBroadcastObservers() {
9173         for (BroadcastQueue queue : mBroadcastQueues) {
9174             queue.start(mContext.getContentResolver());
9175         }
9176     }
9177 
updateForceBackgroundCheck(boolean enabled)9178     private void updateForceBackgroundCheck(boolean enabled) {
9179         synchronized (this) {
9180             if (mForceBackgroundCheck != enabled) {
9181                 mForceBackgroundCheck = enabled;
9182 
9183                 if (DEBUG_BACKGROUND_CHECK) {
9184                     Slog.i(TAG, "Force background check " + (enabled ? "enabled" : "disabled"));
9185                 }
9186 
9187                 if (mForceBackgroundCheck) {
9188                     // Stop background services for idle UIDs.
9189                     mProcessList.doStopUidForIdleUidsLocked();
9190                 }
9191             }
9192         }
9193     }
9194 
killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog)9195     void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
9196         synchronized (this) {
9197             mAppErrors.killAppAtUserRequestLocked(app, fromDialog);
9198         }
9199     }
9200 
skipCurrentReceiverLocked(ProcessRecord app)9201     void skipCurrentReceiverLocked(ProcessRecord app) {
9202         for (BroadcastQueue queue : mBroadcastQueues) {
9203             queue.skipCurrentReceiverLocked(app);
9204         }
9205     }
9206 
9207     /**
9208      * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
9209      * The application process will exit immediately after this call returns.
9210      * @param app object of the crashing app, null for the system server
9211      * @param crashInfo describing the exception
9212      */
handleApplicationCrash(IBinder app, ApplicationErrorReport.ParcelableCrashInfo crashInfo)9213     public void handleApplicationCrash(IBinder app,
9214             ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
9215         ProcessRecord r = findAppProcess(app, "Crash");
9216         final String processName = app == null ? "system_server"
9217                 : (r == null ? "unknown" : r.processName);
9218 
9219         handleApplicationCrashInner("crash", r, processName, crashInfo);
9220     }
9221 
9222     /* Native crash reporting uses this inner version because it needs to be somewhat
9223      * decoupled from the AM-managed cleanup lifecycle
9224      */
handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)9225     void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
9226             ApplicationErrorReport.CrashInfo crashInfo) {
9227         EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
9228                 UserHandle.getUserId(Binder.getCallingUid()), processName,
9229                 r == null ? -1 : r.info.flags,
9230                 crashInfo.exceptionClassName,
9231                 crashInfo.exceptionMessage,
9232                 crashInfo.throwFileName,
9233                 crashInfo.throwLineNumber);
9234 
9235         StatsLog.write(StatsLog.APP_CRASH_OCCURRED,
9236                 Binder.getCallingUid(),
9237                 eventType,
9238                 processName,
9239                 Binder.getCallingPid(),
9240                 (r != null && r.info != null) ? r.info.packageName : "",
9241                 (r != null && r.info != null) ? (r.info.isInstantApp()
9242                         ? StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__TRUE
9243                         : StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__FALSE)
9244                         : StatsLog.APP_CRASH_OCCURRED__IS_INSTANT_APP__UNAVAILABLE,
9245                 r != null ? (r.isInterestingToUserLocked()
9246                         ? StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__FOREGROUND
9247                         : StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__BACKGROUND)
9248                         : StatsLog.APP_CRASH_OCCURRED__FOREGROUND_STATE__UNKNOWN,
9249                 processName.equals("system_server") ? ServerProtoEnums.SYSTEM_SERVER
9250                         : (r != null) ? r.getProcessClassEnum()
9251                                       : ServerProtoEnums.ERROR_SOURCE_UNKNOWN
9252         );
9253 
9254         final int relaunchReason = r == null ? RELAUNCH_REASON_NONE
9255                         : r.getWindowProcessController().computeRelaunchReason();
9256         final String relaunchReasonString = relaunchReasonToString(relaunchReason);
9257         if (crashInfo.crashTag == null) {
9258             crashInfo.crashTag = relaunchReasonString;
9259         } else {
9260             crashInfo.crashTag = crashInfo.crashTag + " " + relaunchReasonString;
9261         }
9262 
9263         addErrorToDropBox(
9264                 eventType, r, processName, null, null, null, null, null, null, crashInfo);
9265 
9266         mAppErrors.crashApplication(r, crashInfo);
9267     }
9268 
handleApplicationStrictModeViolation( IBinder app, int penaltyMask, StrictMode.ViolationInfo info)9269     public void handleApplicationStrictModeViolation(
9270             IBinder app,
9271             int penaltyMask,
9272             StrictMode.ViolationInfo info) {
9273         // We're okay if the ProcessRecord is missing; it probably means that
9274         // we're reporting a violation from the system process itself.
9275         final ProcessRecord r = findAppProcess(app, "StrictMode");
9276 
9277         if ((penaltyMask & StrictMode.PENALTY_DROPBOX) != 0) {
9278             Integer stackFingerprint = info.hashCode();
9279             boolean logIt = true;
9280             synchronized (mAlreadyLoggedViolatedStacks) {
9281                 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
9282                     logIt = false;
9283                     // TODO: sub-sample into EventLog for these, with
9284                     // the info.durationMillis?  Then we'd get
9285                     // the relative pain numbers, without logging all
9286                     // the stack traces repeatedly.  We'd want to do
9287                     // likewise in the client code, which also does
9288                     // dup suppression, before the Binder call.
9289                 } else {
9290                     if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
9291                         mAlreadyLoggedViolatedStacks.clear();
9292                     }
9293                     mAlreadyLoggedViolatedStacks.add(stackFingerprint);
9294                 }
9295             }
9296             if (logIt) {
9297                 logStrictModeViolationToDropBox(r, info);
9298             }
9299         }
9300 
9301         if ((penaltyMask & StrictMode.PENALTY_DIALOG) != 0) {
9302             AppErrorResult result = new AppErrorResult();
9303             synchronized (this) {
9304                 final long origId = Binder.clearCallingIdentity();
9305 
9306                 Message msg = Message.obtain();
9307                 msg.what = SHOW_STRICT_MODE_VIOLATION_UI_MSG;
9308                 HashMap<String, Object> data = new HashMap<String, Object>();
9309                 data.put("result", result);
9310                 data.put("app", r);
9311                 data.put("info", info);
9312                 msg.obj = data;
9313                 mUiHandler.sendMessage(msg);
9314 
9315                 Binder.restoreCallingIdentity(origId);
9316             }
9317             int res = result.get();
9318             Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
9319         }
9320     }
9321 
9322     // Depending on the policy in effect, there could be a bunch of
9323     // these in quick succession so we try to batch these together to
9324     // minimize disk writes, number of dropbox entries, and maximize
9325     // compression, by having more fewer, larger records.
logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)9326     private void logStrictModeViolationToDropBox(
9327             ProcessRecord process,
9328             StrictMode.ViolationInfo info) {
9329         if (info == null) {
9330             return;
9331         }
9332         final boolean isSystemApp = process == null ||
9333                 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
9334                                        ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
9335         final String processName = process == null ? "unknown" : process.processName;
9336         final DropBoxManager dbox = (DropBoxManager)
9337                 mContext.getSystemService(Context.DROPBOX_SERVICE);
9338 
9339         // Exit early if the dropbox isn't configured to accept this report type.
9340         final String dropboxTag = processClass(process) + "_strictmode";
9341         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9342 
9343         final StringBuilder sb = new StringBuilder(1024);
9344         synchronized (sb) {
9345             appendDropBoxProcessHeaders(process, processName, sb);
9346             sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9347             sb.append("System-App: ").append(isSystemApp).append("\n");
9348             sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
9349             if (info.violationNumThisLoop != 0) {
9350                 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
9351             }
9352             if (info.numAnimationsRunning != 0) {
9353                 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
9354             }
9355             if (info.broadcastIntentAction != null) {
9356                 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
9357             }
9358             if (info.durationMillis != -1) {
9359                 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
9360             }
9361             if (info.numInstances != -1) {
9362                 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
9363             }
9364             if (info.tags != null) {
9365                 for (String tag : info.tags) {
9366                     sb.append("Span-Tag: ").append(tag).append("\n");
9367                 }
9368             }
9369             sb.append("\n");
9370             sb.append(info.getStackTrace());
9371             sb.append("\n");
9372             if (info.getViolationDetails() != null) {
9373                 sb.append(info.getViolationDetails());
9374                 sb.append("\n");
9375             }
9376         }
9377 
9378         final String res = sb.toString();
9379         IoThread.getHandler().post(() -> {
9380             dbox.addText(dropboxTag, res);
9381         });
9382     }
9383 
9384     /**
9385      * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
9386      * @param app object of the crashing app, null for the system server
9387      * @param tag reported by the caller
9388      * @param system whether this wtf is coming from the system
9389      * @param crashInfo describing the context of the error
9390      * @return true if the process should exit immediately (WTF is fatal)
9391      */
handleApplicationWtf(final IBinder app, final String tag, boolean system, final ApplicationErrorReport.ParcelableCrashInfo crashInfo)9392     public boolean handleApplicationWtf(final IBinder app, final String tag, boolean system,
9393             final ApplicationErrorReport.ParcelableCrashInfo crashInfo) {
9394         final int callingUid = Binder.getCallingUid();
9395         final int callingPid = Binder.getCallingPid();
9396 
9397         if (system) {
9398             // If this is coming from the system, we could very well have low-level
9399             // system locks held, so we want to do this all asynchronously.  And we
9400             // never want this to become fatal, so there is that too.
9401             mHandler.post(new Runnable() {
9402                 @Override public void run() {
9403                     handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo);
9404                 }
9405             });
9406             return false;
9407         }
9408 
9409         final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag,
9410                 crashInfo);
9411 
9412         final boolean isFatal = Build.IS_ENG || Settings.Global
9413                 .getInt(mContext.getContentResolver(), Settings.Global.WTF_IS_FATAL, 0) != 0;
9414         final boolean isSystem = (r == null) || r.isPersistent();
9415 
9416         if (isFatal && !isSystem) {
9417             mAppErrors.crashApplication(r, crashInfo);
9418             return true;
9419         } else {
9420             return false;
9421         }
9422     }
9423 
handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, final ApplicationErrorReport.CrashInfo crashInfo)9424     ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag,
9425             final ApplicationErrorReport.CrashInfo crashInfo) {
9426         final ProcessRecord r = findAppProcess(app, "WTF");
9427         final String processName = app == null ? "system_server"
9428                 : (r == null ? "unknown" : r.processName);
9429 
9430         EventLog.writeEvent(EventLogTags.AM_WTF, UserHandle.getUserId(callingUid), callingPid,
9431                 processName, r == null ? -1 : r.info.flags, tag, crashInfo.exceptionMessage);
9432 
9433         StatsLog.write(StatsLog.WTF_OCCURRED, callingUid, tag, processName,
9434                 callingPid, (r != null) ? r.getProcessClassEnum() : 0);
9435 
9436         addErrorToDropBox("wtf", r, processName, null, null, null, tag, null, null, crashInfo);
9437 
9438         return r;
9439     }
9440 
9441     /**
9442      * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
9443      * @return the corresponding {@link ProcessRecord} object, or null if none could be found
9444      */
findAppProcess(IBinder app, String reason)9445     private ProcessRecord findAppProcess(IBinder app, String reason) {
9446         if (app == null) {
9447             return null;
9448         }
9449 
9450         synchronized (this) {
9451             return mProcessList.findAppProcessLocked(app, reason);
9452         }
9453     }
9454 
9455     /**
9456      * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
9457      * to append various headers to the dropbox log text.
9458      */
appendDropBoxProcessHeaders(ProcessRecord process, String processName, StringBuilder sb)9459     private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
9460             StringBuilder sb) {
9461         // Watchdog thread ends up invoking this function (with
9462         // a null ProcessRecord) to add the stack file to dropbox.
9463         // Do not acquire a lock on this (am) in such cases, as it
9464         // could cause a potential deadlock, if and when watchdog
9465         // is invoked due to unavailability of lock on am and it
9466         // would prevent watchdog from killing system_server.
9467         if (process == null) {
9468             sb.append("Process: ").append(processName).append("\n");
9469             return;
9470         }
9471         // Note: ProcessRecord 'process' is guarded by the service
9472         // instance.  (notably process.pkgList, which could otherwise change
9473         // concurrently during execution of this method)
9474         synchronized (this) {
9475             sb.append("Process: ").append(processName).append("\n");
9476             sb.append("PID: ").append(process.pid).append("\n");
9477             sb.append("UID: ").append(process.uid).append("\n");
9478             int flags = process.info.flags;
9479             IPackageManager pm = AppGlobals.getPackageManager();
9480             sb.append("Flags: 0x").append(Integer.toHexString(flags)).append("\n");
9481             for (int ip=0; ip<process.pkgList.size(); ip++) {
9482                 String pkg = process.pkgList.keyAt(ip);
9483                 sb.append("Package: ").append(pkg);
9484                 try {
9485                     PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
9486                     if (pi != null) {
9487                         sb.append(" v").append(pi.getLongVersionCode());
9488                         if (pi.versionName != null) {
9489                             sb.append(" (").append(pi.versionName).append(")");
9490                         }
9491                     }
9492                 } catch (RemoteException e) {
9493                     Slog.e(TAG, "Error getting package info: " + pkg, e);
9494                 }
9495                 sb.append("\n");
9496             }
9497             if (process.info.isInstantApp()) {
9498                 sb.append("Instant-App: true\n");
9499             }
9500         }
9501     }
9502 
processClass(ProcessRecord process)9503     private static String processClass(ProcessRecord process) {
9504         if (process == null || process.pid == MY_PID) {
9505             return "system_server";
9506         } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9507             return "system_app";
9508         } else {
9509             return "data_app";
9510         }
9511     }
9512 
9513     private volatile long mWtfClusterStart;
9514     private volatile int mWtfClusterCount;
9515 
9516     /**
9517      * Write a description of an error (crash, WTF, ANR) to the drop box.
9518      * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
9519      * @param process which caused the error, null means the system server
9520      * @param activityShortComponentName which triggered the error, null if unknown
9521      * @param parentShortComponentName activity related to the error, null if unknown
9522      * @param parentProcess parent process
9523      * @param subject line related to the error, null if absent
9524      * @param report in long form describing the error, null if absent
9525      * @param dataFile text file to include in the report, null if none
9526      * @param crashInfo giving an application stack trace, null if absent
9527      */
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)9528     public void addErrorToDropBox(String eventType,
9529             ProcessRecord process, String processName, String activityShortComponentName,
9530             String parentShortComponentName, ProcessRecord parentProcess,
9531             String subject, final String report, final File dataFile,
9532             final ApplicationErrorReport.CrashInfo crashInfo) {
9533         // NOTE -- this must never acquire the ActivityManagerService lock,
9534         // otherwise the watchdog may be prevented from resetting the system.
9535 
9536         // Bail early if not published yet
9537         if (ServiceManager.getService(Context.DROPBOX_SERVICE) == null) return;
9538         final DropBoxManager dbox = mContext.getSystemService(DropBoxManager.class);
9539 
9540         // Exit early if the dropbox isn't configured to accept this report type.
9541         final String dropboxTag = processClass(process) + "_" + eventType;
9542         if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
9543 
9544         // Rate-limit how often we're willing to do the heavy lifting below to
9545         // collect and record logs; currently 5 logs per 10 second period.
9546         final long now = SystemClock.elapsedRealtime();
9547         if (now - mWtfClusterStart > 10 * DateUtils.SECOND_IN_MILLIS) {
9548             mWtfClusterStart = now;
9549             mWtfClusterCount = 1;
9550         } else {
9551             if (mWtfClusterCount++ >= 5) return;
9552         }
9553 
9554         final StringBuilder sb = new StringBuilder(1024);
9555         appendDropBoxProcessHeaders(process, processName, sb);
9556         if (process != null) {
9557             sb.append("Foreground: ")
9558                     .append(process.isInterestingToUserLocked() ? "Yes" : "No")
9559                     .append("\n");
9560         }
9561         if (activityShortComponentName != null) {
9562             sb.append("Activity: ").append(activityShortComponentName).append("\n");
9563         }
9564         if (parentShortComponentName != null) {
9565             if (parentProcess != null && parentProcess.pid != process.pid) {
9566                 sb.append("Parent-Process: ").append(parentProcess.processName).append("\n");
9567             }
9568             if (!parentShortComponentName.equals(activityShortComponentName)) {
9569                 sb.append("Parent-Activity: ").append(parentShortComponentName).append("\n");
9570             }
9571         }
9572         if (subject != null) {
9573             sb.append("Subject: ").append(subject).append("\n");
9574         }
9575         sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
9576         if (Debug.isDebuggerConnected()) {
9577             sb.append("Debugger: Connected\n");
9578         }
9579         if (crashInfo != null && crashInfo.crashTag != null && !crashInfo.crashTag.isEmpty()) {
9580             sb.append("Crash-Tag: ").append(crashInfo.crashTag).append("\n");
9581         }
9582         sb.append("\n");
9583 
9584         // Do the rest in a worker thread to avoid blocking the caller on I/O
9585         // (After this point, we shouldn't access AMS internal data structures.)
9586         Thread worker = new Thread("Error dump: " + dropboxTag) {
9587             @Override
9588             public void run() {
9589                 if (report != null) {
9590                     sb.append(report);
9591                 }
9592 
9593                 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
9594                 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
9595                 int maxDataFileSize = DROPBOX_MAX_SIZE - sb.length()
9596                         - lines * RESERVED_BYTES_PER_LOGCAT_LINE;
9597 
9598                 if (dataFile != null && maxDataFileSize > 0) {
9599                     try {
9600                         sb.append(FileUtils.readTextFile(dataFile, maxDataFileSize,
9601                                     "\n\n[[TRUNCATED]]"));
9602                     } catch (IOException e) {
9603                         Slog.e(TAG, "Error reading " + dataFile, e);
9604                     }
9605                 }
9606                 if (crashInfo != null && crashInfo.stackTrace != null) {
9607                     sb.append(crashInfo.stackTrace);
9608                 }
9609 
9610                 if (lines > 0) {
9611                     sb.append("\n");
9612 
9613                     // Merge several logcat streams, and take the last N lines
9614                     InputStreamReader input = null;
9615                     try {
9616                         java.lang.Process logcat = new ProcessBuilder(
9617                                 "/system/bin/timeout", "-k", "15s", "10s",
9618                                 "/system/bin/logcat", "-v", "threadtime", "-b", "events", "-b", "system",
9619                                 "-b", "main", "-b", "crash", "-t", String.valueOf(lines))
9620                                         .redirectErrorStream(true).start();
9621 
9622                         try { logcat.getOutputStream().close(); } catch (IOException e) {}
9623                         try { logcat.getErrorStream().close(); } catch (IOException e) {}
9624                         input = new InputStreamReader(logcat.getInputStream());
9625 
9626                         int num;
9627                         char[] buf = new char[8192];
9628                         while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
9629                     } catch (IOException e) {
9630                         Slog.e(TAG, "Error running logcat", e);
9631                     } finally {
9632                         if (input != null) try { input.close(); } catch (IOException e) {}
9633                     }
9634                 }
9635 
9636                 dbox.addText(dropboxTag, sb.toString());
9637             }
9638         };
9639 
9640         if (process == null) {
9641             // If process is null, we are being called from some internal code
9642             // and may be about to die -- run this synchronously.
9643             final int oldMask = StrictMode.allowThreadDiskWritesMask();
9644             try {
9645                 worker.run();
9646             } finally {
9647                 StrictMode.setThreadPolicyMask(oldMask);
9648             }
9649         } else {
9650             worker.start();
9651         }
9652     }
9653 
9654     @Override
getProcessesInErrorState()9655     public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
9656         enforceNotIsolatedCaller("getProcessesInErrorState");
9657         // assume our apps are happy - lazy create the list
9658         List<ActivityManager.ProcessErrorStateInfo> errList = null;
9659 
9660         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9661                 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
9662         int userId = UserHandle.getUserId(Binder.getCallingUid());
9663 
9664         synchronized (this) {
9665 
9666             // iterate across all processes
9667             for (int i=mProcessList.mLruProcesses.size()-1; i>=0; i--) {
9668                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
9669                 if (!allUsers && app.userId != userId) {
9670                     continue;
9671                 }
9672                 final boolean crashing = app.isCrashing();
9673                 final boolean notResponding = app.isNotResponding();
9674                 if ((app.thread != null) && (crashing || notResponding)) {
9675                     // This one's in trouble, so we'll generate a report for it
9676                     // crashes are higher priority (in case there's a crash *and* an anr)
9677                     ActivityManager.ProcessErrorStateInfo report = null;
9678                     if (crashing) {
9679                         report = app.crashingReport;
9680                     } else if (notResponding) {
9681                         report = app.notRespondingReport;
9682                     }
9683 
9684                     if (report != null) {
9685                         if (errList == null) {
9686                             errList = new ArrayList<>(1);
9687                         }
9688                         errList.add(report);
9689                     } else {
9690                         Slog.w(TAG, "Missing app error report, app = " + app.processName +
9691                                 " crashing = " + crashing +
9692                                 " notResponding = " + notResponding);
9693                     }
9694                 }
9695             }
9696         }
9697 
9698         return errList;
9699     }
9700 
9701     @Override
getRunningAppProcesses()9702     public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
9703         enforceNotIsolatedCaller("getRunningAppProcesses");
9704 
9705         final int callingUid = Binder.getCallingUid();
9706         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9707 
9708         final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
9709                 callingUid) == PackageManager.PERMISSION_GRANTED;
9710         final int userId = UserHandle.getUserId(callingUid);
9711         final boolean allUids = mAtmInternal.isGetTasksAllowed(
9712                 "getRunningAppProcesses", Binder.getCallingPid(), callingUid);
9713 
9714         synchronized (this) {
9715             // Iterate across all processes
9716             return mProcessList.getRunningAppProcessesLocked(allUsers, userId, allUids,
9717                     callingUid, clientTargetSdk);
9718         }
9719     }
9720 
9721     @Override
getRunningExternalApplications()9722     public List<ApplicationInfo> getRunningExternalApplications() {
9723         enforceNotIsolatedCaller("getRunningExternalApplications");
9724         List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
9725         List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
9726         if (runningApps != null && runningApps.size() > 0) {
9727             Set<String> extList = new HashSet<String>();
9728             for (ActivityManager.RunningAppProcessInfo app : runningApps) {
9729                 if (app.pkgList != null) {
9730                     for (String pkg : app.pkgList) {
9731                         extList.add(pkg);
9732                     }
9733                 }
9734             }
9735             IPackageManager pm = AppGlobals.getPackageManager();
9736             for (String pkg : extList) {
9737                 try {
9738                     ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
9739                     if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
9740                         retList.add(info);
9741                     }
9742                 } catch (RemoteException e) {
9743                 }
9744             }
9745         }
9746         return retList;
9747     }
9748 
9749     @Override
getMyMemoryState(ActivityManager.RunningAppProcessInfo outState)9750     public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outState) {
9751         if (outState == null) {
9752             throw new IllegalArgumentException("outState is null");
9753         }
9754         enforceNotIsolatedCaller("getMyMemoryState");
9755 
9756         final int callingUid = Binder.getCallingUid();
9757         final int clientTargetSdk = mPackageManagerInt.getUidTargetSdkVersion(callingUid);
9758 
9759         synchronized (this) {
9760             ProcessRecord proc;
9761             synchronized (mPidsSelfLocked) {
9762                 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9763             }
9764             if (proc != null) {
9765                 mProcessList.fillInProcMemInfoLocked(proc, outState, clientTargetSdk);
9766             }
9767         }
9768     }
9769 
9770     @Override
getMemoryTrimLevel()9771     public int getMemoryTrimLevel() {
9772         enforceNotIsolatedCaller("getMyMemoryState");
9773         synchronized (this) {
9774             return mLastMemoryLevel;
9775         }
9776     }
9777 
9778     @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)9779     public void onShellCommand(FileDescriptor in, FileDescriptor out,
9780             FileDescriptor err, String[] args, ShellCallback callback,
9781             ResultReceiver resultReceiver) {
9782         (new ActivityManagerShellCommand(this, false)).exec(
9783                 this, in, out, err, args, callback, resultReceiver);
9784     }
9785 
9786     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)9787     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
9788         PriorityDump.dump(mPriorityDumper, fd, pw, args);
9789     }
9790 
dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority, int dumpAppId)9791     private void dumpEverything(FileDescriptor fd, PrintWriter pw, String[] args, int opti,
9792             boolean dumpAll, String dumpPackage, boolean dumpClient, boolean dumpNormalPriority,
9793             int dumpAppId) {
9794 
9795         ActiveServices.ServiceDumper sdumper;
9796 
9797         synchronized(this) {
9798             mConstants.dump(pw);
9799             mOomAdjuster.dumpAppCompactorSettings(pw);
9800             pw.println();
9801             if (dumpAll) {
9802                 pw.println("-------------------------------------------------------------------------------");
9803 
9804             }
9805             dumpAllowedAssociationsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9806             pw.println();
9807             if (dumpAll) {
9808                 pw.println("-------------------------------------------------------------------------------");
9809 
9810             }
9811             mPendingIntentController.dumpPendingIntents(pw, dumpAll, dumpPackage);
9812             pw.println();
9813             if (dumpAll) {
9814                 pw.println("-------------------------------------------------------------------------------");
9815             }
9816             dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9817             pw.println();
9818             if (dumpAll) {
9819                 pw.println("-------------------------------------------------------------------------------");
9820             }
9821             if (dumpAll || dumpPackage != null) {
9822                 dumpBroadcastStatsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9823                 pw.println();
9824                 if (dumpAll) {
9825                     pw.println("-------------------------------------------------------------------------------");
9826                 }
9827             }
9828             dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9829             pw.println();
9830             if (dumpAll) {
9831                 pw.println("-------------------------------------------------------------------------------");
9832             }
9833             dumpPermissionsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9834             pw.println();
9835             sdumper = mServices.newServiceDumperLocked(fd, pw, args, opti, dumpAll, dumpPackage);
9836             if (!dumpClient) {
9837                 if (dumpAll) {
9838                     pw.println("-------------------------------------------------------------------------------");
9839                 }
9840                 sdumper.dumpLocked();
9841             }
9842         }
9843         // We drop the lock here because we can't call dumpWithClient() with the lock held;
9844         // if the caller wants a consistent state for the !dumpClient case, it can call this
9845         // method with the lock held.
9846         if (dumpClient) {
9847             if (dumpAll) {
9848                 pw.println("-------------------------------------------------------------------------------");
9849             }
9850             sdumper.dumpWithClient();
9851         }
9852         if (dumpPackage == null) {
9853             // Intentionally dropping the lock for this, because dumpBinderProxies() will make many
9854             // outgoing binder calls to retrieve interface descriptors; while that is system code,
9855             // there is nothing preventing an app from overriding this implementation by talking to
9856             // the binder driver directly, and hang up system_server in the process. So, dump
9857             // without locks held, and even then only when there is an unreasonably large number of
9858             // proxies in the first place.
9859             pw.println();
9860             if (dumpAll) {
9861                 pw.println("-------------------------------------------------------------------------------");
9862             }
9863             dumpBinderProxies(pw, BINDER_PROXY_HIGH_WATERMARK /* minToDump */);
9864         }
9865         synchronized(this) {
9866             pw.println();
9867             if (dumpAll) {
9868                 pw.println("-------------------------------------------------------------------------------");
9869             }
9870             mAtmInternal.dump(
9871                     DUMP_RECENTS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9872             pw.println();
9873             if (dumpAll) {
9874                 pw.println("-------------------------------------------------------------------------------");
9875             }
9876             mAtmInternal.dump(
9877                     DUMP_LASTANR_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9878             pw.println();
9879             if (dumpAll) {
9880                 pw.println("-------------------------------------------------------------------------------");
9881             }
9882             mAtmInternal.dump(
9883                     DUMP_STARTER_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9884             pw.println();
9885             if (dumpAll) {
9886                 pw.println("-------------------------------------------------------------------------------");
9887             }
9888             mAtmInternal.dump(
9889                     DUMP_CONTAINERS_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9890             // Activities section is dumped as part of the Critical priority dump. Exclude the
9891             // section if priority is Normal.
9892             if (!dumpNormalPriority) {
9893                 pw.println();
9894                 if (dumpAll) {
9895                     pw.println("-------------------------------------------------------------------------------");
9896                 }
9897                 mAtmInternal.dump(
9898                         DUMP_ACTIVITIES_CMD, fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9899             }
9900             if (mAssociations.size() > 0) {
9901                 pw.println();
9902                 if (dumpAll) {
9903                     pw.println("-------------------------------------------------------------------------------");
9904                 }
9905                 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
9906             }
9907             if (dumpPackage == null) {
9908                 pw.println();
9909                 if (dumpAll) {
9910                     pw.println("-------------------------------------------------------------------------------");
9911                 }
9912                 mOomAdjProfiler.dump(pw);
9913                 pw.println();
9914                 if (dumpAll) {
9915                     pw.println("-------------------------------------------------------------------------------");
9916                 }
9917                 dumpLmkLocked(pw);
9918             }
9919             pw.println();
9920             if (dumpAll) {
9921                 pw.println("-------------------------------------------------------------------------------");
9922             }
9923             dumpLruLocked(pw, dumpPackage);
9924             pw.println();
9925             if (dumpAll) {
9926                 pw.println("-------------------------------------------------------------------------------");
9927             }
9928             dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage, dumpAppId);
9929         }
9930     }
9931 
9932     /**
9933      * Wrapper function to print out debug data filtered by specified arguments.
9934     */
doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto)9935     private void doDump(FileDescriptor fd, PrintWriter pw, String[] args, boolean useProto) {
9936         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
9937 
9938         boolean dumpAll = false;
9939         boolean dumpClient = false;
9940         boolean dumpCheckin = false;
9941         boolean dumpCheckinFormat = false;
9942         boolean dumpNormalPriority = false;
9943         boolean dumpVisibleStacksOnly = false;
9944         boolean dumpFocusedStackOnly = false;
9945         String dumpPackage = null;
9946 
9947         int opti = 0;
9948         while (opti < args.length) {
9949             String opt = args[opti];
9950             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9951                 break;
9952             }
9953             opti++;
9954             if ("-a".equals(opt)) {
9955                 dumpAll = true;
9956             } else if ("-c".equals(opt)) {
9957                 dumpClient = true;
9958             } else if ("-v".equals(opt)) {
9959                 dumpVisibleStacksOnly = true;
9960             } else if ("-f".equals(opt)) {
9961                 dumpFocusedStackOnly = true;
9962             } else if ("-p".equals(opt)) {
9963                 if (opti < args.length) {
9964                     dumpPackage = args[opti];
9965                     opti++;
9966                 } else {
9967                     pw.println("Error: -p option requires package argument");
9968                     return;
9969                 }
9970                 dumpClient = true;
9971             } else if ("--checkin".equals(opt)) {
9972                 dumpCheckin = dumpCheckinFormat = true;
9973             } else if ("-C".equals(opt)) {
9974                 dumpCheckinFormat = true;
9975             } else if ("--normal-priority".equals(opt)) {
9976                 dumpNormalPriority = true;
9977             } else if ("-h".equals(opt)) {
9978                 ActivityManagerShellCommand.dumpHelp(pw, true);
9979                 return;
9980             } else {
9981                 pw.println("Unknown argument: " + opt + "; use -h for help");
9982             }
9983         }
9984 
9985         long origId = Binder.clearCallingIdentity();
9986 
9987         if (useProto) {
9988             final ProtoOutputStream proto = new ProtoOutputStream(fd);
9989             String cmd = opti < args.length ? args[opti] : "";
9990             opti++;
9991 
9992             if ("activities".equals(cmd) || "a".equals(cmd)) {
9993                 // output proto is ActivityManagerServiceDumpActivitiesProto
9994                 mAtmInternal.writeActivitiesToProto(proto);
9995             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
9996                 // output proto is ActivityManagerServiceDumpBroadcastsProto
9997                 synchronized (this) {
9998                     writeBroadcastsToProtoLocked(proto);
9999                 }
10000             } else if ("provider".equals(cmd)) {
10001                 String[] newArgs;
10002                 String name;
10003                 if (opti >= args.length) {
10004                     name = null;
10005                     newArgs = EMPTY_STRING_ARRAY;
10006                 } else {
10007                     name = args[opti];
10008                     opti++;
10009                     newArgs = new String[args.length - opti];
10010                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10011                             args.length - opti);
10012                 }
10013                 if (!dumpProviderProto(fd, pw, name, newArgs)) {
10014                     pw.println("No providers match: " + name);
10015                     pw.println("Use -h for help.");
10016                 }
10017             } else if ("service".equals(cmd)) {
10018                 // output proto is ActivityManagerServiceDumpServicesProto
10019                 mServices.writeToProto(proto, ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10020             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10021                 if (opti < args.length) {
10022                     dumpPackage = args[opti];
10023                     opti++;
10024                 }
10025                 // output proto is ProcessProto
10026                 synchronized (this) {
10027                     writeProcessesToProtoLocked(proto, dumpPackage);
10028                 }
10029             } else {
10030                 // default option, dump everything, output is ActivityManagerServiceProto
10031                 synchronized (this) {
10032                     long activityToken = proto.start(ActivityManagerServiceProto.ACTIVITIES);
10033                     mAtmInternal.writeActivitiesToProto(proto);
10034                     proto.end(activityToken);
10035 
10036                     long broadcastToken = proto.start(ActivityManagerServiceProto.BROADCASTS);
10037                     writeBroadcastsToProtoLocked(proto);
10038                     proto.end(broadcastToken);
10039 
10040                     long serviceToken = proto.start(ActivityManagerServiceProto.SERVICES);
10041                     mServices.writeToProto(proto,
10042                             ActivityManagerServiceDumpServicesProto.ACTIVE_SERVICES);
10043                     proto.end(serviceToken);
10044 
10045                     long processToken = proto.start(ActivityManagerServiceProto.PROCESSES);
10046                     writeProcessesToProtoLocked(proto, dumpPackage);
10047                     proto.end(processToken);
10048                 }
10049             }
10050             proto.flush();
10051             Binder.restoreCallingIdentity(origId);
10052             return;
10053         }
10054 
10055         int dumpAppId = getAppId(dumpPackage);
10056         boolean more = false;
10057         // Is the caller requesting to dump a particular piece of data?
10058         if (opti < args.length) {
10059             String cmd = args[opti];
10060             opti++;
10061             if (DUMP_ACTIVITIES_CMD.equals(cmd) || DUMP_ACTIVITIES_SHORT_CMD.equals(cmd)
10062                     || DUMP_LASTANR_CMD.equals(cmd) || DUMP_LASTANR_TRACES_CMD.equals(cmd)
10063                     || DUMP_STARTER_CMD.equals(cmd) || DUMP_CONTAINERS_CMD.equals(cmd)
10064                     || DUMP_RECENTS_CMD.equals(cmd) || DUMP_RECENTS_SHORT_CMD.equals(cmd)) {
10065                 mAtmInternal.dump(
10066                         cmd, fd, pw, args, opti, true /* dumpAll */, dumpClient, dumpPackage);
10067             } else if ("binder-proxies".equals(cmd)) {
10068                 if (opti >= args.length) {
10069                     dumpBinderProxies(pw, 0 /* minToDump */);
10070                 } else {
10071                     String uid = args[opti];
10072                     opti++;
10073                     // Ensure Binder Proxy Count is as up to date as possible
10074                     System.gc();
10075                     System.runFinalization();
10076                     System.gc();
10077                     pw.println(BinderInternal.nGetBinderProxyCount(Integer.parseInt(uid)));
10078                 }
10079             } else if ("allowed-associations".equals(cmd)) {
10080                 if (opti < args.length) {
10081                     dumpPackage = args[opti];
10082                     opti++;
10083                 }
10084                 synchronized (this) {
10085                     dumpAllowedAssociationsLocked(fd, pw, args, opti, true, dumpPackage);
10086                 }
10087             } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
10088                 if (opti < args.length) {
10089                     dumpPackage = args[opti];
10090                     opti++;
10091                 }
10092                 synchronized (this) {
10093                     dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage);
10094                 }
10095             } else if ("broadcast-stats".equals(cmd)) {
10096                 if (opti < args.length) {
10097                     dumpPackage = args[opti];
10098                     opti++;
10099                 }
10100                 synchronized (this) {
10101                     if (dumpCheckinFormat) {
10102                         dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin,
10103                                 dumpPackage);
10104                     } else {
10105                         dumpBroadcastStatsLocked(fd, pw, args, opti, true, dumpPackage);
10106                     }
10107                 }
10108             } else if ("intents".equals(cmd) || "i".equals(cmd)) {
10109                 if (opti < args.length) {
10110                     dumpPackage = args[opti];
10111                     opti++;
10112                 }
10113                 synchronized (this) {
10114                     mPendingIntentController.dumpPendingIntents(pw, true, dumpPackage);
10115                 }
10116             } else if ("processes".equals(cmd) || "p".equals(cmd)) {
10117                 if (opti < args.length) {
10118                     dumpPackage = args[opti];
10119                     opti++;
10120                 }
10121                 synchronized (this) {
10122                     dumpProcessesLocked(fd, pw, args, opti, true, dumpPackage, dumpAppId);
10123                 }
10124             } else if ("oom".equals(cmd) || "o".equals(cmd)) {
10125                 synchronized (this) {
10126                     dumpOomLocked(fd, pw, args, opti, true);
10127                 }
10128             } else if ("lmk".equals(cmd)) {
10129                 synchronized (this) {
10130                     dumpLmkLocked(pw);
10131                 }
10132             } else if ("lru".equals(cmd)) {
10133                 synchronized (this) {
10134                     dumpLruLocked(pw, null);
10135                 }
10136             } else if ("permissions".equals(cmd) || "perm".equals(cmd)) {
10137                 synchronized (this) {
10138                     dumpPermissionsLocked(fd, pw, args, opti, true, null);
10139                 }
10140             } else if ("provider".equals(cmd)) {
10141                 String[] newArgs;
10142                 String name;
10143                 if (opti >= args.length) {
10144                     name = null;
10145                     newArgs = EMPTY_STRING_ARRAY;
10146                 } else {
10147                     name = args[opti];
10148                     opti++;
10149                     newArgs = new String[args.length - opti];
10150                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
10151                 }
10152                 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
10153                     pw.println("No providers match: " + name);
10154                     pw.println("Use -h for help.");
10155                 }
10156             } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
10157                 synchronized (this) {
10158                     dumpProvidersLocked(fd, pw, args, opti, true, null);
10159                 }
10160             } else if ("service".equals(cmd)) {
10161                 String[] newArgs;
10162                 String name;
10163                 if (opti >= args.length) {
10164                     name = null;
10165                     newArgs = EMPTY_STRING_ARRAY;
10166                 } else {
10167                     name = args[opti];
10168                     opti++;
10169                     newArgs = new String[args.length - opti];
10170                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10171                             args.length - opti);
10172                 }
10173                 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
10174                     pw.println("No services match: " + name);
10175                     pw.println("Use -h for help.");
10176                 }
10177             } else if ("package".equals(cmd)) {
10178                 String[] newArgs;
10179                 if (opti >= args.length) {
10180                     pw.println("package: no package name specified");
10181                     pw.println("Use -h for help.");
10182                 } else {
10183                     dumpPackage = args[opti];
10184                     opti++;
10185                     newArgs = new String[args.length - opti];
10186                     if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
10187                             args.length - opti);
10188                     args = newArgs;
10189                     opti = 0;
10190                     more = true;
10191                 }
10192             } else if ("associations".equals(cmd) || "as".equals(cmd)) {
10193                 synchronized (this) {
10194                     dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage);
10195                 }
10196             } else if ("settings".equals(cmd)) {
10197                 synchronized (this) {
10198                     mConstants.dump(pw);
10199                     mOomAdjuster.dumpAppCompactorSettings(pw);
10200                 }
10201             } else if ("services".equals(cmd) || "s".equals(cmd)) {
10202                 if (dumpClient) {
10203                     ActiveServices.ServiceDumper dumper;
10204                     synchronized (this) {
10205                         dumper = mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10206                                 dumpPackage);
10207                     }
10208                     dumper.dumpWithClient();
10209                 } else {
10210                     synchronized (this) {
10211                         mServices.newServiceDumperLocked(fd, pw, args, opti, true,
10212                                 dumpPackage).dumpLocked();
10213                     }
10214                 }
10215             } else if ("locks".equals(cmd)) {
10216                 LockGuard.dump(fd, pw, args);
10217             } else {
10218                 // Dumping a single activity?
10219                 if (!mAtmInternal.dumpActivity(fd, pw, cmd, args, opti, dumpAll,
10220                         dumpVisibleStacksOnly, dumpFocusedStackOnly)) {
10221                     ActivityManagerShellCommand shell = new ActivityManagerShellCommand(this, true);
10222                     int res = shell.exec(this, null, fd, null, args, null,
10223                             new ResultReceiver(null));
10224                     if (res < 0) {
10225                         pw.println("Bad activity command, or no activities match: " + cmd);
10226                         pw.println("Use -h for help.");
10227                     }
10228                 }
10229             }
10230             if (!more) {
10231                 Binder.restoreCallingIdentity(origId);
10232                 return;
10233             }
10234         }
10235 
10236         // No piece of data specified, dump everything.
10237         if (dumpCheckinFormat) {
10238             dumpBroadcastStatsCheckinLocked(fd, pw, args, opti, dumpCheckin, dumpPackage);
10239         } else {
10240             if (dumpClient) {
10241                 // dumpEverything() will take the lock when needed, and momentarily drop
10242                 // it for dumping client state.
10243                 dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
10244                         dumpNormalPriority, dumpAppId);
10245             } else {
10246                 // Take the lock here, so we get a consistent state for the entire dump;
10247                 // dumpEverything() will take the lock as well, but that is fine.
10248                 synchronized(this) {
10249                     dumpEverything(fd, pw, args, opti, dumpAll, dumpPackage, dumpClient,
10250                             dumpNormalPriority, dumpAppId);
10251                 }
10252             }
10253         }
10254         Binder.restoreCallingIdentity(origId);
10255     }
10256 
dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)10257     void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10258             int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
10259         pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)");
10260 
10261         int dumpUid = 0;
10262         if (dumpPackage != null) {
10263             IPackageManager pm = AppGlobals.getPackageManager();
10264             try {
10265                 dumpUid = pm.getPackageUid(dumpPackage, MATCH_ANY_USER, 0);
10266             } catch (RemoteException e) {
10267             }
10268         }
10269 
10270         boolean printedAnything = false;
10271 
10272         final long now = SystemClock.uptimeMillis();
10273 
10274         for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
10275             ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
10276                     = mAssociations.valueAt(i1);
10277             for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
10278                 SparseArray<ArrayMap<String, Association>> sourceUids
10279                         = targetComponents.valueAt(i2);
10280                 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) {
10281                     ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3);
10282                     for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
10283                         Association ass = sourceProcesses.valueAt(i4);
10284                         if (dumpPackage != null) {
10285                             if (!ass.mTargetComponent.getPackageName().equals(dumpPackage)
10286                                     && UserHandle.getAppId(ass.mSourceUid) != dumpUid) {
10287                                 continue;
10288                             }
10289                         }
10290                         printedAnything = true;
10291                         pw.print("  ");
10292                         pw.print(ass.mTargetProcess);
10293                         pw.print("/");
10294                         UserHandle.formatUid(pw, ass.mTargetUid);
10295                         pw.print(" <- ");
10296                         pw.print(ass.mSourceProcess);
10297                         pw.print("/");
10298                         UserHandle.formatUid(pw, ass.mSourceUid);
10299                         pw.println();
10300                         pw.print("    via ");
10301                         pw.print(ass.mTargetComponent.flattenToShortString());
10302                         pw.println();
10303                         pw.print("    ");
10304                         long dur = ass.mTime;
10305                         if (ass.mNesting > 0) {
10306                             dur += now - ass.mStartTime;
10307                         }
10308                         TimeUtils.formatDuration(dur, pw);
10309                         pw.print(" (");
10310                         pw.print(ass.mCount);
10311                         pw.print(" times)");
10312                         pw.print("  ");
10313                         for (int i=0; i<ass.mStateTimes.length; i++) {
10314                             long amt = ass.mStateTimes[i];
10315                             if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10316                                 amt += now - ass.mLastStateUptime;
10317                             }
10318                             if (amt != 0) {
10319                                 pw.print(" ");
10320                                 pw.print(ProcessList.makeProcStateString(
10321                                             i + ActivityManager.MIN_PROCESS_STATE));
10322                                 pw.print("=");
10323                                 TimeUtils.formatDuration(amt, pw);
10324                                 if ((ass.mLastState-ActivityManager.MIN_PROCESS_STATE) == i) {
10325                                     pw.print("*");
10326                                 }
10327                             }
10328                         }
10329                         pw.println();
10330                         if (ass.mNesting > 0) {
10331                             pw.print("    Currently active: ");
10332                             TimeUtils.formatDuration(now - ass.mStartTime, pw);
10333                             pw.println();
10334                         }
10335                     }
10336                 }
10337             }
10338 
10339         }
10340 
10341         if (!printedAnything) {
10342             pw.println("  (nothing)");
10343         }
10344     }
10345 
getAppId(String dumpPackage)10346     private int getAppId(String dumpPackage) {
10347         if (dumpPackage != null) {
10348             try {
10349                 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
10350                         dumpPackage, 0);
10351                 return UserHandle.getAppId(info.uid);
10352             } catch (NameNotFoundException e) {
10353                 e.printStackTrace();
10354             }
10355         }
10356         return -1;
10357     }
10358 
dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids, String header, boolean needSep)10359     boolean dumpUids(PrintWriter pw, String dumpPackage, int dumpAppId, ActiveUids uids,
10360                 String header, boolean needSep) {
10361         boolean printed = false;
10362         for (int i=0; i<uids.size(); i++) {
10363             UidRecord uidRec = uids.valueAt(i);
10364             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != dumpAppId) {
10365                 continue;
10366             }
10367             if (!printed) {
10368                 printed = true;
10369                 if (needSep) {
10370                     pw.println();
10371                 }
10372                 pw.print("  ");
10373                 pw.println(header);
10374                 needSep = true;
10375             }
10376             pw.print("    UID "); UserHandle.formatUid(pw, uidRec.uid);
10377             pw.print(": "); pw.println(uidRec);
10378         }
10379         return printed;
10380     }
10381 
dumpBinderProxyInterfaceCounts(PrintWriter pw, String header)10382     void dumpBinderProxyInterfaceCounts(PrintWriter pw, String header) {
10383         final BinderProxy.InterfaceCount[] proxyCounts = BinderProxy.getSortedInterfaceCounts(50);
10384 
10385         pw.println(header);
10386         for (int i = 0; i < proxyCounts.length; i++) {
10387             pw.println("    #" + (i + 1) + ": " + proxyCounts[i]);
10388         }
10389     }
10390 
dumpBinderProxiesCounts(PrintWriter pw, String header)10391     boolean dumpBinderProxiesCounts(PrintWriter pw, String header) {
10392         SparseIntArray counts = BinderInternal.nGetBinderProxyPerUidCounts();
10393         if(counts != null) {
10394             pw.println(header);
10395             for (int i = 0; i < counts.size(); i++) {
10396                 final int uid = counts.keyAt(i);
10397                 final int binderCount = counts.valueAt(i);
10398                 pw.print("    UID ");
10399                 pw.print(uid);
10400                 pw.print(", binder count = ");
10401                 pw.print(binderCount);
10402                 pw.print(", package(s)= ");
10403                 final String[] pkgNames = mContext.getPackageManager().getPackagesForUid(uid);
10404                 if (pkgNames != null) {
10405                     for (int j = 0; j < pkgNames.length; j++) {
10406                         pw.print(pkgNames[j]);
10407                         pw.print("; ");
10408                     }
10409                 } else {
10410                     pw.print("NO PACKAGE NAME FOUND");
10411                 }
10412                 pw.println();
10413             }
10414             return true;
10415         }
10416         return false;
10417     }
10418 
dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces)10419     void dumpBinderProxies(PrintWriter pw, int minCountToDumpInterfaces) {
10420         pw.println("ACTIVITY MANAGER BINDER PROXY STATE (dumpsys activity binder-proxies)");
10421         final int proxyCount = BinderProxy.getProxyCount();
10422         if (proxyCount >= minCountToDumpInterfaces) {
10423             dumpBinderProxyInterfaceCounts(pw,
10424                     "Top proxy interface names held by SYSTEM");
10425         } else {
10426             pw.print("Not dumping proxy interface counts because size ("
10427                     + Integer.toString(proxyCount) + ") looks reasonable");
10428             pw.println();
10429         }
10430         dumpBinderProxiesCounts(pw,
10431                 "  Counts of Binder Proxies held by SYSTEM");
10432     }
10433 
dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc)10434     void dumpLruEntryLocked(PrintWriter pw, int index, ProcessRecord proc) {
10435         pw.print("    #");
10436         pw.print(index);
10437         pw.print(": ");
10438         pw.print(ProcessList.makeOomAdjString(proc.setAdj, false));
10439         pw.print(" ");
10440         pw.print(ProcessList.makeProcStateString(proc.getCurProcState()));
10441         pw.print(" ");
10442         pw.print(proc.toShortString());
10443         pw.print(" ");
10444         if (proc.hasActivitiesOrRecentTasks() || proc.hasClientActivities()
10445                 || proc.treatLikeActivity) {
10446             pw.print(" activity=");
10447             boolean printed = false;
10448             if (proc.hasActivities()) {
10449                 pw.print("activities");
10450                 printed = true;
10451             }
10452             if (proc.hasRecentTasks()) {
10453                 if (printed) {
10454                     pw.print("|");
10455                 }
10456                 pw.print("recents");
10457                 printed = true;
10458             }
10459             if (proc.hasClientActivities()) {
10460                 if (printed) {
10461                     pw.print("|");
10462                 }
10463                 pw.print("client");
10464                 printed = true;
10465             }
10466             if (proc.treatLikeActivity) {
10467                 if (printed) {
10468                     pw.print("|");
10469                 }
10470                 pw.print("treated");
10471             }
10472         }
10473         pw.println();
10474     }
10475 
10476     // TODO: Move to ProcessList?
dumpLruLocked(PrintWriter pw, String dumpPackage)10477     void dumpLruLocked(PrintWriter pw, String dumpPackage) {
10478         pw.println("ACTIVITY MANAGER LRU PROCESSES (dumpsys activity lru)");
10479         final int N = mProcessList.mLruProcesses.size();
10480         int i;
10481         boolean first = true;
10482         for (i = N - 1; i >= mProcessList.mLruProcessActivityStart; i--) {
10483             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
10484             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10485                 continue;
10486             }
10487             if (first) {
10488                 pw.println("  Activities:");
10489                 first = false;
10490             }
10491             dumpLruEntryLocked(pw, i, r);
10492         }
10493         first = true;
10494         for (; i >= mProcessList.mLruProcessServiceStart; i--) {
10495             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
10496             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10497                 continue;
10498             }
10499             if (first) {
10500                 pw.println("  Services:");
10501                 first = false;
10502             }
10503             dumpLruEntryLocked(pw, i, r);
10504         }
10505         first = true;
10506         for (; i >= 0; i--) {
10507             final ProcessRecord r = mProcessList.mLruProcesses.get(i);
10508             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10509                 continue;
10510             }
10511             if (first) {
10512                 pw.println("  Other:");
10513                 first = false;
10514             }
10515             dumpLruEntryLocked(pw, i, r);
10516         }
10517     }
10518 
10519     // TODO: Move to ProcessList?
10520     @GuardedBy("this")
dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage, int dumpAppId)10521     void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
10522             int opti, boolean dumpAll, String dumpPackage, int dumpAppId) {
10523         boolean needSep = false;
10524         int numPers = 0;
10525 
10526         pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
10527 
10528         if (dumpAll) {
10529             final int NP = mProcessList.mProcessNames.getMap().size();
10530             for (int ip=0; ip<NP; ip++) {
10531                 SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip);
10532                 final int NA = procs.size();
10533                 for (int ia=0; ia<NA; ia++) {
10534                     ProcessRecord r = procs.valueAt(ia);
10535                     if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10536                         continue;
10537                     }
10538                     if (!needSep) {
10539                         pw.println("  All known processes:");
10540                         needSep = true;
10541                     }
10542                     pw.print(r.isPersistent() ? "  *PERS*" : "  *APP*");
10543                         pw.print(" UID "); pw.print(procs.keyAt(ia));
10544                         pw.print(" "); pw.println(r);
10545                     r.dump(pw, "    ");
10546                     if (r.isPersistent()) {
10547                         numPers++;
10548                     }
10549                 }
10550             }
10551         }
10552 
10553         if (mProcessList.mIsolatedProcesses.size() > 0) {
10554             boolean printed = false;
10555             for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) {
10556                 ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i);
10557                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10558                     continue;
10559                 }
10560                 if (!printed) {
10561                     if (needSep) {
10562                         pw.println();
10563                     }
10564                     pw.println("  Isolated process list (sorted by uid):");
10565                     printed = true;
10566                     needSep = true;
10567                 }
10568                 pw.print("    Isolated #"); pw.print(i); pw.print(": ");
10569                 pw.println(r);
10570             }
10571         }
10572 
10573         if (mActiveInstrumentation.size() > 0) {
10574             boolean printed = false;
10575             for (int i=0; i<mActiveInstrumentation.size(); i++) {
10576                 ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10577                 if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10578                         && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10579                     continue;
10580                 }
10581                 if (!printed) {
10582                     if (needSep) {
10583                         pw.println();
10584                     }
10585                     pw.println("  Active instrumentation:");
10586                     printed = true;
10587                     needSep = true;
10588                 }
10589                 pw.print("    Instrumentation #"); pw.print(i); pw.print(": ");
10590                 pw.println(ai);
10591                 ai.dump(pw, "      ");
10592             }
10593         }
10594 
10595         if (mProcessList.mActiveUids.size() > 0) {
10596             if (dumpUids(pw, dumpPackage, dumpAppId, mProcessList.mActiveUids,
10597                     "UID states:", needSep)) {
10598                 needSep = true;
10599             }
10600         }
10601 
10602         if (dumpAll) {
10603             if (mValidateUids.size() > 0) {
10604                 if (dumpUids(pw, dumpPackage, dumpAppId, mValidateUids, "UID validation:",
10605                         needSep)) {
10606                     needSep = true;
10607                 }
10608             }
10609         }
10610 
10611         if (mProcessList.getLruSizeLocked() > 0) {
10612             if (needSep) {
10613                 pw.println();
10614             }
10615             mProcessList.dumpLruListHeaderLocked(pw);
10616             dumpProcessOomList(pw, this, mProcessList.mLruProcesses, "    ", "Proc", "PERS", false,
10617                     dumpPackage);
10618             needSep = true;
10619         }
10620 
10621         if (dumpAll || dumpPackage != null) {
10622             synchronized (mPidsSelfLocked) {
10623                 boolean printed = false;
10624                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
10625                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10626                     if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10627                         continue;
10628                     }
10629                     if (!printed) {
10630                         if (needSep) pw.println();
10631                         needSep = true;
10632                         pw.println("  PID mappings:");
10633                         printed = true;
10634                     }
10635                     pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
10636                         pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
10637                 }
10638             }
10639         }
10640 
10641         if (mImportantProcesses.size() > 0) {
10642             synchronized (mPidsSelfLocked) {
10643                 boolean printed = false;
10644                 for (int i = 0; i< mImportantProcesses.size(); i++) {
10645                     ProcessRecord r = mPidsSelfLocked.get(
10646                             mImportantProcesses.valueAt(i).pid);
10647                     if (dumpPackage != null && (r == null
10648                             || !r.pkgList.containsKey(dumpPackage))) {
10649                         continue;
10650                     }
10651                     if (!printed) {
10652                         if (needSep) pw.println();
10653                         needSep = true;
10654                         pw.println("  Foreground Processes:");
10655                         printed = true;
10656                     }
10657                     pw.print("    PID #"); pw.print(mImportantProcesses.keyAt(i));
10658                             pw.print(": "); pw.println(mImportantProcesses.valueAt(i));
10659                 }
10660             }
10661         }
10662 
10663         if (mPersistentStartingProcesses.size() > 0) {
10664             if (needSep) pw.println();
10665             needSep = true;
10666             pw.println("  Persisent processes that are starting:");
10667             dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
10668                     "Starting Norm", "Restarting PERS", dumpPackage);
10669         }
10670 
10671         if (mProcessList.mRemovedProcesses.size() > 0) {
10672             if (needSep) pw.println();
10673             needSep = true;
10674             pw.println("  Processes that are being removed:");
10675             dumpProcessList(pw, this, mProcessList.mRemovedProcesses, "    ",
10676                     "Removed Norm", "Removed PERS", dumpPackage);
10677         }
10678 
10679         if (mProcessesOnHold.size() > 0) {
10680             if (needSep) pw.println();
10681             needSep = true;
10682             pw.println("  Processes that are on old until the system is ready:");
10683             dumpProcessList(pw, this, mProcessesOnHold, "    ",
10684                     "OnHold Norm", "OnHold PERS", dumpPackage);
10685         }
10686 
10687         needSep = dumpProcessesToGc(pw, needSep, dumpPackage);
10688 
10689         needSep = mAppErrors.dumpLocked(fd, pw, needSep, dumpPackage);
10690 
10691         if (dumpPackage == null) {
10692             pw.println();
10693             needSep = false;
10694             mUserController.dump(pw, dumpAll);
10695         }
10696 
10697         needSep = mAtmInternal.dumpForProcesses(fd, pw, dumpAll, dumpPackage, dumpAppId, needSep,
10698                 mTestPssMode, mWakefulness);
10699 
10700         if (dumpAll && mProcessList.mPendingStarts.size() > 0) {
10701             if (needSep) pw.println();
10702             needSep = true;
10703             pw.println("  mPendingStarts: ");
10704             for (int i = 0, len = mProcessList.mPendingStarts.size(); i < len; ++i ) {
10705                 pw.println("    " + mProcessList.mPendingStarts.keyAt(i) + ": "
10706                         + mProcessList.mPendingStarts.valueAt(i));
10707             }
10708         }
10709         if (dumpAll) {
10710             final int NI = mUidObservers.getRegisteredCallbackCount();
10711             boolean printed = false;
10712             for (int i=0; i<NI; i++) {
10713                 final UidObserverRegistration reg = (UidObserverRegistration)
10714                         mUidObservers.getRegisteredCallbackCookie(i);
10715                 if (dumpPackage == null || dumpPackage.equals(reg.pkg)) {
10716                     if (!printed) {
10717                         pw.println("  mUidObservers:");
10718                         printed = true;
10719                     }
10720                     pw.print("    "); UserHandle.formatUid(pw, reg.uid);
10721                     pw.print(" "); pw.print(reg.pkg);
10722                     final IUidObserver observer = mUidObservers.getRegisteredCallbackItem(i);
10723                     pw.print(" "); pw.print(observer.getClass().getTypeName()); pw.print(":");
10724                     if ((reg.which&ActivityManager.UID_OBSERVER_IDLE) != 0) {
10725                         pw.print(" IDLE");
10726                     }
10727                     if ((reg.which&ActivityManager.UID_OBSERVER_ACTIVE) != 0) {
10728                         pw.print(" ACT" );
10729                     }
10730                     if ((reg.which&ActivityManager.UID_OBSERVER_GONE) != 0) {
10731                         pw.print(" GONE");
10732                     }
10733                     if ((reg.which&ActivityManager.UID_OBSERVER_PROCSTATE) != 0) {
10734                         pw.print(" STATE");
10735                         pw.print(" (cut="); pw.print(reg.cutpoint);
10736                         pw.print(")");
10737                     }
10738                     pw.println();
10739                     if (reg.lastProcStates != null) {
10740                         final int NJ = reg.lastProcStates.size();
10741                         for (int j=0; j<NJ; j++) {
10742                             pw.print("      Last ");
10743                             UserHandle.formatUid(pw, reg.lastProcStates.keyAt(j));
10744                             pw.print(": "); pw.println(reg.lastProcStates.valueAt(j));
10745                         }
10746                     }
10747                 }
10748             }
10749             pw.println("  mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
10750             pw.println("  mDeviceIdleExceptIdleWhitelist="
10751                     + Arrays.toString(mDeviceIdleExceptIdleWhitelist));
10752             pw.println("  mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
10753             if (mPendingTempWhitelist.size() > 0) {
10754                 pw.println("  mPendingTempWhitelist:");
10755                 for (int i = 0; i < mPendingTempWhitelist.size(); i++) {
10756                     PendingTempWhitelist ptw = mPendingTempWhitelist.valueAt(i);
10757                     pw.print("    ");
10758                     UserHandle.formatUid(pw, ptw.targetUid);
10759                     pw.print(": ");
10760                     TimeUtils.formatDuration(ptw.duration, pw);
10761                     pw.print(" ");
10762                     pw.println(ptw.tag);
10763                 }
10764             }
10765         }
10766         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
10767                 || mOrigWaitForDebugger) {
10768             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
10769                     || dumpPackage.equals(mOrigDebugApp)) {
10770                 if (needSep) {
10771                     pw.println();
10772                     needSep = false;
10773                 }
10774                 pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
10775                         + " mDebugTransient=" + mDebugTransient
10776                         + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
10777             }
10778         }
10779         if (mMemWatchProcesses.getMap().size() > 0) {
10780             pw.println("  Mem watch processes:");
10781             final ArrayMap<String, SparseArray<Pair<Long, String>>> procs
10782                     = mMemWatchProcesses.getMap();
10783             for (int i=0; i<procs.size(); i++) {
10784                 final String proc = procs.keyAt(i);
10785                 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i);
10786                 for (int j=0; j<uids.size(); j++) {
10787                     if (needSep) {
10788                         pw.println();
10789                         needSep = false;
10790                     }
10791                     StringBuilder sb = new StringBuilder();
10792                     sb.append("    ").append(proc).append('/');
10793                     UserHandle.formatUid(sb, uids.keyAt(j));
10794                     Pair<Long, String> val = uids.valueAt(j);
10795                     sb.append(": "); DebugUtils.sizeValueToString(val.first, sb);
10796                     if (val.second != null) {
10797                         sb.append(", report to ").append(val.second);
10798                     }
10799                     pw.println(sb.toString());
10800                 }
10801             }
10802             pw.print("  mMemWatchDumpProcName="); pw.println(mMemWatchDumpProcName);
10803             pw.print("  mMemWatchDumpFile="); pw.println(mMemWatchDumpFile);
10804             pw.print("  mMemWatchDumpPid="); pw.println(mMemWatchDumpPid);
10805             pw.print("  mMemWatchDumpUid="); pw.println(mMemWatchDumpUid);
10806             pw.print("  mMemWatchIsUserInitiated="); pw.println(mMemWatchIsUserInitiated);
10807         }
10808         if (mTrackAllocationApp != null) {
10809             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
10810                 if (needSep) {
10811                     pw.println();
10812                     needSep = false;
10813                 }
10814                 pw.println("  mTrackAllocationApp=" + mTrackAllocationApp);
10815             }
10816         }
10817         if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null
10818                 || (mProfileData.getProfilerInfo() != null &&
10819                 (mProfileData.getProfilerInfo().profileFile != null
10820                         || mProfileData.getProfilerInfo().profileFd != null))) {
10821             if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) {
10822                 if (needSep) {
10823                     pw.println();
10824                     needSep = false;
10825                 }
10826                 pw.println("  mProfileApp=" + mProfileData.getProfileApp()
10827                         + " mProfileProc=" + mProfileData.getProfileProc());
10828                 if (mProfileData.getProfilerInfo() != null) {
10829                     pw.println("  mProfileFile=" + mProfileData.getProfilerInfo().profileFile
10830                             + " mProfileFd=" + mProfileData.getProfilerInfo().profileFd);
10831                     pw.println("  mSamplingInterval="
10832                             + mProfileData.getProfilerInfo().samplingInterval +
10833                             " mAutoStopProfiler="
10834                             + mProfileData.getProfilerInfo().autoStopProfiler +
10835                             " mStreamingOutput=" + mProfileData.getProfilerInfo().streamingOutput);
10836                     pw.println("  mProfileType=" + mProfileType);
10837                 }
10838             }
10839         }
10840         if (mNativeDebuggingApp != null) {
10841             if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
10842                 if (needSep) {
10843                     pw.println();
10844                     needSep = false;
10845                 }
10846                 pw.println("  mNativeDebuggingApp=" + mNativeDebuggingApp);
10847             }
10848         }
10849         if (dumpPackage == null) {
10850             if (mAlwaysFinishActivities) {
10851                 pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities);
10852             }
10853             if (dumpAll) {
10854                 pw.println("  Total persistent processes: " + numPers);
10855                 pw.println("  mProcessesReady=" + mProcessesReady
10856                         + " mSystemReady=" + mSystemReady
10857                         + " mBooted=" + mBooted
10858                         + " mFactoryTest=" + mFactoryTest);
10859                 pw.println("  mBooting=" + mBooting
10860                         + " mCallFinishBooting=" + mCallFinishBooting
10861                         + " mBootAnimationComplete=" + mBootAnimationComplete);
10862                 pw.print("  mLastPowerCheckUptime=");
10863                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
10864                         pw.println("");
10865                 mOomAdjuster.dumpSequenceNumbersLocked(pw);
10866                 mOomAdjuster.dumpProcCountsLocked(pw);
10867                 pw.println("  mAllowLowerMemLevel=" + mAllowLowerMemLevel
10868                         + " mLastMemoryLevel=" + mLastMemoryLevel
10869                         + " mLastNumProcesses=" + mLastNumProcesses);
10870                 long now = SystemClock.uptimeMillis();
10871                 pw.print("  mLastIdleTime=");
10872                         TimeUtils.formatDuration(now, mLastIdleTime, pw);
10873                         pw.print(" mLowRamSinceLastIdle=");
10874                         TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw);
10875                         pw.println();
10876                 pw.println();
10877                 pw.print("  mUidChangeDispatchCount=");
10878                 pw.print(mUidChangeDispatchCount);
10879                 pw.println();
10880 
10881                 pw.println("  Slow UID dispatches:");
10882                 final int N = mUidObservers.beginBroadcast();
10883                 for (int i = 0; i < N; i++) {
10884                     UidObserverRegistration r =
10885                             (UidObserverRegistration) mUidObservers.getBroadcastCookie(i);
10886                     pw.print("    ");
10887                     pw.print(mUidObservers.getBroadcastItem(i).getClass().getTypeName());
10888                     pw.print(": ");
10889                     pw.print(r.mSlowDispatchCount);
10890                     pw.print(" / Max ");
10891                     pw.print(r.mMaxDispatchTime);
10892                     pw.println("ms");
10893                 }
10894                 mUidObservers.finishBroadcast();
10895 
10896                 pw.println();
10897                 pw.println("  ServiceManager statistics:");
10898                 ServiceManager.sStatLogger.dump(pw, "    ");
10899                 pw.println();
10900             }
10901         }
10902         pw.println("  mForceBackgroundCheck=" + mForceBackgroundCheck);
10903     }
10904 
10905     @GuardedBy("this")
writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage)10906     void writeProcessesToProtoLocked(ProtoOutputStream proto, String dumpPackage) {
10907         int numPers = 0;
10908 
10909         final int NP = mProcessList.mProcessNames.getMap().size();
10910         for (int ip=0; ip<NP; ip++) {
10911             SparseArray<ProcessRecord> procs = mProcessList.mProcessNames.getMap().valueAt(ip);
10912             final int NA = procs.size();
10913             for (int ia = 0; ia<NA; ia++) {
10914                 ProcessRecord r = procs.valueAt(ia);
10915                 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10916                     continue;
10917                 }
10918                 r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.PROCS,
10919                         mProcessList.mLruProcesses.indexOf(r)
10920                 );
10921                 if (r.isPersistent()) {
10922                     numPers++;
10923                 }
10924             }
10925         }
10926 
10927         for (int i=0; i<mProcessList.mIsolatedProcesses.size(); i++) {
10928             ProcessRecord r = mProcessList.mIsolatedProcesses.valueAt(i);
10929             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
10930                 continue;
10931             }
10932             r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ISOLATED_PROCS,
10933                     mProcessList.mLruProcesses.indexOf(r)
10934             );
10935         }
10936 
10937         for (int i=0; i<mActiveInstrumentation.size(); i++) {
10938             ActiveInstrumentation ai = mActiveInstrumentation.get(i);
10939             if (dumpPackage != null && !ai.mClass.getPackageName().equals(dumpPackage)
10940                     && !ai.mTargetInfo.packageName.equals(dumpPackage)) {
10941                 continue;
10942             }
10943             ai.writeToProto(proto,
10944                     ActivityManagerServiceDumpProcessesProto.ACTIVE_INSTRUMENTATIONS);
10945         }
10946 
10947         int whichAppId = getAppId(dumpPackage);
10948         for (int i = 0; i < mProcessList.mActiveUids.size(); i++) {
10949             UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
10950             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) {
10951                 continue;
10952             }
10953             uidRec.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ACTIVE_UIDS);
10954         }
10955 
10956         for (int i = 0; i < mValidateUids.size(); i++) {
10957             UidRecord uidRec = mValidateUids.valueAt(i);
10958             if (dumpPackage != null && UserHandle.getAppId(uidRec.uid) != whichAppId) {
10959                 continue;
10960             }
10961             uidRec.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.VALIDATE_UIDS);
10962         }
10963 
10964         if (mProcessList.getLruSizeLocked() > 0) {
10965             long lruToken = proto.start(ActivityManagerServiceDumpProcessesProto.LRU_PROCS);
10966             int total = mProcessList.getLruSizeLocked();
10967             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.SIZE, total);
10968             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_ACT_AT,
10969                     total - mProcessList.mLruProcessActivityStart);
10970             proto.write(ActivityManagerServiceDumpProcessesProto.LruProcesses.NON_SVC_AT,
10971                     total - mProcessList.mLruProcessServiceStart);
10972             writeProcessOomListToProto(proto,
10973                     ActivityManagerServiceDumpProcessesProto.LruProcesses.LIST, this,
10974                     mProcessList.mLruProcesses,false, dumpPackage);
10975             proto.end(lruToken);
10976         }
10977 
10978         if (dumpPackage != null) {
10979             synchronized (mPidsSelfLocked) {
10980                 for (int i=0; i<mPidsSelfLocked.size(); i++) {
10981                     ProcessRecord r = mPidsSelfLocked.valueAt(i);
10982                     if (!r.pkgList.containsKey(dumpPackage)) {
10983                         continue;
10984                     }
10985                     r.writeToProto(proto,
10986                             ActivityManagerServiceDumpProcessesProto.PIDS_SELF_LOCKED);
10987                 }
10988             }
10989         }
10990 
10991         if (mImportantProcesses.size() > 0) {
10992             synchronized (mPidsSelfLocked) {
10993                 for (int i=0; i<mImportantProcesses.size(); i++) {
10994                     ImportanceToken it = mImportantProcesses.valueAt(i);
10995                     ProcessRecord r = mPidsSelfLocked.get(it.pid);
10996                     if (dumpPackage != null && (r == null
10997                             || !r.pkgList.containsKey(dumpPackage))) {
10998                         continue;
10999                     }
11000                     it.writeToProto(proto,
11001                             ActivityManagerServiceDumpProcessesProto.IMPORTANT_PROCS);
11002                 }
11003             }
11004         }
11005 
11006         for (int i=0; i<mPersistentStartingProcesses.size(); i++) {
11007             ProcessRecord r = mPersistentStartingProcesses.get(i);
11008             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11009                 continue;
11010             }
11011             r.writeToProto(proto,
11012                     ActivityManagerServiceDumpProcessesProto.PERSISTENT_STARTING_PROCS);
11013         }
11014 
11015         for (int i = 0; i < mProcessList.mRemovedProcesses.size(); i++) {
11016             ProcessRecord r = mProcessList.mRemovedProcesses.get(i);
11017             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11018                 continue;
11019             }
11020             r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.REMOVED_PROCS);
11021         }
11022 
11023         for (int i=0; i<mProcessesOnHold.size(); i++) {
11024             ProcessRecord r = mProcessesOnHold.get(i);
11025             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11026                 continue;
11027             }
11028             r.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.ON_HOLD_PROCS);
11029         }
11030 
11031         writeProcessesToGcToProto(proto, ActivityManagerServiceDumpProcessesProto.GC_PROCS,
11032                 dumpPackage);
11033         mAppErrors.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.APP_ERRORS,
11034                 dumpPackage);
11035         mAtmInternal.writeProcessesToProto(proto, dumpPackage, mWakefulness, mTestPssMode);
11036 
11037         if (dumpPackage == null) {
11038             mUserController.writeToProto(proto,
11039             ActivityManagerServiceDumpProcessesProto.USER_CONTROLLER);
11040         }
11041 
11042         final int NI = mUidObservers.getRegisteredCallbackCount();
11043         for (int i=0; i<NI; i++) {
11044             final UidObserverRegistration reg = (UidObserverRegistration)
11045                     mUidObservers.getRegisteredCallbackCookie(i);
11046             if (dumpPackage == null || dumpPackage.equals(reg.pkg)) {
11047                 reg.writeToProto(proto, ActivityManagerServiceDumpProcessesProto.UID_OBSERVERS);
11048             }
11049         }
11050 
11051         for (int v : mDeviceIdleWhitelist) {
11052             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_WHITELIST, v);
11053         }
11054 
11055         for (int v : mDeviceIdleTempWhitelist) {
11056             proto.write(ActivityManagerServiceDumpProcessesProto.DEVICE_IDLE_TEMP_WHITELIST, v);
11057         }
11058 
11059         if (mPendingTempWhitelist.size() > 0) {
11060             for (int i=0; i < mPendingTempWhitelist.size(); i++) {
11061                 mPendingTempWhitelist.valueAt(i).writeToProto(proto,
11062                         ActivityManagerServiceDumpProcessesProto.PENDING_TEMP_WHITELIST);
11063             }
11064         }
11065 
11066         if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
11067                 || mOrigWaitForDebugger) {
11068             if (dumpPackage == null || dumpPackage.equals(mDebugApp)
11069                     || dumpPackage.equals(mOrigDebugApp)) {
11070                 final long debugAppToken = proto.start(ActivityManagerServiceDumpProcessesProto.DEBUG);
11071                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_APP, mDebugApp);
11072                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_DEBUG_APP, mOrigDebugApp);
11073                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.DEBUG_TRANSIENT, mDebugTransient);
11074                 proto.write(ActivityManagerServiceDumpProcessesProto.DebugApp.ORIG_WAIT_FOR_DEBUGGER, mOrigWaitForDebugger);
11075                 proto.end(debugAppToken);
11076             }
11077         }
11078 
11079         if (mMemWatchProcesses.getMap().size() > 0) {
11080             final long token = proto.start(ActivityManagerServiceDumpProcessesProto.MEM_WATCH_PROCESSES);
11081             ArrayMap<String, SparseArray<Pair<Long, String>>> procs = mMemWatchProcesses.getMap();
11082             for (int i=0; i<procs.size(); i++) {
11083                 final String proc = procs.keyAt(i);
11084                 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i);
11085                 final long ptoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.PROCS);
11086                 proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.NAME, proc);
11087                 for (int j=0; j<uids.size(); j++) {
11088                     final long utoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MEM_STATS);
11089                     Pair<Long, String> val = uids.valueAt(j);
11090                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.UID, uids.keyAt(j));
11091                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.SIZE,
11092                             DebugUtils.sizeValueToString(val.first, new StringBuilder()));
11093                     proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Process.MemStats.REPORT_TO, val.second);
11094                     proto.end(utoken);
11095                 }
11096                 proto.end(ptoken);
11097             }
11098 
11099             final long dtoken = proto.start(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.DUMP);
11100             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PROC_NAME, mMemWatchDumpProcName);
11101             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.FILE, mMemWatchDumpFile);
11102             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.PID, mMemWatchDumpPid);
11103             proto.write(ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.UID, mMemWatchDumpUid);
11104             proto.write(
11105                     ActivityManagerServiceDumpProcessesProto.MemWatchProcess.Dump.IS_USER_INITIATED,
11106                     mMemWatchIsUserInitiated);
11107             proto.end(dtoken);
11108 
11109             proto.end(token);
11110         }
11111 
11112         if (mTrackAllocationApp != null) {
11113             if (dumpPackage == null || dumpPackage.equals(mTrackAllocationApp)) {
11114                 proto.write(ActivityManagerServiceDumpProcessesProto.TRACK_ALLOCATION_APP,
11115                         mTrackAllocationApp);
11116             }
11117         }
11118 
11119         if (mProfileData.getProfileApp() != null || mProfileData.getProfileProc() != null
11120                 || (mProfileData.getProfilerInfo() != null &&
11121                 (mProfileData.getProfilerInfo().profileFile != null
11122                         || mProfileData.getProfilerInfo().profileFd != null))) {
11123             if (dumpPackage == null || dumpPackage.equals(mProfileData.getProfileApp())) {
11124                 final long token = proto.start(ActivityManagerServiceDumpProcessesProto.PROFILE);
11125                 proto.write(ActivityManagerServiceDumpProcessesProto.Profile.APP_NAME,
11126                         mProfileData.getProfileApp());
11127                 mProfileData.getProfileProc().writeToProto(proto,
11128                         ActivityManagerServiceDumpProcessesProto.Profile.PROC);
11129                 if (mProfileData.getProfilerInfo() != null) {
11130                     mProfileData.getProfilerInfo().writeToProto(proto,
11131                             ActivityManagerServiceDumpProcessesProto.Profile.INFO);
11132                     proto.write(ActivityManagerServiceDumpProcessesProto.Profile.TYPE,
11133                             mProfileType);
11134                 }
11135                 proto.end(token);
11136             }
11137         }
11138 
11139         if (dumpPackage == null || dumpPackage.equals(mNativeDebuggingApp)) {
11140             proto.write(ActivityManagerServiceDumpProcessesProto.NATIVE_DEBUGGING_APP, mNativeDebuggingApp);
11141         }
11142 
11143         if (dumpPackage == null) {
11144             proto.write(ActivityManagerServiceDumpProcessesProto.ALWAYS_FINISH_ACTIVITIES, mAlwaysFinishActivities);
11145             proto.write(ActivityManagerServiceDumpProcessesProto.TOTAL_PERSISTENT_PROCS, numPers);
11146             proto.write(ActivityManagerServiceDumpProcessesProto.PROCESSES_READY, mProcessesReady);
11147             proto.write(ActivityManagerServiceDumpProcessesProto.SYSTEM_READY, mSystemReady);
11148             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTED, mBooted);
11149             proto.write(ActivityManagerServiceDumpProcessesProto.FACTORY_TEST, mFactoryTest);
11150             proto.write(ActivityManagerServiceDumpProcessesProto.BOOTING, mBooting);
11151             proto.write(ActivityManagerServiceDumpProcessesProto.CALL_FINISH_BOOTING, mCallFinishBooting);
11152             proto.write(ActivityManagerServiceDumpProcessesProto.BOOT_ANIMATION_COMPLETE, mBootAnimationComplete);
11153             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_POWER_CHECK_UPTIME_MS, mLastPowerCheckUptime);
11154             mOomAdjuster.dumpProcessListVariablesLocked(proto);
11155             proto.write(ActivityManagerServiceDumpProcessesProto.ALLOW_LOWER_MEM_LEVEL, mAllowLowerMemLevel);
11156             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_MEMORY_LEVEL, mLastMemoryLevel);
11157             proto.write(ActivityManagerServiceDumpProcessesProto.LAST_NUM_PROCESSES, mLastNumProcesses);
11158             long now = SystemClock.uptimeMillis();
11159             ProtoUtils.toDuration(proto, ActivityManagerServiceDumpProcessesProto.LAST_IDLE_TIME, mLastIdleTime, now);
11160             proto.write(ActivityManagerServiceDumpProcessesProto.LOW_RAM_SINCE_LAST_IDLE_MS, getLowRamTimeSinceIdle(now));
11161         }
11162     }
11163 
writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage)11164     void writeProcessesToGcToProto(ProtoOutputStream proto, long fieldId, String dumpPackage) {
11165         if (mProcessesToGc.size() > 0) {
11166             long now = SystemClock.uptimeMillis();
11167             for (int i=0; i<mProcessesToGc.size(); i++) {
11168                 ProcessRecord r = mProcessesToGc.get(i);
11169                 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11170                     continue;
11171                 }
11172                 final long token = proto.start(fieldId);
11173                 r.writeToProto(proto, ProcessToGcProto.PROC);
11174                 proto.write(ProcessToGcProto.REPORT_LOW_MEMORY, r.reportLowMemory);
11175                 proto.write(ProcessToGcProto.NOW_UPTIME_MS, now);
11176                 proto.write(ProcessToGcProto.LAST_GCED_MS, r.lastRequestedGc);
11177                 proto.write(ProcessToGcProto.LAST_LOW_MEMORY_MS, r.lastLowMemory);
11178                 proto.end(token);
11179             }
11180         }
11181     }
11182 
dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage)11183     boolean dumpProcessesToGc(PrintWriter pw, boolean needSep, String dumpPackage) {
11184         if (mProcessesToGc.size() > 0) {
11185             boolean printed = false;
11186             long now = SystemClock.uptimeMillis();
11187             for (int i=0; i<mProcessesToGc.size(); i++) {
11188                 ProcessRecord proc = mProcessesToGc.get(i);
11189                 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
11190                     continue;
11191                 }
11192                 if (!printed) {
11193                     if (needSep) pw.println();
11194                     needSep = true;
11195                     pw.println("  Processes that are waiting to GC:");
11196                     printed = true;
11197                 }
11198                 pw.print("    Process "); pw.println(proc);
11199                 pw.print("      lowMem="); pw.print(proc.reportLowMemory);
11200                         pw.print(", last gced=");
11201                         pw.print(now-proc.lastRequestedGc);
11202                         pw.print(" ms ago, last lowMem=");
11203                         pw.print(now-proc.lastLowMemory);
11204                         pw.println(" ms ago");
11205 
11206             }
11207         }
11208         return needSep;
11209     }
11210 
printOomLevel(PrintWriter pw, String name, int adj)11211     void printOomLevel(PrintWriter pw, String name, int adj) {
11212         pw.print("    ");
11213         if (adj >= 0) {
11214             pw.print(' ');
11215             if (adj < 10) pw.print(' ');
11216         } else {
11217             if (adj > -10) pw.print(' ');
11218         }
11219         pw.print(adj);
11220         pw.print(": ");
11221         pw.print(name);
11222         pw.print(" (");
11223         pw.print(stringifySize(mProcessList.getMemLevel(adj), 1024));
11224         pw.println(")");
11225     }
11226 
dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll)11227     boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11228             int opti, boolean dumpAll) {
11229         boolean needSep = false;
11230 
11231         if (mProcessList.getLruSizeLocked() > 0) {
11232             if (needSep) pw.println();
11233             needSep = true;
11234             pw.println("  OOM levels:");
11235             printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ);
11236             printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ);
11237             printOomLevel(pw, "PERSISTENT_SERVICE_ADJ", ProcessList.PERSISTENT_SERVICE_ADJ);
11238             printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ);
11239             printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ);
11240             printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ);
11241             printOomLevel(pw, "PERCEPTIBLE_LOW_APP_ADJ", ProcessList.PERCEPTIBLE_LOW_APP_ADJ);
11242             printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ);
11243             printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ);
11244             printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ);
11245             printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ);
11246             printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ);
11247             printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ);
11248             printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ);
11249             printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ);
11250 
11251             if (needSep) pw.println();
11252             pw.print("  Process OOM control ("); pw.print(mProcessList.getLruSizeLocked());
11253                     pw.print(" total, non-act at ");
11254                     pw.print(mProcessList.getLruSizeLocked()
11255                             - mProcessList.mLruProcessActivityStart);
11256                     pw.print(", non-svc at ");
11257                     pw.print(mProcessList.getLruSizeLocked()
11258                             - mProcessList.mLruProcessServiceStart);
11259                     pw.println("):");
11260             dumpProcessOomList(pw, this, mProcessList.mLruProcesses, "    ", "Proc", "PERS", true,
11261                     null);
11262             needSep = true;
11263         }
11264 
11265         dumpProcessesToGc(pw, needSep, null);
11266 
11267         pw.println();
11268         mAtmInternal.dumpForOom(pw);
11269 
11270         return true;
11271     }
11272 
reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj)11273     private boolean reportLmkKillAtOrBelow(PrintWriter pw, int oom_adj) {
11274         Integer cnt = ProcessList.getLmkdKillCount(0, oom_adj);
11275         if (cnt != null) {
11276             pw.println("    kills at or below oom_adj " + oom_adj + ": " + cnt);
11277             return true;
11278         }
11279         return false;
11280     }
11281 
dumpLmkLocked(PrintWriter pw)11282     boolean dumpLmkLocked(PrintWriter pw) {
11283         pw.println("ACTIVITY MANAGER LMK KILLS (dumpsys activity lmk)");
11284         Integer cnt = ProcessList.getLmkdKillCount(ProcessList.UNKNOWN_ADJ,
11285                 ProcessList.UNKNOWN_ADJ);
11286         if (cnt == null) {
11287             return false;
11288         }
11289         pw.println("  Total number of kills: " + cnt);
11290 
11291         return reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MAX_ADJ) &&
11292                 reportLmkKillAtOrBelow(pw, ProcessList.CACHED_APP_MIN_ADJ) &&
11293                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_B_ADJ) &&
11294                 reportLmkKillAtOrBelow(pw, ProcessList.PREVIOUS_APP_ADJ) &&
11295                 reportLmkKillAtOrBelow(pw, ProcessList.HOME_APP_ADJ) &&
11296                 reportLmkKillAtOrBelow(pw, ProcessList.SERVICE_ADJ) &&
11297                 reportLmkKillAtOrBelow(pw, ProcessList.HEAVY_WEIGHT_APP_ADJ) &&
11298                 reportLmkKillAtOrBelow(pw, ProcessList.BACKUP_APP_ADJ) &&
11299                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_LOW_APP_ADJ) &&
11300                 reportLmkKillAtOrBelow(pw, ProcessList.PERCEPTIBLE_APP_ADJ) &&
11301                 reportLmkKillAtOrBelow(pw, ProcessList.VISIBLE_APP_ADJ) &&
11302                 reportLmkKillAtOrBelow(pw, ProcessList.FOREGROUND_APP_ADJ);
11303     }
11304 
11305     /**
11306      * There are three ways to call this:
11307      *  - no provider specified: dump all the providers
11308      *  - a flattened component name that matched an existing provider was specified as the
11309      *    first arg: dump that one provider
11310      *  - the first arg isn't the flattened component name of an existing provider:
11311      *    dump all providers whose component contains the first arg as a substring
11312      */
dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)11313     protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
11314             int opti, boolean dumpAll) {
11315         return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
11316     }
11317 
11318     /**
11319      * Similar to the dumpProvider, but only dumps the first matching provider.
11320      * The provider is responsible for dumping as proto.
11321      */
dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name, String[] args)11322     protected boolean dumpProviderProto(FileDescriptor fd, PrintWriter pw, String name,
11323             String[] args) {
11324         return mProviderMap.dumpProviderProto(fd, pw, name, args);
11325     }
11326 
11327     public static class ItemMatcher {
11328         ArrayList<ComponentName> components;
11329         ArrayList<String> strings;
11330         ArrayList<Integer> objects;
11331         boolean all;
11332 
ItemMatcher()11333         public ItemMatcher() {
11334             all = true;
11335         }
11336 
build(String name)11337         public void build(String name) {
11338             ComponentName componentName = ComponentName.unflattenFromString(name);
11339             if (componentName != null) {
11340                 if (components == null) {
11341                     components = new ArrayList<ComponentName>();
11342                 }
11343                 components.add(componentName);
11344                 all = false;
11345             } else {
11346                 int objectId = 0;
11347                 // Not a '/' separated full component name; maybe an object ID?
11348                 try {
11349                     objectId = Integer.parseInt(name, 16);
11350                     if (objects == null) {
11351                         objects = new ArrayList<Integer>();
11352                     }
11353                     objects.add(objectId);
11354                     all = false;
11355                 } catch (RuntimeException e) {
11356                     // Not an integer; just do string match.
11357                     if (strings == null) {
11358                         strings = new ArrayList<String>();
11359                     }
11360                     strings.add(name);
11361                     all = false;
11362                 }
11363             }
11364         }
11365 
build(String[] args, int opti)11366         public int build(String[] args, int opti) {
11367             for (; opti<args.length; opti++) {
11368                 String name = args[opti];
11369                 if ("--".equals(name)) {
11370                     return opti+1;
11371                 }
11372                 build(name);
11373             }
11374             return opti;
11375         }
11376 
match(Object object, ComponentName comp)11377         public boolean match(Object object, ComponentName comp) {
11378             if (all) {
11379                 return true;
11380             }
11381             if (components != null) {
11382                 for (int i=0; i<components.size(); i++) {
11383                     if (components.get(i).equals(comp)) {
11384                         return true;
11385                     }
11386                 }
11387             }
11388             if (objects != null) {
11389                 for (int i=0; i<objects.size(); i++) {
11390                     if (System.identityHashCode(object) == objects.get(i)) {
11391                         return true;
11392                     }
11393                 }
11394             }
11395             if (strings != null) {
11396                 String flat = comp.flattenToString();
11397                 for (int i=0; i<strings.size(); i++) {
11398                     if (flat.contains(strings.get(i))) {
11399                         return true;
11400                     }
11401                 }
11402             }
11403             return false;
11404         }
11405     }
11406 
writeBroadcastsToProtoLocked(ProtoOutputStream proto)11407     void writeBroadcastsToProtoLocked(ProtoOutputStream proto) {
11408         if (mRegisteredReceivers.size() > 0) {
11409             Iterator it = mRegisteredReceivers.values().iterator();
11410             while (it.hasNext()) {
11411                 ReceiverList r = (ReceiverList)it.next();
11412                 r.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_LIST);
11413             }
11414         }
11415         mReceiverResolver.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.RECEIVER_RESOLVER);
11416         for (BroadcastQueue q : mBroadcastQueues) {
11417             q.writeToProto(proto, ActivityManagerServiceDumpBroadcastsProto.BROADCAST_QUEUE);
11418         }
11419         for (int user=0; user<mStickyBroadcasts.size(); user++) {
11420             long token = proto.start(ActivityManagerServiceDumpBroadcastsProto.STICKY_BROADCASTS);
11421             proto.write(StickyBroadcastProto.USER, mStickyBroadcasts.keyAt(user));
11422             for (Map.Entry<String, ArrayList<Intent>> ent
11423                     : mStickyBroadcasts.valueAt(user).entrySet()) {
11424                 long actionToken = proto.start(StickyBroadcastProto.ACTIONS);
11425                 proto.write(StickyBroadcastProto.StickyAction.NAME, ent.getKey());
11426                 for (Intent intent : ent.getValue()) {
11427                     intent.writeToProto(proto, StickyBroadcastProto.StickyAction.INTENTS,
11428                             false, true, true, false);
11429                 }
11430                 proto.end(actionToken);
11431             }
11432             proto.end(token);
11433         }
11434 
11435         long handlerToken = proto.start(ActivityManagerServiceDumpBroadcastsProto.HANDLER);
11436         proto.write(ActivityManagerServiceDumpBroadcastsProto.MainHandler.HANDLER, mHandler.toString());
11437         mHandler.getLooper().writeToProto(proto,
11438             ActivityManagerServiceDumpBroadcastsProto.MainHandler.LOOPER);
11439         proto.end(handlerToken);
11440     }
11441 
dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11442     void dumpAllowedAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11443             int opti, boolean dumpAll, String dumpPackage) {
11444         boolean needSep = false;
11445 
11446         pw.println("ACTIVITY MANAGER ALLOWED ASSOCIATION STATE (dumpsys activity allowed-associations)");
11447         boolean printed = false;
11448         if (mAllowedAssociations != null) {
11449             for (int i = 0; i < mAllowedAssociations.size(); i++) {
11450                 final String pkg = mAllowedAssociations.keyAt(i);
11451                 final ArraySet<String> asc =
11452                         mAllowedAssociations.valueAt(i).getAllowedPackageAssociations();
11453                 boolean printedHeader = false;
11454                 for (int j = 0; j < asc.size(); j++) {
11455                     if (dumpPackage == null || pkg.equals(dumpPackage)
11456                             || asc.valueAt(j).equals(dumpPackage)) {
11457                         if (!printed) {
11458                             pw.println("  Allowed associations (by restricted package):");
11459                             printed = true;
11460                             needSep = true;
11461                         }
11462                         if (!printedHeader) {
11463                             pw.print("  * ");
11464                             pw.print(pkg);
11465                             pw.println(":");
11466                             printedHeader = true;
11467                         }
11468                         pw.print("      Allow: ");
11469                         pw.println(asc.valueAt(j));
11470                     }
11471                 }
11472                 if (mAllowedAssociations.valueAt(i).isDebuggable()) {
11473                     pw.println("      (debuggable)");
11474                 }
11475             }
11476         }
11477         if (!printed) {
11478             pw.println("  (No association restrictions)");
11479         }
11480     }
11481 
dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11482     void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11483             int opti, boolean dumpAll, String dumpPackage) {
11484         boolean needSep = false;
11485         boolean onlyHistory = false;
11486         boolean printedAnything = false;
11487 
11488         if ("history".equals(dumpPackage)) {
11489             if (opti < args.length && "-s".equals(args[opti])) {
11490                 dumpAll = false;
11491             }
11492             onlyHistory = true;
11493             dumpPackage = null;
11494         }
11495 
11496         pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
11497         if (!onlyHistory && dumpAll) {
11498             if (mRegisteredReceivers.size() > 0) {
11499                 boolean printed = false;
11500                 Iterator it = mRegisteredReceivers.values().iterator();
11501                 while (it.hasNext()) {
11502                     ReceiverList r = (ReceiverList)it.next();
11503                     if (dumpPackage != null && (r.app == null ||
11504                             !dumpPackage.equals(r.app.info.packageName))) {
11505                         continue;
11506                     }
11507                     if (!printed) {
11508                         pw.println("  Registered Receivers:");
11509                         needSep = true;
11510                         printed = true;
11511                         printedAnything = true;
11512                     }
11513                     pw.print("  * "); pw.println(r);
11514                     r.dump(pw, "    ");
11515                 }
11516             }
11517 
11518             if (mReceiverResolver.dump(pw, needSep ?
11519                     "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
11520                     "    ", dumpPackage, false, false)) {
11521                 needSep = true;
11522                 printedAnything = true;
11523             }
11524         }
11525 
11526         for (BroadcastQueue q : mBroadcastQueues) {
11527             needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
11528             printedAnything |= needSep;
11529         }
11530 
11531         needSep = true;
11532 
11533         if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
11534             for (int user=0; user<mStickyBroadcasts.size(); user++) {
11535                 if (needSep) {
11536                     pw.println();
11537                 }
11538                 needSep = true;
11539                 printedAnything = true;
11540                 pw.print("  Sticky broadcasts for user ");
11541                         pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
11542                 StringBuilder sb = new StringBuilder(128);
11543                 for (Map.Entry<String, ArrayList<Intent>> ent
11544                         : mStickyBroadcasts.valueAt(user).entrySet()) {
11545                     pw.print("  * Sticky action "); pw.print(ent.getKey());
11546                     if (dumpAll) {
11547                         pw.println(":");
11548                         ArrayList<Intent> intents = ent.getValue();
11549                         final int N = intents.size();
11550                         for (int i=0; i<N; i++) {
11551                             sb.setLength(0);
11552                             sb.append("    Intent: ");
11553                             intents.get(i).toShortString(sb, false, true, false, false);
11554                             pw.println(sb.toString());
11555                             Bundle bundle = intents.get(i).getExtras();
11556                             if (bundle != null) {
11557                                 pw.print("      ");
11558                                 pw.println(bundle.toString());
11559                             }
11560                         }
11561                     } else {
11562                         pw.println("");
11563                     }
11564                 }
11565             }
11566         }
11567 
11568         if (!onlyHistory && dumpAll) {
11569             pw.println();
11570             for (BroadcastQueue queue : mBroadcastQueues) {
11571                 pw.println("  mBroadcastsScheduled [" + queue.mQueueName + "]="
11572                         + queue.mBroadcastsScheduled);
11573             }
11574             pw.println("  mHandler:");
11575             mHandler.dump(new PrintWriterPrinter(pw), "    ");
11576             needSep = true;
11577             printedAnything = true;
11578         }
11579 
11580         if (!printedAnything) {
11581             pw.println("  (nothing)");
11582         }
11583     }
11584 
dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11585     void dumpBroadcastStatsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11586             int opti, boolean dumpAll, String dumpPackage) {
11587         if (mCurBroadcastStats == null) {
11588             return;
11589         }
11590 
11591         pw.println("ACTIVITY MANAGER BROADCAST STATS STATE (dumpsys activity broadcast-stats)");
11592         final long now = SystemClock.elapsedRealtime();
11593         if (mLastBroadcastStats != null) {
11594             pw.print("  Last stats (from ");
11595             TimeUtils.formatDuration(mLastBroadcastStats.mStartRealtime, now, pw);
11596             pw.print(" to ");
11597             TimeUtils.formatDuration(mLastBroadcastStats.mEndRealtime, now, pw);
11598             pw.print(", ");
11599             TimeUtils.formatDuration(mLastBroadcastStats.mEndUptime
11600                     - mLastBroadcastStats.mStartUptime, pw);
11601             pw.println(" uptime):");
11602             if (!mLastBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11603                 pw.println("    (nothing)");
11604             }
11605             pw.println();
11606         }
11607         pw.print("  Current stats (from ");
11608         TimeUtils.formatDuration(mCurBroadcastStats.mStartRealtime, now, pw);
11609         pw.print(" to now, ");
11610         TimeUtils.formatDuration(SystemClock.uptimeMillis()
11611                 - mCurBroadcastStats.mStartUptime, pw);
11612         pw.println(" uptime):");
11613         if (!mCurBroadcastStats.dumpStats(pw, "    ", dumpPackage)) {
11614             pw.println("    (nothing)");
11615         }
11616     }
11617 
dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean fullCheckin, String dumpPackage)11618     void dumpBroadcastStatsCheckinLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11619             int opti, boolean fullCheckin, String dumpPackage) {
11620         if (mCurBroadcastStats == null) {
11621             return;
11622         }
11623 
11624         if (mLastBroadcastStats != null) {
11625             mLastBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11626             if (fullCheckin) {
11627                 mLastBroadcastStats = null;
11628                 return;
11629             }
11630         }
11631         mCurBroadcastStats.dumpCheckinStats(pw, dumpPackage);
11632         if (fullCheckin) {
11633             mCurBroadcastStats = null;
11634         }
11635     }
11636 
dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11637     void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11638             int opti, boolean dumpAll, String dumpPackage) {
11639         boolean needSep;
11640         boolean printedAnything = false;
11641 
11642         ItemMatcher matcher = new ItemMatcher();
11643         matcher.build(args, opti);
11644 
11645         pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
11646 
11647         needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage);
11648         printedAnything |= needSep;
11649 
11650         if (mLaunchingProviders.size() > 0) {
11651             boolean printed = false;
11652             for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
11653                 ContentProviderRecord r = mLaunchingProviders.get(i);
11654                 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
11655                     continue;
11656                 }
11657                 if (!printed) {
11658                     if (needSep) pw.println();
11659                     needSep = true;
11660                     pw.println("  Launching content providers:");
11661                     printed = true;
11662                     printedAnything = true;
11663                 }
11664                 pw.print("  Launching #"); pw.print(i); pw.print(": ");
11665                         pw.println(r);
11666             }
11667         }
11668 
11669         if (!printedAnything) {
11670             pw.println("  (nothing)");
11671         }
11672     }
11673 
11674     @GuardedBy("this")
dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)11675     void dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11676             int opti, boolean dumpAll, String dumpPackage) {
11677 
11678         pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)");
11679 
11680         mUgmInternal.dump(pw, dumpAll, dumpPackage);
11681     }
11682 
dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)11683     private static final int dumpProcessList(PrintWriter pw,
11684             ActivityManagerService service, List list,
11685             String prefix, String normalLabel, String persistentLabel,
11686             String dumpPackage) {
11687         int numPers = 0;
11688         final int N = list.size()-1;
11689         for (int i=N; i>=0; i--) {
11690             ProcessRecord r = (ProcessRecord)list.get(i);
11691             if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
11692                 continue;
11693             }
11694             pw.println(String.format("%s%s #%2d: %s",
11695                     prefix, (r.isPersistent() ? persistentLabel : normalLabel),
11696                     i, r.toString()));
11697             if (r.isPersistent()) {
11698                 numPers++;
11699             }
11700         }
11701         return numPers;
11702     }
11703 
11704     private static final ArrayList<Pair<ProcessRecord, Integer>>
sortProcessOomList(List<ProcessRecord> origList, String dumpPackage)11705         sortProcessOomList(List<ProcessRecord> origList, String dumpPackage) {
11706         ArrayList<Pair<ProcessRecord, Integer>> list
11707                 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
11708         for (int i=0; i<origList.size(); i++) {
11709             ProcessRecord r = origList.get(i);
11710             if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11711                 continue;
11712             }
11713             list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
11714         }
11715 
11716         Comparator<Pair<ProcessRecord, Integer>> comparator
11717                 = new Comparator<Pair<ProcessRecord, Integer>>() {
11718             @Override
11719             public int compare(Pair<ProcessRecord, Integer> object1,
11720                     Pair<ProcessRecord, Integer> object2) {
11721                 if (object1.first.setAdj != object2.first.setAdj) {
11722                     return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
11723                 }
11724                 if (object1.first.setProcState != object2.first.setProcState) {
11725                     return object1.first.setProcState > object2.first.setProcState ? -1 : 1;
11726                 }
11727                 if (object1.second.intValue() != object2.second.intValue()) {
11728                     return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
11729                 }
11730                 return 0;
11731             }
11732         };
11733 
11734         Collections.sort(list, comparator);
11735         return list;
11736     }
11737 
writeProcessOomListToProto(ProtoOutputStream proto, long fieldId, ActivityManagerService service, List<ProcessRecord> origList, boolean inclDetails, String dumpPackage)11738     private static final boolean writeProcessOomListToProto(ProtoOutputStream proto, long fieldId,
11739             ActivityManagerService service, List<ProcessRecord> origList,
11740             boolean inclDetails, String dumpPackage) {
11741         ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage);
11742         if (list.isEmpty()) return false;
11743 
11744         final long curUptime = SystemClock.uptimeMillis();
11745 
11746         for (int i = list.size() - 1; i >= 0; i--) {
11747             ProcessRecord r = list.get(i).first;
11748             long token = proto.start(fieldId);
11749             String oomAdj = ProcessList.makeOomAdjString(r.setAdj, true);
11750             proto.write(ProcessOomProto.PERSISTENT, r.isPersistent());
11751             proto.write(ProcessOomProto.NUM, (origList.size()-1)-list.get(i).second);
11752             proto.write(ProcessOomProto.OOM_ADJ, oomAdj);
11753             int schedGroup = ProcessOomProto.SCHED_GROUP_UNKNOWN;
11754             switch (r.setSchedGroup) {
11755                 case ProcessList.SCHED_GROUP_BACKGROUND:
11756                     schedGroup = ProcessOomProto.SCHED_GROUP_BACKGROUND;
11757                     break;
11758                 case ProcessList.SCHED_GROUP_DEFAULT:
11759                     schedGroup = ProcessOomProto.SCHED_GROUP_DEFAULT;
11760                     break;
11761                 case ProcessList.SCHED_GROUP_TOP_APP:
11762                     schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP;
11763                     break;
11764                 case ProcessList.SCHED_GROUP_TOP_APP_BOUND:
11765                     schedGroup = ProcessOomProto.SCHED_GROUP_TOP_APP_BOUND;
11766                     break;
11767             }
11768             if (schedGroup != ProcessOomProto.SCHED_GROUP_UNKNOWN) {
11769                 proto.write(ProcessOomProto.SCHED_GROUP, schedGroup);
11770             }
11771             if (r.hasForegroundActivities()) {
11772                 proto.write(ProcessOomProto.ACTIVITIES, true);
11773             } else if (r.hasForegroundServices()) {
11774                 proto.write(ProcessOomProto.SERVICES, true);
11775             }
11776             proto.write(ProcessOomProto.STATE,
11777                     ProcessList.makeProcStateProtoEnum(r.getCurProcState()));
11778             proto.write(ProcessOomProto.TRIM_MEMORY_LEVEL, r.trimMemoryLevel);
11779             r.writeToProto(proto, ProcessOomProto.PROC);
11780             proto.write(ProcessOomProto.ADJ_TYPE, r.adjType);
11781             if (r.adjSource != null || r.adjTarget != null) {
11782                 if (r.adjTarget instanceof  ComponentName) {
11783                     ComponentName cn = (ComponentName) r.adjTarget;
11784                     cn.writeToProto(proto, ProcessOomProto.ADJ_TARGET_COMPONENT_NAME);
11785                 } else if (r.adjTarget != null) {
11786                     proto.write(ProcessOomProto.ADJ_TARGET_OBJECT, r.adjTarget.toString());
11787                 }
11788                 if (r.adjSource instanceof ProcessRecord) {
11789                     ProcessRecord p = (ProcessRecord) r.adjSource;
11790                     p.writeToProto(proto, ProcessOomProto.ADJ_SOURCE_PROC);
11791                 } else if (r.adjSource != null) {
11792                     proto.write(ProcessOomProto.ADJ_SOURCE_OBJECT, r.adjSource.toString());
11793                 }
11794             }
11795             if (inclDetails) {
11796                 long detailToken = proto.start(ProcessOomProto.DETAIL);
11797                 proto.write(ProcessOomProto.Detail.MAX_ADJ, r.maxAdj);
11798                 proto.write(ProcessOomProto.Detail.CUR_RAW_ADJ, r.getCurRawAdj());
11799                 proto.write(ProcessOomProto.Detail.SET_RAW_ADJ, r.setRawAdj);
11800                 proto.write(ProcessOomProto.Detail.CUR_ADJ, r.curAdj);
11801                 proto.write(ProcessOomProto.Detail.SET_ADJ, r.setAdj);
11802                 proto.write(ProcessOomProto.Detail.CURRENT_STATE,
11803                         ProcessList.makeProcStateProtoEnum(r.getCurProcState()));
11804                 proto.write(ProcessOomProto.Detail.SET_STATE,
11805                         ProcessList.makeProcStateProtoEnum(r.setProcState));
11806                 proto.write(ProcessOomProto.Detail.LAST_PSS, DebugUtils.sizeValueToString(
11807                         r.lastPss*1024, new StringBuilder()));
11808                 proto.write(ProcessOomProto.Detail.LAST_SWAP_PSS, DebugUtils.sizeValueToString(
11809                         r.lastSwapPss*1024, new StringBuilder()));
11810                 proto.write(ProcessOomProto.Detail.LAST_CACHED_PSS, DebugUtils.sizeValueToString(
11811                         r.lastCachedPss*1024, new StringBuilder()));
11812                 proto.write(ProcessOomProto.Detail.CACHED, r.cached);
11813                 proto.write(ProcessOomProto.Detail.EMPTY, r.empty);
11814                 proto.write(ProcessOomProto.Detail.HAS_ABOVE_CLIENT, r.hasAboveClient);
11815 
11816                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
11817                     if (r.lastCpuTime != 0) {
11818                         long uptimeSince = curUptime - service.mLastPowerCheckUptime;
11819                         long timeUsed = r.curCpuTime - r.lastCpuTime;
11820                         long cpuTimeToken = proto.start(ProcessOomProto.Detail.SERVICE_RUN_TIME);
11821                         proto.write(ProcessOomProto.Detail.CpuRunTime.OVER_MS, uptimeSince);
11822                         proto.write(ProcessOomProto.Detail.CpuRunTime.USED_MS, timeUsed);
11823                         proto.write(ProcessOomProto.Detail.CpuRunTime.ULTILIZATION,
11824                                 (100.0*timeUsed)/uptimeSince);
11825                         proto.end(cpuTimeToken);
11826                     }
11827                 }
11828                 proto.end(detailToken);
11829             }
11830             proto.end(token);
11831         }
11832 
11833         return true;
11834     }
11835 
dumpProcessOomList(PrintWriter pw, ActivityManagerService service, List<ProcessRecord> origList, String prefix, String normalLabel, String persistentLabel, boolean inclDetails, String dumpPackage)11836     private static final boolean dumpProcessOomList(PrintWriter pw,
11837             ActivityManagerService service, List<ProcessRecord> origList,
11838             String prefix, String normalLabel, String persistentLabel,
11839             boolean inclDetails, String dumpPackage) {
11840 
11841         ArrayList<Pair<ProcessRecord, Integer>> list = sortProcessOomList(origList, dumpPackage);
11842         if (list.isEmpty()) return false;
11843 
11844         final long curUptime = SystemClock.uptimeMillis();
11845         final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
11846 
11847         for (int i=list.size()-1; i>=0; i--) {
11848             ProcessRecord r = list.get(i).first;
11849             String oomAdj = ProcessList.makeOomAdjString(r.setAdj, false);
11850             char schedGroup;
11851             switch (r.setSchedGroup) {
11852                 case ProcessList.SCHED_GROUP_BACKGROUND:
11853                     schedGroup = 'B';
11854                     break;
11855                 case ProcessList.SCHED_GROUP_DEFAULT:
11856                     schedGroup = 'F';
11857                     break;
11858                 case ProcessList.SCHED_GROUP_TOP_APP:
11859                     schedGroup = 'T';
11860                     break;
11861                 case ProcessList.SCHED_GROUP_RESTRICTED:
11862                     schedGroup = 'R';
11863                     break;
11864                 default:
11865                     schedGroup = '?';
11866                     break;
11867             }
11868             char foreground;
11869             if (r.hasForegroundActivities()) {
11870                 foreground = 'A';
11871             } else if (r.hasForegroundServices()) {
11872                 foreground = 'S';
11873             } else {
11874                 foreground = ' ';
11875             }
11876             String procState = ProcessList.makeProcStateString(r.getCurProcState());
11877             pw.print(prefix);
11878             pw.print(r.isPersistent() ? persistentLabel : normalLabel);
11879             pw.print(" #");
11880             int num = (origList.size()-1)-list.get(i).second;
11881             if (num < 10) pw.print(' ');
11882             pw.print(num);
11883             pw.print(": ");
11884             pw.print(oomAdj);
11885             pw.print(' ');
11886             pw.print(schedGroup);
11887             pw.print('/');
11888             pw.print(foreground);
11889             pw.print('/');
11890             pw.print(procState);
11891             pw.print(" trm:");
11892             if (r.trimMemoryLevel < 10) pw.print(' ');
11893             pw.print(r.trimMemoryLevel);
11894             pw.print(' ');
11895             pw.print(r.toShortString());
11896             pw.print(" (");
11897             pw.print(r.adjType);
11898             pw.println(')');
11899             if (r.adjSource != null || r.adjTarget != null) {
11900                 pw.print(prefix);
11901                 pw.print("    ");
11902                 if (r.adjTarget instanceof ComponentName) {
11903                     pw.print(((ComponentName)r.adjTarget).flattenToShortString());
11904                 } else if (r.adjTarget != null) {
11905                     pw.print(r.adjTarget.toString());
11906                 } else {
11907                     pw.print("{null}");
11908                 }
11909                 pw.print("<=");
11910                 if (r.adjSource instanceof ProcessRecord) {
11911                     pw.print("Proc{");
11912                     pw.print(((ProcessRecord)r.adjSource).toShortString());
11913                     pw.println("}");
11914                 } else if (r.adjSource != null) {
11915                     pw.println(r.adjSource.toString());
11916                 } else {
11917                     pw.println("{null}");
11918                 }
11919             }
11920             if (inclDetails) {
11921                 pw.print(prefix);
11922                 pw.print("    ");
11923                 pw.print("oom: max="); pw.print(r.maxAdj);
11924                 pw.print(" curRaw="); pw.print(r.getCurRawAdj());
11925                 pw.print(" setRaw="); pw.print(r.setRawAdj);
11926                 pw.print(" cur="); pw.print(r.curAdj);
11927                 pw.print(" set="); pw.println(r.setAdj);
11928                 pw.print(prefix);
11929                 pw.print("    ");
11930                 pw.print("state: cur="); pw.print(
11931                         ProcessList.makeProcStateString(r.getCurProcState()));
11932                 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState));
11933                 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, r.lastPss*1024);
11934                 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, r.lastSwapPss*1024);
11935                 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, r.lastCachedPss*1024);
11936                 pw.println();
11937                 pw.print(prefix);
11938                 pw.print("    ");
11939                 pw.print("cached="); pw.print(r.cached);
11940                 pw.print(" empty="); pw.print(r.empty);
11941                 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
11942 
11943                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
11944                     if (r.lastCpuTime != 0) {
11945                         long timeUsed = r.curCpuTime - r.lastCpuTime;
11946                         pw.print(prefix);
11947                         pw.print("    ");
11948                         pw.print("run cpu over ");
11949                         TimeUtils.formatDuration(uptimeSince, pw);
11950                         pw.print(" used ");
11951                         TimeUtils.formatDuration(timeUsed, pw);
11952                         pw.print(" (");
11953                         pw.print((timeUsed*100)/uptimeSince);
11954                         pw.println("%)");
11955                     }
11956                 }
11957             }
11958         }
11959         return true;
11960     }
11961 
collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)11962     ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs,
11963             String[] args) {
11964         synchronized (this) {
11965             return mProcessList.collectProcessesLocked(start, allPkgs, args);
11966         }
11967     }
11968 
dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)11969     final void dumpGraphicsHardwareUsage(FileDescriptor fd,
11970             PrintWriter pw, String[] args) {
11971         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
11972         if (procs == null) {
11973             pw.println("No process found for: " + args[0]);
11974             return;
11975         }
11976 
11977         long uptime = SystemClock.uptimeMillis();
11978         long realtime = SystemClock.elapsedRealtime();
11979         pw.println("Applications Graphics Acceleration Info:");
11980         pw.println("Uptime: " + uptime + " Realtime: " + realtime);
11981 
11982         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
11983             ProcessRecord r = procs.get(i);
11984             if (r.thread != null) {
11985                 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
11986                 pw.flush();
11987                 try {
11988                     TransferPipe tp = new TransferPipe();
11989                     try {
11990                         r.thread.dumpGfxInfo(tp.getWriteFd(), args);
11991                         tp.go(fd);
11992                     } finally {
11993                         tp.kill();
11994                     }
11995                 } catch (IOException e) {
11996                     pw.println("Failure while dumping the app: " + r);
11997                     pw.flush();
11998                 } catch (RemoteException e) {
11999                     pw.println("Got a RemoteException while dumping the app " + r);
12000                     pw.flush();
12001                 }
12002             }
12003         }
12004     }
12005 
dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)12006     final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
12007         ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args);
12008         if (procs == null) {
12009             pw.println("No process found for: " + args[0]);
12010             return;
12011         }
12012 
12013         pw.println("Applications Database Info:");
12014 
12015         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12016             ProcessRecord r = procs.get(i);
12017             if (r.thread != null) {
12018                 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
12019                 pw.flush();
12020                 try {
12021                     TransferPipe tp = new TransferPipe();
12022                     try {
12023                         r.thread.dumpDbInfo(tp.getWriteFd(), args);
12024                         tp.go(fd);
12025                     } finally {
12026                         tp.kill();
12027                     }
12028                 } catch (IOException e) {
12029                     pw.println("Failure while dumping the app: " + r);
12030                     pw.flush();
12031                 } catch (RemoteException e) {
12032                     pw.println("Got a RemoteException while dumping the app " + r);
12033                     pw.flush();
12034                 }
12035             }
12036         }
12037     }
12038 
12039     final static class MemItem {
12040         final boolean isProc;
12041         final String label;
12042         final String shortLabel;
12043         final long pss;
12044         final long swapPss;
12045         final int id;
12046         final boolean hasActivities;
12047         ArrayList<MemItem> subitems;
12048 
MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id, boolean _hasActivities)12049         public MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id,
12050                 boolean _hasActivities) {
12051             isProc = true;
12052             label = _label;
12053             shortLabel = _shortLabel;
12054             pss = _pss;
12055             swapPss = _swapPss;
12056             id = _id;
12057             hasActivities = _hasActivities;
12058         }
12059 
MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id)12060         public MemItem(String _label, String _shortLabel, long _pss, long _swapPss, int _id) {
12061             isProc = false;
12062             label = _label;
12063             shortLabel = _shortLabel;
12064             pss = _pss;
12065             swapPss = _swapPss;
12066             id = _id;
12067             hasActivities = false;
12068         }
12069     }
12070 
sortMemItems(List<MemItem> items)12071     private static void sortMemItems(List<MemItem> items) {
12072         Collections.sort(items, new Comparator<MemItem>() {
12073             @Override
12074             public int compare(MemItem lhs, MemItem rhs) {
12075                 if (lhs.pss < rhs.pss) {
12076                     return 1;
12077                 } else if (lhs.pss > rhs.pss) {
12078                     return -1;
12079                 }
12080                 return 0;
12081             }
12082         });
12083     }
12084 
dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpSwapPss)12085     static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
12086             ArrayList<MemItem> items, boolean sort, boolean isCompact, boolean dumpSwapPss) {
12087         if (sort && !isCompact) {
12088             sortMemItems(items);
12089         }
12090 
12091         for (int i=0; i<items.size(); i++) {
12092             MemItem mi = items.get(i);
12093             if (!isCompact) {
12094                 if (dumpSwapPss) {
12095                     pw.printf("%s%s: %-60s (%s in swap)\n", prefix, stringifyKBSize(mi.pss),
12096                             mi.label, stringifyKBSize(mi.swapPss));
12097                 } else {
12098                     pw.printf("%s%s: %s\n", prefix, stringifyKBSize(mi.pss), mi.label);
12099                 }
12100             } else if (mi.isProc) {
12101                 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
12102                 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); pw.print(",");
12103                 pw.print(dumpSwapPss ? mi.swapPss : "N/A");
12104                 pw.println(mi.hasActivities ? ",a" : ",e");
12105             } else {
12106                 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
12107                 pw.print(mi.pss); pw.print(","); pw.println(dumpSwapPss ? mi.swapPss : "N/A");
12108             }
12109             if (mi.subitems != null) {
12110                 dumpMemItems(pw, prefix + "    ", mi.shortLabel, mi.subitems,
12111                         true, isCompact, dumpSwapPss);
12112             }
12113         }
12114     }
12115 
dumpMemItems(ProtoOutputStream proto, long fieldId, String tag, ArrayList<MemItem> items, boolean sort, boolean dumpSwapPss)12116     static final void dumpMemItems(ProtoOutputStream proto, long fieldId, String tag,
12117             ArrayList<MemItem> items, boolean sort, boolean dumpSwapPss) {
12118         if (sort) {
12119             sortMemItems(items);
12120         }
12121 
12122         for (int i=0; i<items.size(); i++) {
12123             MemItem mi = items.get(i);
12124             final long token = proto.start(fieldId);
12125 
12126             proto.write(MemInfoDumpProto.MemItem.TAG, tag);
12127             proto.write(MemInfoDumpProto.MemItem.LABEL, mi.shortLabel);
12128             proto.write(MemInfoDumpProto.MemItem.IS_PROC, mi.isProc);
12129             proto.write(MemInfoDumpProto.MemItem.ID, mi.id);
12130             proto.write(MemInfoDumpProto.MemItem.HAS_ACTIVITIES, mi.hasActivities);
12131             proto.write(MemInfoDumpProto.MemItem.PSS_KB, mi.pss);
12132             if (dumpSwapPss) {
12133                 proto.write(MemInfoDumpProto.MemItem.SWAP_PSS_KB, mi.swapPss);
12134             }
12135             if (mi.subitems != null) {
12136                 dumpMemItems(proto, MemInfoDumpProto.MemItem.SUB_ITEMS, mi.shortLabel, mi.subitems,
12137                         true, dumpSwapPss);
12138             }
12139             proto.end(token);
12140         }
12141     }
12142 
12143     // These are in KB.
12144     static final long[] DUMP_MEM_BUCKETS = new long[] {
12145         5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
12146         120*1024, 160*1024, 200*1024,
12147         250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
12148         1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
12149     };
12150 
appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)12151     static final void appendMemBucket(StringBuilder out, long memKB, String label,
12152             boolean stackLike) {
12153         int start = label.lastIndexOf('.');
12154         if (start >= 0) start++;
12155         else start = 0;
12156         int end = label.length();
12157         for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
12158             if (DUMP_MEM_BUCKETS[i] >= memKB) {
12159                 long bucket = DUMP_MEM_BUCKETS[i]/1024;
12160                 out.append(bucket);
12161                 out.append(stackLike ? "MB." : "MB ");
12162                 out.append(label, start, end);
12163                 return;
12164             }
12165         }
12166         out.append(memKB/1024);
12167         out.append(stackLike ? "MB." : "MB ");
12168         out.append(label, start, end);
12169     }
12170 
12171     static final int[] DUMP_MEM_OOM_ADJ = new int[] {
12172             ProcessList.NATIVE_ADJ,
12173             ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ,
12174             ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ,
12175             ProcessList.VISIBLE_APP_ADJ,
12176             ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_LOW_APP_ADJ,
12177             ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
12178             ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
12179             ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MIN_ADJ
12180     };
12181     static final String[] DUMP_MEM_OOM_LABEL = new String[] {
12182             "Native",
12183             "System", "Persistent", "Persistent Service", "Foreground",
12184             "Visible", "Perceptible", "Perceptible Low",
12185             "Heavy Weight", "Backup",
12186             "A Services", "Home",
12187             "Previous", "B Services", "Cached"
12188     };
12189     static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
12190             "native",
12191             "sys", "pers", "persvc", "fore",
12192             "vis", "percept", "perceptl",
12193             "heavy", "backup",
12194             "servicea", "home",
12195             "prev", "serviceb", "cached"
12196     };
12197 
dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)12198     private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
12199             long realtime, boolean isCheckinRequest, boolean isCompact) {
12200         if (isCompact) {
12201             pw.print("version,"); pw.println(MEMINFO_COMPACT_VERSION);
12202         }
12203         if (isCheckinRequest || isCompact) {
12204             // short checkin version
12205             pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
12206         } else {
12207             pw.println("Applications Memory Usage (in Kilobytes):");
12208             pw.println("Uptime: " + uptime + " Realtime: " + realtime);
12209         }
12210     }
12211 
12212     private static final int KSM_SHARED = 0;
12213     private static final int KSM_SHARING = 1;
12214     private static final int KSM_UNSHARED = 2;
12215     private static final int KSM_VOLATILE = 3;
12216 
getKsmInfo()12217     private final long[] getKsmInfo() {
12218         long[] longOut = new long[4];
12219         final int[] SINGLE_LONG_FORMAT = new int[] {
12220             PROC_SPACE_TERM| PROC_OUT_LONG
12221         };
12222         long[] longTmp = new long[1];
12223         readProcFile("/sys/kernel/mm/ksm/pages_shared",
12224                 SINGLE_LONG_FORMAT, null, longTmp, null);
12225         longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12226         longTmp[0] = 0;
12227         readProcFile("/sys/kernel/mm/ksm/pages_sharing",
12228                 SINGLE_LONG_FORMAT, null, longTmp, null);
12229         longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12230         longTmp[0] = 0;
12231         readProcFile("/sys/kernel/mm/ksm/pages_unshared",
12232                 SINGLE_LONG_FORMAT, null, longTmp, null);
12233         longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12234         longTmp[0] = 0;
12235         readProcFile("/sys/kernel/mm/ksm/pages_volatile",
12236                 SINGLE_LONG_FORMAT, null, longTmp, null);
12237         longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024;
12238         return longOut;
12239     }
12240 
stringifySize(long size, int order)12241     private static String stringifySize(long size, int order) {
12242         Locale locale = Locale.US;
12243         switch (order) {
12244             case 1:
12245                 return String.format(locale, "%,13d", size);
12246             case 1024:
12247                 return String.format(locale, "%,9dK", size / 1024);
12248             case 1024 * 1024:
12249                 return String.format(locale, "%,5dM", size / 1024 / 1024);
12250             case 1024 * 1024 * 1024:
12251                 return String.format(locale, "%,1dG", size / 1024 / 1024 / 1024);
12252             default:
12253                 throw new IllegalArgumentException("Invalid size order");
12254         }
12255     }
12256 
stringifyKBSize(long size)12257     private static String stringifyKBSize(long size) {
12258         return stringifySize(size * 1024, 1024);
12259     }
12260 
12261     // Update this version number if you change the 'compact' format.
12262     private static final int MEMINFO_COMPACT_VERSION = 1;
12263 
12264     private static class MemoryUsageDumpOptions {
12265         boolean dumpDetails;
12266         boolean dumpFullDetails;
12267         boolean dumpDalvik;
12268         boolean dumpSummaryOnly;
12269         boolean dumpUnreachable;
12270         boolean oomOnly;
12271         boolean isCompact;
12272         boolean localOnly;
12273         boolean packages;
12274         boolean isCheckinRequest;
12275         boolean dumpSwapPss;
12276         boolean dumpProto;
12277     }
12278 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw, boolean asProto)12279     final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
12280             String[] args, boolean brief, PrintWriter categoryPw, boolean asProto) {
12281         MemoryUsageDumpOptions opts = new MemoryUsageDumpOptions();
12282         opts.dumpDetails = false;
12283         opts.dumpFullDetails = false;
12284         opts.dumpDalvik = false;
12285         opts.dumpSummaryOnly = false;
12286         opts.dumpUnreachable = false;
12287         opts.oomOnly = false;
12288         opts.isCompact = false;
12289         opts.localOnly = false;
12290         opts.packages = false;
12291         opts.isCheckinRequest = false;
12292         opts.dumpSwapPss = false;
12293         opts.dumpProto = asProto;
12294 
12295         int opti = 0;
12296         while (opti < args.length) {
12297             String opt = args[opti];
12298             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12299                 break;
12300             }
12301             opti++;
12302             if ("-a".equals(opt)) {
12303                 opts.dumpDetails = true;
12304                 opts.dumpFullDetails = true;
12305                 opts.dumpDalvik = true;
12306                 opts.dumpSwapPss = true;
12307             } else if ("-d".equals(opt)) {
12308                 opts.dumpDalvik = true;
12309             } else if ("-c".equals(opt)) {
12310                 opts.isCompact = true;
12311             } else if ("-s".equals(opt)) {
12312                 opts.dumpDetails = true;
12313                 opts.dumpSummaryOnly = true;
12314             } else if ("-S".equals(opt)) {
12315                 opts.dumpSwapPss = true;
12316             } else if ("--unreachable".equals(opt)) {
12317                 opts.dumpUnreachable = true;
12318             } else if ("--oom".equals(opt)) {
12319                 opts.oomOnly = true;
12320             } else if ("--local".equals(opt)) {
12321                 opts.localOnly = true;
12322             } else if ("--package".equals(opt)) {
12323                 opts.packages = true;
12324             } else if ("--checkin".equals(opt)) {
12325                 opts.isCheckinRequest = true;
12326             } else if ("--proto".equals(opt)) {
12327                 opts.dumpProto = true;
12328 
12329             } else if ("-h".equals(opt)) {
12330                 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]");
12331                 pw.println("  -a: include all available information for each process.");
12332                 pw.println("  -d: include dalvik details.");
12333                 pw.println("  -c: dump in a compact machine-parseable representation.");
12334                 pw.println("  -s: dump only summary of application memory usage.");
12335                 pw.println("  -S: dump also SwapPss.");
12336                 pw.println("  --oom: only show processes organized by oom adj.");
12337                 pw.println("  --local: only collect details locally, don't call process.");
12338                 pw.println("  --package: interpret process arg as package, dumping all");
12339                 pw.println("             processes that have loaded that package.");
12340                 pw.println("  --checkin: dump data for a checkin");
12341                 pw.println("  --proto: dump data to proto");
12342                 pw.println("If [process] is specified it can be the name or ");
12343                 pw.println("pid of a specific process to dump.");
12344                 return;
12345             } else {
12346                 pw.println("Unknown argument: " + opt + "; use -h for help");
12347             }
12348         }
12349 
12350         String[] innerArgs = new String[args.length-opti];
12351         System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
12352 
12353         ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, opts.packages, args);
12354         if (opts.dumpProto) {
12355             dumpApplicationMemoryUsage(fd, opts, innerArgs, brief, procs);
12356         } else {
12357             dumpApplicationMemoryUsage(fd, pw, prefix, opts, innerArgs, brief, procs, categoryPw);
12358         }
12359     }
12360 
dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs, PrintWriter categoryPw)12361     private final void dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix,
12362             MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief,
12363             ArrayList<ProcessRecord> procs, PrintWriter categoryPw) {
12364         long uptime = SystemClock.uptimeMillis();
12365         long realtime = SystemClock.elapsedRealtime();
12366         final long[] tmpLong = new long[1];
12367 
12368         if (procs == null) {
12369             // No Java processes.  Maybe they want to print a native process.
12370             String proc = "N/A";
12371             if (innerArgs.length > 0) {
12372                 proc = innerArgs[0];
12373                 if (proc.charAt(0) != '-') {
12374                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
12375                             = new ArrayList<ProcessCpuTracker.Stats>();
12376                     updateCpuStatsNow();
12377                     int findPid = -1;
12378                     try {
12379                         findPid = Integer.parseInt(innerArgs[0]);
12380                     } catch (NumberFormatException e) {
12381                     }
12382                     synchronized (mProcessCpuTracker) {
12383                         final int N = mProcessCpuTracker.countStats();
12384                         for (int i=0; i<N; i++) {
12385                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12386                             if (st.pid == findPid || (st.baseName != null
12387                                     && st.baseName.equals(innerArgs[0]))) {
12388                                 nativeProcs.add(st);
12389                             }
12390                         }
12391                     }
12392                     if (nativeProcs.size() > 0) {
12393                         dumpApplicationMemoryUsageHeader(pw, uptime, realtime,
12394                                 opts.isCheckinRequest, opts.isCompact);
12395                         Debug.MemoryInfo mi = null;
12396                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12397                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12398                             final int pid = r.pid;
12399                             if (!opts.isCheckinRequest && opts.dumpDetails) {
12400                                 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **");
12401                             }
12402                             if (mi == null) {
12403                                 mi = new Debug.MemoryInfo();
12404                             }
12405                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12406                                 Debug.getMemoryInfo(pid, mi);
12407                             } else {
12408                                 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null);
12409                                 mi.dalvikPrivateDirty = (int)tmpLong[0];
12410                             }
12411                             ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest,
12412                                     opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
12413                                     pid, r.baseName, 0, 0, 0, 0, 0, 0);
12414                             if (opts.isCheckinRequest) {
12415                                 pw.println();
12416                             }
12417                         }
12418                         return;
12419                     }
12420                 }
12421             }
12422             pw.println("No process found for: " + proc);
12423             return;
12424         }
12425 
12426         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
12427             opts.dumpDetails = true;
12428         }
12429 
12430         dumpApplicationMemoryUsageHeader(pw, uptime, realtime, opts.isCheckinRequest, opts.isCompact);
12431 
12432         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
12433         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
12434         long nativePss = 0;
12435         long nativeSwapPss = 0;
12436         long dalvikPss = 0;
12437         long dalvikSwapPss = 0;
12438         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12439                 EmptyArray.LONG;
12440         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12441                 EmptyArray.LONG;
12442         long otherPss = 0;
12443         long otherSwapPss = 0;
12444         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12445         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12446 
12447         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
12448         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
12449         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
12450                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
12451 
12452         long totalPss = 0;
12453         long totalSwapPss = 0;
12454         long cachedPss = 0;
12455         long cachedSwapPss = 0;
12456         boolean hasSwapPss = false;
12457 
12458         Debug.MemoryInfo mi = null;
12459         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12460             final ProcessRecord r = procs.get(i);
12461             final IApplicationThread thread;
12462             final int pid;
12463             final int oomAdj;
12464             final boolean hasActivities;
12465             synchronized (this) {
12466                 thread = r.thread;
12467                 pid = r.pid;
12468                 oomAdj = r.getSetAdjWithServices();
12469                 hasActivities = r.hasActivities();
12470             }
12471             if (thread != null) {
12472                 if (!opts.isCheckinRequest && opts.dumpDetails) {
12473                     pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
12474                 }
12475                 if (mi == null) {
12476                     mi = new Debug.MemoryInfo();
12477                 }
12478                 final int reportType;
12479                 final long startTime;
12480                 final long endTime;
12481                 if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12482                     reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
12483                     startTime = SystemClock.currentThreadTimeMillis();
12484                     Debug.getMemoryInfo(pid, mi);
12485                     endTime = SystemClock.currentThreadTimeMillis();
12486                     hasSwapPss = mi.hasSwappedOutPss;
12487                 } else {
12488                     reportType = ProcessStats.ADD_PSS_EXTERNAL;
12489                     startTime = SystemClock.currentThreadTimeMillis();
12490                     mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null);
12491                     endTime = SystemClock.currentThreadTimeMillis();
12492                     mi.dalvikPrivateDirty = (int)tmpLong[0];
12493                 }
12494                 if (opts.dumpDetails) {
12495                     if (opts.localOnly) {
12496                         ActivityThread.dumpMemInfoTable(pw, mi, opts.isCheckinRequest, opts.dumpFullDetails,
12497                                 opts.dumpDalvik, opts.dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0);
12498                         if (opts.isCheckinRequest) {
12499                             pw.println();
12500                         }
12501                     } else {
12502                         pw.flush();
12503                         try {
12504                             TransferPipe tp = new TransferPipe();
12505                             try {
12506                                 thread.dumpMemInfo(tp.getWriteFd(),
12507                                         mi, opts.isCheckinRequest, opts.dumpFullDetails,
12508                                         opts.dumpDalvik, opts.dumpSummaryOnly, opts.dumpUnreachable, innerArgs);
12509                                 tp.go(fd, opts.dumpUnreachable ? 30000 : 5000);
12510                             } finally {
12511                                 tp.kill();
12512                             }
12513                         } catch (IOException e) {
12514                             if (!opts.isCheckinRequest) {
12515                                 pw.println("Got IoException! " + e);
12516                                 pw.flush();
12517                             }
12518                         } catch (RemoteException e) {
12519                             if (!opts.isCheckinRequest) {
12520                                 pw.println("Got RemoteException! " + e);
12521                                 pw.flush();
12522                             }
12523                         }
12524                     }
12525                 }
12526 
12527                 final long myTotalPss = mi.getTotalPss();
12528                 final long myTotalUss = mi.getTotalUss();
12529                 final long myTotalRss = mi.getTotalRss();
12530                 final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12531 
12532                 synchronized (this) {
12533                     if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
12534                         // Record this for posterity if the process has been stable.
12535                         r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true,
12536                                 reportType, endTime-startTime, r.pkgList.mPkgList);
12537                         for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) {
12538                             ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg);
12539                             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
12540                                     r.info.uid,
12541                                     holder.state.getName(),
12542                                     holder.state.getPackage(),
12543                                     myTotalPss, myTotalUss, myTotalRss, reportType,
12544                                     endTime-startTime,
12545                                     holder.appVersion);
12546                         }
12547                     }
12548                 }
12549 
12550                 if (!opts.isCheckinRequest && mi != null) {
12551                     totalPss += myTotalPss;
12552                     totalSwapPss += myTotalSwapPss;
12553                     MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
12554                             (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
12555                             myTotalSwapPss, pid, hasActivities);
12556                     procMems.add(pssItem);
12557                     procMemsMap.put(pid, pssItem);
12558 
12559                     nativePss += mi.nativePss;
12560                     nativeSwapPss += mi.nativeSwappedOutPss;
12561                     dalvikPss += mi.dalvikPss;
12562                     dalvikSwapPss += mi.dalvikSwappedOutPss;
12563                     for (int j=0; j<dalvikSubitemPss.length; j++) {
12564                         dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12565                         dalvikSubitemSwapPss[j] +=
12566                                 mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12567                     }
12568                     otherPss += mi.otherPss;
12569                     otherSwapPss += mi.otherSwappedOutPss;
12570                     for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12571                         long mem = mi.getOtherPss(j);
12572                         miscPss[j] += mem;
12573                         otherPss -= mem;
12574                         mem = mi.getOtherSwappedOutPss(j);
12575                         miscSwapPss[j] += mem;
12576                         otherSwapPss -= mem;
12577                     }
12578 
12579                     if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
12580                         cachedPss += myTotalPss;
12581                         cachedSwapPss += myTotalSwapPss;
12582                     }
12583 
12584                     for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
12585                         if (oomIndex == (oomPss.length - 1)
12586                                 || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
12587                                         && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
12588                             oomPss[oomIndex] += myTotalPss;
12589                             oomSwapPss[oomIndex] += myTotalSwapPss;
12590                             if (oomProcs[oomIndex] == null) {
12591                                 oomProcs[oomIndex] = new ArrayList<MemItem>();
12592                             }
12593                             oomProcs[oomIndex].add(pssItem);
12594                             break;
12595                         }
12596                     }
12597                 }
12598             }
12599         }
12600 
12601         long nativeProcTotalPss = 0;
12602 
12603         if (!opts.isCheckinRequest && procs.size() > 1 && !opts.packages) {
12604             // If we are showing aggregations, also look for native processes to
12605             // include so that our aggregations are more accurate.
12606             updateCpuStatsNow();
12607             mi = null;
12608             synchronized (mProcessCpuTracker) {
12609                 final int N = mProcessCpuTracker.countStats();
12610                 for (int i=0; i<N; i++) {
12611                     ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12612                     if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
12613                         if (mi == null) {
12614                             mi = new Debug.MemoryInfo();
12615                         }
12616                         if (!brief && !opts.oomOnly) {
12617                             Debug.getMemoryInfo(st.pid, mi);
12618                         } else {
12619                             mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null);
12620                             mi.nativePrivateDirty = (int)tmpLong[0];
12621                         }
12622 
12623                         final long myTotalPss = mi.getTotalPss();
12624                         final long myTotalSwapPss = mi.getTotalSwappedOutPss();
12625                         totalPss += myTotalPss;
12626                         totalSwapPss += myTotalSwapPss;
12627                         nativeProcTotalPss += myTotalPss;
12628 
12629                         MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
12630                                 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false);
12631                         procMems.add(pssItem);
12632 
12633                         nativePss += mi.nativePss;
12634                         nativeSwapPss += mi.nativeSwappedOutPss;
12635                         dalvikPss += mi.dalvikPss;
12636                         dalvikSwapPss += mi.dalvikSwappedOutPss;
12637                         for (int j=0; j<dalvikSubitemPss.length; j++) {
12638                             dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12639                             dalvikSubitemSwapPss[j] +=
12640                                     mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
12641                         }
12642                         otherPss += mi.otherPss;
12643                         otherSwapPss += mi.otherSwappedOutPss;
12644                         for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12645                             long mem = mi.getOtherPss(j);
12646                             miscPss[j] += mem;
12647                             otherPss -= mem;
12648                             mem = mi.getOtherSwappedOutPss(j);
12649                             miscSwapPss[j] += mem;
12650                             otherSwapPss -= mem;
12651                         }
12652                         oomPss[0] += myTotalPss;
12653                         oomSwapPss[0] += myTotalSwapPss;
12654                         if (oomProcs[0] == null) {
12655                             oomProcs[0] = new ArrayList<MemItem>();
12656                         }
12657                         oomProcs[0].add(pssItem);
12658                     }
12659                 }
12660             }
12661 
12662             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
12663 
12664             catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1));
12665             final int dalvikId = -2;
12666             catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikId));
12667             catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3));
12668             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
12669                 String label = Debug.MemoryInfo.getOtherLabel(j);
12670                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j));
12671             }
12672             if (dalvikSubitemPss.length > 0) {
12673                 // Add dalvik subitems.
12674                 for (MemItem memItem : catMems) {
12675                     int memItemStart = 0, memItemEnd = 0;
12676                     if (memItem.id == dalvikId) {
12677                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
12678                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
12679                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
12680                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
12681                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
12682                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
12683                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
12684                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
12685                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
12686                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
12687                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
12688                     } else {
12689                         continue;  // No subitems, continue.
12690                     }
12691                     memItem.subitems = new ArrayList<MemItem>();
12692                     for (int j=memItemStart; j<=memItemEnd; j++) {
12693                         final String name = Debug.MemoryInfo.getOtherLabel(
12694                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
12695                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
12696                                 dalvikSubitemSwapPss[j], j));
12697                     }
12698                 }
12699             }
12700 
12701             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
12702             for (int j=0; j<oomPss.length; j++) {
12703                 if (oomPss[j] != 0) {
12704                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
12705                             : DUMP_MEM_OOM_LABEL[j];
12706                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j],
12707                             DUMP_MEM_OOM_ADJ[j]);
12708                     item.subitems = oomProcs[j];
12709                     oomMems.add(item);
12710                 }
12711             }
12712 
12713             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0;
12714             if (!brief && !opts.oomOnly && !opts.isCompact) {
12715                 pw.println();
12716                 pw.println("Total PSS by process:");
12717                 dumpMemItems(pw, "  ", "proc", procMems, true, opts.isCompact, opts.dumpSwapPss);
12718                 pw.println();
12719             }
12720             if (!opts.isCompact) {
12721                 pw.println("Total PSS by OOM adjustment:");
12722             }
12723             dumpMemItems(pw, "  ", "oom", oomMems, false, opts.isCompact, opts.dumpSwapPss);
12724             if (!brief && !opts.oomOnly) {
12725                 PrintWriter out = categoryPw != null ? categoryPw : pw;
12726                 if (!opts.isCompact) {
12727                     out.println();
12728                     out.println("Total PSS by category:");
12729                 }
12730                 dumpMemItems(out, "  ", "cat", catMems, true, opts.isCompact, opts.dumpSwapPss);
12731             }
12732             if (!opts.isCompact) {
12733                 pw.println();
12734             }
12735             MemInfoReader memInfo = new MemInfoReader();
12736             memInfo.readMemInfo();
12737             if (nativeProcTotalPss > 0) {
12738                 synchronized (this) {
12739                     final long cachedKb = memInfo.getCachedSizeKb();
12740                     final long freeKb = memInfo.getFreeSizeKb();
12741                     final long zramKb = memInfo.getZramTotalSizeKb();
12742                     final long kernelKb = memInfo.getKernelUsedSizeKb();
12743                     EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
12744                             kernelKb*1024, nativeProcTotalPss*1024);
12745                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
12746                             nativeProcTotalPss);
12747                 }
12748             }
12749             if (!brief) {
12750                 if (!opts.isCompact) {
12751                     pw.print("Total RAM: "); pw.print(stringifyKBSize(memInfo.getTotalSizeKb()));
12752                     pw.print(" (status ");
12753                     switch (mLastMemoryLevel) {
12754                         case ProcessStats.ADJ_MEM_FACTOR_NORMAL:
12755                             pw.println("normal)");
12756                             break;
12757                         case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
12758                             pw.println("moderate)");
12759                             break;
12760                         case ProcessStats.ADJ_MEM_FACTOR_LOW:
12761                             pw.println("low)");
12762                             break;
12763                         case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
12764                             pw.println("critical)");
12765                             break;
12766                         default:
12767                             pw.print(mLastMemoryLevel);
12768                             pw.println(")");
12769                             break;
12770                     }
12771                     pw.print(" Free RAM: ");
12772                     pw.print(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
12773                             + memInfo.getFreeSizeKb()));
12774                     pw.print(" (");
12775                     pw.print(stringifyKBSize(cachedPss));
12776                     pw.print(" cached pss + ");
12777                     pw.print(stringifyKBSize(memInfo.getCachedSizeKb()));
12778                     pw.print(" cached kernel + ");
12779                     pw.print(stringifyKBSize(memInfo.getFreeSizeKb()));
12780                     pw.println(" free)");
12781                 } else {
12782                     pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
12783                     pw.print(cachedPss + memInfo.getCachedSizeKb()
12784                             + memInfo.getFreeSizeKb()); pw.print(",");
12785                     pw.println(totalPss - cachedPss);
12786                 }
12787             }
12788             long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss)
12789                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
12790                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
12791             if (!opts.isCompact) {
12792                 pw.print(" Used RAM: "); pw.print(stringifyKBSize(totalPss - cachedPss
12793                         + memInfo.getKernelUsedSizeKb())); pw.print(" (");
12794                 pw.print(stringifyKBSize(totalPss - cachedPss)); pw.print(" used pss + ");
12795                 pw.print(stringifyKBSize(memInfo.getKernelUsedSizeKb())); pw.print(" kernel)\n");
12796                 pw.print(" Lost RAM: "); pw.println(stringifyKBSize(lostRAM));
12797             } else {
12798                 pw.print("lostram,"); pw.println(lostRAM);
12799             }
12800             if (!brief) {
12801                 if (memInfo.getZramTotalSizeKb() != 0) {
12802                     if (!opts.isCompact) {
12803                         pw.print("     ZRAM: ");
12804                         pw.print(stringifyKBSize(memInfo.getZramTotalSizeKb()));
12805                                 pw.print(" physical used for ");
12806                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()
12807                                         - memInfo.getSwapFreeSizeKb()));
12808                                 pw.print(" in swap (");
12809                                 pw.print(stringifyKBSize(memInfo.getSwapTotalSizeKb()));
12810                                 pw.println(" total swap)");
12811                     } else {
12812                         pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
12813                                 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
12814                                 pw.println(memInfo.getSwapFreeSizeKb());
12815                     }
12816                 }
12817                 final long[] ksm = getKsmInfo();
12818                 if (!opts.isCompact) {
12819                     if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
12820                             || ksm[KSM_VOLATILE] != 0) {
12821                         pw.print("      KSM: "); pw.print(stringifyKBSize(ksm[KSM_SHARING]));
12822                                 pw.print(" saved from shared ");
12823                                 pw.print(stringifyKBSize(ksm[KSM_SHARED]));
12824                         pw.print("           "); pw.print(stringifyKBSize(ksm[KSM_UNSHARED]));
12825                                 pw.print(" unshared; ");
12826                                 pw.print(stringifyKBSize(
12827                                              ksm[KSM_VOLATILE])); pw.println(" volatile");
12828                     }
12829                     pw.print("   Tuning: ");
12830                     pw.print(ActivityManager.staticGetMemoryClass());
12831                     pw.print(" (large ");
12832                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12833                     pw.print("), oom ");
12834                     pw.print(stringifySize(
12835                                 mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ), 1024));
12836                     pw.print(", restore limit ");
12837                     pw.print(stringifyKBSize(mProcessList.getCachedRestoreThresholdKb()));
12838                     if (ActivityManager.isLowRamDeviceStatic()) {
12839                         pw.print(" (low-ram)");
12840                     }
12841                     if (ActivityManager.isHighEndGfx()) {
12842                         pw.print(" (high-end-gfx)");
12843                     }
12844                     pw.println();
12845                 } else {
12846                     pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(",");
12847                     pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]);
12848                     pw.print(","); pw.println(ksm[KSM_VOLATILE]);
12849                     pw.print("tuning,");
12850                     pw.print(ActivityManager.staticGetMemoryClass());
12851                     pw.print(',');
12852                     pw.print(ActivityManager.staticGetLargeMemoryClass());
12853                     pw.print(',');
12854                     pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
12855                     if (ActivityManager.isLowRamDeviceStatic()) {
12856                         pw.print(",low-ram");
12857                     }
12858                     if (ActivityManager.isHighEndGfx()) {
12859                         pw.print(",high-end-gfx");
12860                     }
12861                     pw.println();
12862                 }
12863             }
12864         }
12865     }
12866 
dumpApplicationMemoryUsage(FileDescriptor fd, MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief, ArrayList<ProcessRecord> procs)12867     private final void dumpApplicationMemoryUsage(FileDescriptor fd,
12868             MemoryUsageDumpOptions opts, String[] innerArgs, boolean brief,
12869             ArrayList<ProcessRecord> procs) {
12870         final long uptimeMs = SystemClock.uptimeMillis();
12871         final long realtimeMs = SystemClock.elapsedRealtime();
12872         final long[] tmpLong = new long[1];
12873 
12874         if (procs == null) {
12875             // No Java processes.  Maybe they want to print a native process.
12876             String proc = "N/A";
12877             if (innerArgs.length > 0) {
12878                 proc = innerArgs[0];
12879                 if (proc.charAt(0) != '-') {
12880                     ArrayList<ProcessCpuTracker.Stats> nativeProcs
12881                             = new ArrayList<ProcessCpuTracker.Stats>();
12882                     updateCpuStatsNow();
12883                     int findPid = -1;
12884                     try {
12885                         findPid = Integer.parseInt(innerArgs[0]);
12886                     } catch (NumberFormatException e) {
12887                     }
12888                     synchronized (mProcessCpuTracker) {
12889                         final int N = mProcessCpuTracker.countStats();
12890                         for (int i=0; i<N; i++) {
12891                             ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12892                             if (st.pid == findPid || (st.baseName != null
12893                                     && st.baseName.equals(innerArgs[0]))) {
12894                                 nativeProcs.add(st);
12895                             }
12896                         }
12897                     }
12898                     if (nativeProcs.size() > 0) {
12899                         ProtoOutputStream proto = new ProtoOutputStream(fd);
12900 
12901                         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12902                         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12903                         Debug.MemoryInfo mi = null;
12904                         for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12905                             final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12906                             final int pid = r.pid;
12907                             final long nToken = proto.start(MemInfoDumpProto.NATIVE_PROCESSES);
12908 
12909                             proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
12910                             proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.baseName);
12911 
12912                             if (mi == null) {
12913                                 mi = new Debug.MemoryInfo();
12914                             }
12915                             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12916                                 Debug.getMemoryInfo(pid, mi);
12917                             } else {
12918                                 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null);
12919                                 mi.dalvikPrivateDirty = (int)tmpLong[0];
12920                             }
12921                             ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
12922                                     opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
12923 
12924                             proto.end(nToken);
12925                         }
12926 
12927                         proto.flush();
12928                         return;
12929                     }
12930                 }
12931             }
12932             Log.d(TAG, "No process found for: " + innerArgs[0]);
12933             return;
12934         }
12935 
12936         if (!brief && !opts.oomOnly && (procs.size() == 1 || opts.isCheckinRequest || opts.packages)) {
12937             opts.dumpDetails = true;
12938         }
12939 
12940         ProtoOutputStream proto = new ProtoOutputStream(fd);
12941 
12942         proto.write(MemInfoDumpProto.UPTIME_DURATION_MS, uptimeMs);
12943         proto.write(MemInfoDumpProto.ELAPSED_REALTIME_MS, realtimeMs);
12944 
12945         ArrayList<MemItem> procMems = new ArrayList<MemItem>();
12946         final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
12947         long nativePss = 0;
12948         long nativeSwapPss = 0;
12949         long dalvikPss = 0;
12950         long dalvikSwapPss = 0;
12951         long[] dalvikSubitemPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12952                 EmptyArray.LONG;
12953         long[] dalvikSubitemSwapPss = opts.dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] :
12954                 EmptyArray.LONG;
12955         long otherPss = 0;
12956         long otherSwapPss = 0;
12957         long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12958         long[] miscSwapPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
12959 
12960         long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
12961         long oomSwapPss[] = new long[DUMP_MEM_OOM_LABEL.length];
12962         ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
12963                 new ArrayList[DUMP_MEM_OOM_LABEL.length];
12964 
12965         long totalPss = 0;
12966         long totalSwapPss = 0;
12967         long cachedPss = 0;
12968         long cachedSwapPss = 0;
12969         boolean hasSwapPss = false;
12970 
12971         Debug.MemoryInfo mi = null;
12972         for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12973             final ProcessRecord r = procs.get(i);
12974             final IApplicationThread thread;
12975             final int pid;
12976             final int oomAdj;
12977             final boolean hasActivities;
12978             synchronized (this) {
12979                 thread = r.thread;
12980                 pid = r.pid;
12981                 oomAdj = r.getSetAdjWithServices();
12982                 hasActivities = r.hasActivities();
12983             }
12984             if (thread == null) {
12985                 continue;
12986             }
12987             if (mi == null) {
12988                 mi = new Debug.MemoryInfo();
12989             }
12990             final int reportType;
12991             final long startTime;
12992             final long endTime;
12993             if (opts.dumpDetails || (!brief && !opts.oomOnly)) {
12994                 reportType = ProcessStats.ADD_PSS_EXTERNAL_SLOW;
12995                 startTime = SystemClock.currentThreadTimeMillis();
12996                 Debug.getMemoryInfo(pid, mi);
12997                 endTime = SystemClock.currentThreadTimeMillis();
12998                 hasSwapPss = mi.hasSwappedOutPss;
12999             } else {
13000                 reportType = ProcessStats.ADD_PSS_EXTERNAL;
13001                 startTime = SystemClock.currentThreadTimeMillis();
13002                 mi.dalvikPss = (int) Debug.getPss(pid, tmpLong, null);
13003                 endTime = SystemClock.currentThreadTimeMillis();
13004                 mi.dalvikPrivateDirty = (int) tmpLong[0];
13005             }
13006             if (opts.dumpDetails) {
13007                 if (opts.localOnly) {
13008                     final long aToken = proto.start(MemInfoDumpProto.APP_PROCESSES);
13009                     final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
13010                     proto.write(MemInfoDumpProto.ProcessMemory.PID, pid);
13011                     proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME, r.processName);
13012                     ActivityThread.dumpMemInfoTable(proto, mi, opts.dumpDalvik,
13013                             opts.dumpSummaryOnly, 0, 0, 0, 0, 0, 0);
13014                     proto.end(mToken);
13015                     proto.end(aToken);
13016                 } else {
13017                     try {
13018                         ByteTransferPipe tp = new ByteTransferPipe();
13019                         try {
13020                             thread.dumpMemInfoProto(tp.getWriteFd(),
13021                                 mi, opts.dumpFullDetails, opts.dumpDalvik, opts.dumpSummaryOnly,
13022                                 opts.dumpUnreachable, innerArgs);
13023                             proto.write(MemInfoDumpProto.APP_PROCESSES, tp.get());
13024                         } finally {
13025                             tp.kill();
13026                         }
13027                     } catch (IOException e) {
13028                         Log.e(TAG, "Got IOException!", e);
13029                     } catch (RemoteException e) {
13030                         Log.e(TAG, "Got RemoteException!", e);
13031                     }
13032                 }
13033             }
13034 
13035             final long myTotalPss = mi.getTotalPss();
13036             final long myTotalUss = mi.getTotalUss();
13037             final long myTotalRss = mi.getTotalRss();
13038             final long myTotalSwapPss = mi.getTotalSwappedOutPss();
13039 
13040             synchronized (this) {
13041                 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
13042                     // Record this for posterity if the process has been stable.
13043                     r.baseProcessTracker.addPss(myTotalPss, myTotalUss, myTotalRss, true,
13044                             reportType, endTime-startTime, r.pkgList.mPkgList);
13045                     for (int ipkg = r.pkgList.size() - 1; ipkg >= 0; ipkg--) {
13046                         ProcessStats.ProcessStateHolder holder = r.pkgList.valueAt(ipkg);
13047                         StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
13048                                 r.info.uid,
13049                                 holder.state.getName(),
13050                                 holder.state.getPackage(),
13051                                 myTotalPss, myTotalUss, myTotalRss, reportType, endTime-startTime,
13052                                 holder.appVersion);
13053                     }
13054                 }
13055             }
13056 
13057             if (!opts.isCheckinRequest && mi != null) {
13058                 totalPss += myTotalPss;
13059                 totalSwapPss += myTotalSwapPss;
13060                 MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
13061                         (hasActivities ? " / activities)" : ")"), r.processName, myTotalPss,
13062                         myTotalSwapPss, pid, hasActivities);
13063                 procMems.add(pssItem);
13064                 procMemsMap.put(pid, pssItem);
13065 
13066                 nativePss += mi.nativePss;
13067                 nativeSwapPss += mi.nativeSwappedOutPss;
13068                 dalvikPss += mi.dalvikPss;
13069                 dalvikSwapPss += mi.dalvikSwappedOutPss;
13070                 for (int j=0; j<dalvikSubitemPss.length; j++) {
13071                     dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13072                     dalvikSubitemSwapPss[j] +=
13073                             mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13074                 }
13075                 otherPss += mi.otherPss;
13076                 otherSwapPss += mi.otherSwappedOutPss;
13077                 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13078                     long mem = mi.getOtherPss(j);
13079                     miscPss[j] += mem;
13080                     otherPss -= mem;
13081                     mem = mi.getOtherSwappedOutPss(j);
13082                     miscSwapPss[j] += mem;
13083                     otherSwapPss -= mem;
13084                 }
13085 
13086                 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13087                     cachedPss += myTotalPss;
13088                     cachedSwapPss += myTotalSwapPss;
13089                 }
13090 
13091                 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
13092                     if (oomIndex == (oomPss.length - 1)
13093                             || (oomAdj >= DUMP_MEM_OOM_ADJ[oomIndex]
13094                                     && oomAdj < DUMP_MEM_OOM_ADJ[oomIndex + 1])) {
13095                         oomPss[oomIndex] += myTotalPss;
13096                         oomSwapPss[oomIndex] += myTotalSwapPss;
13097                         if (oomProcs[oomIndex] == null) {
13098                             oomProcs[oomIndex] = new ArrayList<MemItem>();
13099                         }
13100                         oomProcs[oomIndex].add(pssItem);
13101                         break;
13102                     }
13103                 }
13104             }
13105         }
13106 
13107         long nativeProcTotalPss = 0;
13108 
13109         if (procs.size() > 1 && !opts.packages) {
13110             // If we are showing aggregations, also look for native processes to
13111             // include so that our aggregations are more accurate.
13112             updateCpuStatsNow();
13113             mi = null;
13114             synchronized (mProcessCpuTracker) {
13115                 final int N = mProcessCpuTracker.countStats();
13116                 for (int i=0; i<N; i++) {
13117                     ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13118                     if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
13119                         if (mi == null) {
13120                             mi = new Debug.MemoryInfo();
13121                         }
13122                         if (!brief && !opts.oomOnly) {
13123                             Debug.getMemoryInfo(st.pid, mi);
13124                         } else {
13125                             mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null);
13126                             mi.nativePrivateDirty = (int)tmpLong[0];
13127                         }
13128 
13129                         final long myTotalPss = mi.getTotalPss();
13130                         final long myTotalSwapPss = mi.getTotalSwappedOutPss();
13131                         totalPss += myTotalPss;
13132                         nativeProcTotalPss += myTotalPss;
13133 
13134                         MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
13135                                 st.name, myTotalPss, mi.getSummaryTotalSwapPss(), st.pid, false);
13136                         procMems.add(pssItem);
13137 
13138                         nativePss += mi.nativePss;
13139                         nativeSwapPss += mi.nativeSwappedOutPss;
13140                         dalvikPss += mi.dalvikPss;
13141                         dalvikSwapPss += mi.dalvikSwappedOutPss;
13142                         for (int j=0; j<dalvikSubitemPss.length; j++) {
13143                             dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13144                             dalvikSubitemSwapPss[j] +=
13145                                     mi.getOtherSwappedOutPss(Debug.MemoryInfo.NUM_OTHER_STATS + j);
13146                         }
13147                         otherPss += mi.otherPss;
13148                         otherSwapPss += mi.otherSwappedOutPss;
13149                         for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13150                             long mem = mi.getOtherPss(j);
13151                             miscPss[j] += mem;
13152                             otherPss -= mem;
13153                             mem = mi.getOtherSwappedOutPss(j);
13154                             miscSwapPss[j] += mem;
13155                             otherSwapPss -= mem;
13156                         }
13157                         oomPss[0] += myTotalPss;
13158                         oomSwapPss[0] += myTotalSwapPss;
13159                         if (oomProcs[0] == null) {
13160                             oomProcs[0] = new ArrayList<MemItem>();
13161                         }
13162                         oomProcs[0].add(pssItem);
13163                     }
13164                 }
13165             }
13166 
13167             ArrayList<MemItem> catMems = new ArrayList<MemItem>();
13168 
13169             catMems.add(new MemItem("Native", "Native", nativePss, nativeSwapPss, -1));
13170             final int dalvikId = -2;
13171             catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, dalvikSwapPss, dalvikId));
13172             catMems.add(new MemItem("Unknown", "Unknown", otherPss, otherSwapPss, -3));
13173             for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13174                 String label = Debug.MemoryInfo.getOtherLabel(j);
13175                 catMems.add(new MemItem(label, label, miscPss[j], miscSwapPss[j], j));
13176             }
13177             if (dalvikSubitemPss.length > 0) {
13178                 // Add dalvik subitems.
13179                 for (MemItem memItem : catMems) {
13180                     int memItemStart = 0, memItemEnd = 0;
13181                     if (memItem.id == dalvikId) {
13182                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_START;
13183                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_END;
13184                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DALVIK_OTHER) {
13185                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_START;
13186                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DALVIK_OTHER_END;
13187                     } else if (memItem.id == Debug.MemoryInfo.OTHER_DEX) {
13188                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_START;
13189                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_DEX_END;
13190                     } else if (memItem.id == Debug.MemoryInfo.OTHER_ART) {
13191                         memItemStart = Debug.MemoryInfo.OTHER_DVK_STAT_ART_START;
13192                         memItemEnd = Debug.MemoryInfo.OTHER_DVK_STAT_ART_END;
13193                     } else {
13194                         continue;  // No subitems, continue.
13195                     }
13196                     memItem.subitems = new ArrayList<MemItem>();
13197                     for (int j=memItemStart; j<=memItemEnd; j++) {
13198                         final String name = Debug.MemoryInfo.getOtherLabel(
13199                                 Debug.MemoryInfo.NUM_OTHER_STATS + j);
13200                         memItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j],
13201                                 dalvikSubitemSwapPss[j], j));
13202                     }
13203                 }
13204             }
13205 
13206             ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
13207             for (int j=0; j<oomPss.length; j++) {
13208                 if (oomPss[j] != 0) {
13209                     String label = opts.isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
13210                             : DUMP_MEM_OOM_LABEL[j];
13211                     MemItem item = new MemItem(label, label, oomPss[j], oomSwapPss[j],
13212                             DUMP_MEM_OOM_ADJ[j]);
13213                     item.subitems = oomProcs[j];
13214                     oomMems.add(item);
13215                 }
13216             }
13217 
13218             opts.dumpSwapPss = opts.dumpSwapPss && hasSwapPss && totalSwapPss != 0;
13219             if (!opts.oomOnly) {
13220                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_PROCESS, "proc",
13221                         procMems, true, opts.dumpSwapPss);
13222             }
13223             dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_OOM_ADJUSTMENT, "oom",
13224                     oomMems, false, opts.dumpSwapPss);
13225             if (!brief && !opts.oomOnly) {
13226                 dumpMemItems(proto, MemInfoDumpProto.TOTAL_PSS_BY_CATEGORY, "cat",
13227                         catMems, true, opts.dumpSwapPss);
13228             }
13229             MemInfoReader memInfo = new MemInfoReader();
13230             memInfo.readMemInfo();
13231             if (nativeProcTotalPss > 0) {
13232                 synchronized (this) {
13233                     final long cachedKb = memInfo.getCachedSizeKb();
13234                     final long freeKb = memInfo.getFreeSizeKb();
13235                     final long zramKb = memInfo.getZramTotalSizeKb();
13236                     final long kernelKb = memInfo.getKernelUsedSizeKb();
13237                     EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024,
13238                             kernelKb*1024, nativeProcTotalPss*1024);
13239                     mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb,
13240                             nativeProcTotalPss);
13241                 }
13242             }
13243             if (!brief) {
13244                 proto.write(MemInfoDumpProto.TOTAL_RAM_KB, memInfo.getTotalSizeKb());
13245                 proto.write(MemInfoDumpProto.STATUS, mLastMemoryLevel);
13246                 proto.write(MemInfoDumpProto.CACHED_PSS_KB, cachedPss);
13247                 proto.write(MemInfoDumpProto.CACHED_KERNEL_KB, memInfo.getCachedSizeKb());
13248                 proto.write(MemInfoDumpProto.FREE_KB, memInfo.getFreeSizeKb());
13249             }
13250             long lostRAM = memInfo.getTotalSizeKb() - (totalPss - totalSwapPss)
13251                     - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
13252                     - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb();
13253             proto.write(MemInfoDumpProto.USED_PSS_KB, totalPss - cachedPss);
13254             proto.write(MemInfoDumpProto.USED_KERNEL_KB, memInfo.getKernelUsedSizeKb());
13255             proto.write(MemInfoDumpProto.LOST_RAM_KB, lostRAM);
13256             if (!brief) {
13257                 if (memInfo.getZramTotalSizeKb() != 0) {
13258                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_KB, memInfo.getZramTotalSizeKb());
13259                     proto.write(MemInfoDumpProto.ZRAM_PHYSICAL_USED_IN_SWAP_KB,
13260                             memInfo.getSwapTotalSizeKb() - memInfo.getSwapFreeSizeKb());
13261                     proto.write(MemInfoDumpProto.TOTAL_ZRAM_SWAP_KB, memInfo.getSwapTotalSizeKb());
13262                 }
13263                 final long[] ksm = getKsmInfo();
13264                 proto.write(MemInfoDumpProto.KSM_SHARING_KB, ksm[KSM_SHARING]);
13265                 proto.write(MemInfoDumpProto.KSM_SHARED_KB, ksm[KSM_SHARED]);
13266                 proto.write(MemInfoDumpProto.KSM_UNSHARED_KB, ksm[KSM_UNSHARED]);
13267                 proto.write(MemInfoDumpProto.KSM_VOLATILE_KB, ksm[KSM_VOLATILE]);
13268 
13269                 proto.write(MemInfoDumpProto.TUNING_MB, ActivityManager.staticGetMemoryClass());
13270                 proto.write(MemInfoDumpProto.TUNING_LARGE_MB, ActivityManager.staticGetLargeMemoryClass());
13271                 proto.write(MemInfoDumpProto.OOM_KB,
13272                         mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024);
13273                 proto.write(MemInfoDumpProto.RESTORE_LIMIT_KB,
13274                         mProcessList.getCachedRestoreThresholdKb());
13275 
13276                 proto.write(MemInfoDumpProto.IS_LOW_RAM_DEVICE, ActivityManager.isLowRamDeviceStatic());
13277                 proto.write(MemInfoDumpProto.IS_HIGH_END_GFX, ActivityManager.isHighEndGfx());
13278             }
13279         }
13280 
13281         proto.flush();
13282     }
13283 
appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)13284     private void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss,
13285             long memtrack, String name) {
13286         sb.append("  ");
13287         sb.append(ProcessList.makeOomAdjString(oomAdj, false));
13288         sb.append(' ');
13289         sb.append(ProcessList.makeProcStateString(procState));
13290         sb.append(' ');
13291         ProcessList.appendRamKb(sb, pss);
13292         sb.append(": ");
13293         sb.append(name);
13294         if (memtrack > 0) {
13295             sb.append(" (");
13296             sb.append(stringifyKBSize(memtrack));
13297             sb.append(" memtrack)");
13298         }
13299     }
13300 
appendMemInfo(StringBuilder sb, ProcessMemInfo mi)13301     private void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) {
13302         appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name);
13303         sb.append(" (pid ");
13304         sb.append(mi.pid);
13305         sb.append(") ");
13306         sb.append(mi.adjType);
13307         sb.append('\n');
13308         if (mi.adjReason != null) {
13309             sb.append("                      ");
13310             sb.append(mi.adjReason);
13311             sb.append('\n');
13312         }
13313     }
13314 
reportMemUsage(ArrayList<ProcessMemInfo> memInfos)13315     void reportMemUsage(ArrayList<ProcessMemInfo> memInfos) {
13316         final SparseArray<ProcessMemInfo> infoMap = new SparseArray<>(memInfos.size());
13317         for (int i=0, N=memInfos.size(); i<N; i++) {
13318             ProcessMemInfo mi = memInfos.get(i);
13319             infoMap.put(mi.pid, mi);
13320         }
13321         updateCpuStatsNow();
13322         long[] memtrackTmp = new long[1];
13323         long[] swaptrackTmp = new long[2];
13324         final List<ProcessCpuTracker.Stats> stats;
13325         // Get a list of Stats that have vsize > 0
13326         synchronized (mProcessCpuTracker) {
13327             stats = mProcessCpuTracker.getStats((st) -> {
13328                 return st.vsize > 0;
13329             });
13330         }
13331         final int statsCount = stats.size();
13332         for (int i = 0; i < statsCount; i++) {
13333             ProcessCpuTracker.Stats st = stats.get(i);
13334             long pss = Debug.getPss(st.pid, swaptrackTmp, memtrackTmp);
13335             if (pss > 0) {
13336                 if (infoMap.indexOfKey(st.pid) < 0) {
13337                     ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid,
13338                             ProcessList.NATIVE_ADJ, -1, "native", null);
13339                     mi.pss = pss;
13340                     mi.swapPss = swaptrackTmp[1];
13341                     mi.memtrack = memtrackTmp[0];
13342                     memInfos.add(mi);
13343                 }
13344             }
13345         }
13346 
13347         long totalPss = 0;
13348         long totalSwapPss = 0;
13349         long totalMemtrack = 0;
13350         for (int i=0, N=memInfos.size(); i<N; i++) {
13351             ProcessMemInfo mi = memInfos.get(i);
13352             if (mi.pss == 0) {
13353                 mi.pss = Debug.getPss(mi.pid, swaptrackTmp, memtrackTmp);
13354                 mi.swapPss = swaptrackTmp[1];
13355                 mi.memtrack = memtrackTmp[0];
13356             }
13357             totalPss += mi.pss;
13358             totalSwapPss += mi.swapPss;
13359             totalMemtrack += mi.memtrack;
13360         }
13361         Collections.sort(memInfos, new Comparator<ProcessMemInfo>() {
13362             @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) {
13363                 if (lhs.oomAdj != rhs.oomAdj) {
13364                     return lhs.oomAdj < rhs.oomAdj ? -1 : 1;
13365                 }
13366                 if (lhs.pss != rhs.pss) {
13367                     return lhs.pss < rhs.pss ? 1 : -1;
13368                 }
13369                 return 0;
13370             }
13371         });
13372 
13373         StringBuilder tag = new StringBuilder(128);
13374         StringBuilder stack = new StringBuilder(128);
13375         tag.append("Low on memory -- ");
13376         appendMemBucket(tag, totalPss, "total", false);
13377         appendMemBucket(stack, totalPss, "total", true);
13378 
13379         StringBuilder fullNativeBuilder = new StringBuilder(1024);
13380         StringBuilder shortNativeBuilder = new StringBuilder(1024);
13381         StringBuilder fullJavaBuilder = new StringBuilder(1024);
13382 
13383         boolean firstLine = true;
13384         int lastOomAdj = Integer.MIN_VALUE;
13385         long extraNativeRam = 0;
13386         long extraNativeMemtrack = 0;
13387         long cachedPss = 0;
13388         for (int i=0, N=memInfos.size(); i<N; i++) {
13389             ProcessMemInfo mi = memInfos.get(i);
13390 
13391             if (mi.oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13392                 cachedPss += mi.pss;
13393             }
13394 
13395             if (mi.oomAdj != ProcessList.NATIVE_ADJ
13396                     && (mi.oomAdj < ProcessList.SERVICE_ADJ
13397                             || mi.oomAdj == ProcessList.HOME_APP_ADJ
13398                             || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) {
13399                 if (lastOomAdj != mi.oomAdj) {
13400                     lastOomAdj = mi.oomAdj;
13401                     if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13402                         tag.append(" / ");
13403                     }
13404                     if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13405                         if (firstLine) {
13406                             stack.append(":");
13407                             firstLine = false;
13408                         }
13409                         stack.append("\n\t at ");
13410                     } else {
13411                         stack.append("$");
13412                     }
13413                 } else {
13414                     tag.append(" ");
13415                     stack.append("$");
13416                 }
13417                 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
13418                     appendMemBucket(tag, mi.pss, mi.name, false);
13419                 }
13420                 appendMemBucket(stack, mi.pss, mi.name, true);
13421                 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ
13422                         && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) {
13423                     stack.append("(");
13424                     for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
13425                         if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) {
13426                             stack.append(DUMP_MEM_OOM_LABEL[k]);
13427                             stack.append(":");
13428                             stack.append(DUMP_MEM_OOM_ADJ[k]);
13429                         }
13430                     }
13431                     stack.append(")");
13432                 }
13433             }
13434 
13435             appendMemInfo(fullNativeBuilder, mi);
13436             if (mi.oomAdj == ProcessList.NATIVE_ADJ) {
13437                 // The short form only has native processes that are >= 512K.
13438                 if (mi.pss >= 512) {
13439                     appendMemInfo(shortNativeBuilder, mi);
13440                 } else {
13441                     extraNativeRam += mi.pss;
13442                     extraNativeMemtrack += mi.memtrack;
13443                 }
13444             } else {
13445                 // Short form has all other details, but if we have collected RAM
13446                 // from smaller native processes let's dump a summary of that.
13447                 if (extraNativeRam > 0) {
13448                     appendBasicMemEntry(shortNativeBuilder, ProcessList.NATIVE_ADJ,
13449                             -1, extraNativeRam, extraNativeMemtrack, "(Other native)");
13450                     shortNativeBuilder.append('\n');
13451                     extraNativeRam = 0;
13452                 }
13453                 appendMemInfo(fullJavaBuilder, mi);
13454             }
13455         }
13456 
13457         fullJavaBuilder.append("           ");
13458         ProcessList.appendRamKb(fullJavaBuilder, totalPss);
13459         fullJavaBuilder.append(": TOTAL");
13460         if (totalMemtrack > 0) {
13461             fullJavaBuilder.append(" (");
13462             fullJavaBuilder.append(stringifyKBSize(totalMemtrack));
13463             fullJavaBuilder.append(" memtrack)");
13464         } else {
13465         }
13466         fullJavaBuilder.append("\n");
13467 
13468         MemInfoReader memInfo = new MemInfoReader();
13469         memInfo.readMemInfo();
13470         final long[] infos = memInfo.getRawInfo();
13471 
13472         StringBuilder memInfoBuilder = new StringBuilder(1024);
13473         Debug.getMemInfo(infos);
13474         memInfoBuilder.append("  MemInfo: ");
13475         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SLAB])).append(" slab, ");
13476         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SHMEM])).append(" shmem, ");
13477         memInfoBuilder.append(stringifyKBSize(
13478                                   infos[Debug.MEMINFO_VM_ALLOC_USED])).append(" vm alloc, ");
13479         memInfoBuilder.append(stringifyKBSize(
13480                                   infos[Debug.MEMINFO_PAGE_TABLES])).append(" page tables ");
13481         memInfoBuilder.append(stringifyKBSize(
13482                                   infos[Debug.MEMINFO_KERNEL_STACK])).append(" kernel stack\n");
13483         memInfoBuilder.append("           ");
13484         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_BUFFERS])).append(" buffers, ");
13485         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_CACHED])).append(" cached, ");
13486         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_MAPPED])).append(" mapped, ");
13487         memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_FREE])).append(" free\n");
13488         if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) {
13489             memInfoBuilder.append("  ZRAM: ");
13490             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_ZRAM_TOTAL]));
13491             memInfoBuilder.append(" RAM, ");
13492             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_TOTAL]));
13493             memInfoBuilder.append(" swap total, ");
13494             memInfoBuilder.append(stringifyKBSize(infos[Debug.MEMINFO_SWAP_FREE]));
13495             memInfoBuilder.append(" swap free\n");
13496         }
13497         final long[] ksm = getKsmInfo();
13498         if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0
13499                 || ksm[KSM_VOLATILE] != 0) {
13500             memInfoBuilder.append("  KSM: ");
13501             memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARING]));
13502             memInfoBuilder.append(" saved from shared ");
13503             memInfoBuilder.append(stringifyKBSize(ksm[KSM_SHARED]));
13504             memInfoBuilder.append("\n       ");
13505             memInfoBuilder.append(stringifyKBSize(ksm[KSM_UNSHARED]));
13506             memInfoBuilder.append(" unshared; ");
13507             memInfoBuilder.append(stringifyKBSize(ksm[KSM_VOLATILE]));
13508             memInfoBuilder.append(" volatile\n");
13509         }
13510         memInfoBuilder.append("  Free RAM: ");
13511         memInfoBuilder.append(stringifyKBSize(cachedPss + memInfo.getCachedSizeKb()
13512                 + memInfo.getFreeSizeKb()));
13513         memInfoBuilder.append("\n");
13514         memInfoBuilder.append("  Used RAM: ");
13515         memInfoBuilder.append(stringifyKBSize(
13516                                   totalPss - cachedPss + memInfo.getKernelUsedSizeKb()));
13517         memInfoBuilder.append("\n");
13518         memInfoBuilder.append("  Lost RAM: ");
13519         memInfoBuilder.append(stringifyKBSize(memInfo.getTotalSizeKb()
13520                 - (totalPss - totalSwapPss) - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
13521                 - memInfo.getKernelUsedSizeKb() - memInfo.getZramTotalSizeKb()));
13522         memInfoBuilder.append("\n");
13523         Slog.i(TAG, "Low on memory:");
13524         Slog.i(TAG, shortNativeBuilder.toString());
13525         Slog.i(TAG, fullJavaBuilder.toString());
13526         Slog.i(TAG, memInfoBuilder.toString());
13527 
13528         StringBuilder dropBuilder = new StringBuilder(1024);
13529         /*
13530         StringWriter oomSw = new StringWriter();
13531         PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256);
13532         StringWriter catSw = new StringWriter();
13533         PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
13534         String[] emptyArgs = new String[] { };
13535         dumpApplicationMemoryUsage(null, oomPw, "  ", emptyArgs, true, catPw);
13536         oomPw.flush();
13537         String oomString = oomSw.toString();
13538         */
13539         dropBuilder.append("Low on memory:");
13540         dropBuilder.append(stack);
13541         dropBuilder.append('\n');
13542         dropBuilder.append(fullNativeBuilder);
13543         dropBuilder.append(fullJavaBuilder);
13544         dropBuilder.append('\n');
13545         dropBuilder.append(memInfoBuilder);
13546         dropBuilder.append('\n');
13547         /*
13548         dropBuilder.append(oomString);
13549         dropBuilder.append('\n');
13550         */
13551         StringWriter catSw = new StringWriter();
13552         synchronized (ActivityManagerService.this) {
13553             PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
13554             String[] emptyArgs = new String[] { };
13555             catPw.println();
13556             dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null, -1);
13557             catPw.println();
13558             mServices.newServiceDumperLocked(null, catPw, emptyArgs, 0,
13559                     false, null).dumpLocked();
13560             catPw.println();
13561             mAtmInternal.dump(DUMP_ACTIVITIES_CMD, null, catPw, emptyArgs, 0, false, false, null);
13562             catPw.flush();
13563         }
13564         dropBuilder.append(catSw.toString());
13565         StatsLog.write(StatsLog.LOW_MEM_REPORTED);
13566         addErrorToDropBox("lowmem", null, "system_server", null,
13567                 null, null, tag.toString(), dropBuilder.toString(), null, null);
13568         //Slog.i(TAG, "Sent to dropbox:");
13569         //Slog.i(TAG, dropBuilder.toString());
13570         synchronized (ActivityManagerService.this) {
13571             long now = SystemClock.uptimeMillis();
13572             if (mLastMemUsageReportTime < now) {
13573                 mLastMemUsageReportTime = now;
13574             }
13575         }
13576     }
13577 
13578     /**
13579      * Searches array of arguments for the specified string
13580      * @param args array of argument strings
13581      * @param value value to search for
13582      * @return true if the value is contained in the array
13583      */
scanArgs(String[] args, String value)13584     private static boolean scanArgs(String[] args, String value) {
13585         if (args != null) {
13586             for (String arg : args) {
13587                 if (value.equals(arg)) {
13588                     return true;
13589                 }
13590             }
13591         }
13592         return false;
13593     }
13594 
removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, boolean always)13595     private final boolean removeDyingProviderLocked(ProcessRecord proc,
13596             ContentProviderRecord cpr, boolean always) {
13597         final boolean inLaunching = mLaunchingProviders.contains(cpr);
13598 
13599         if (!inLaunching || always) {
13600             synchronized (cpr) {
13601                 cpr.launchingApp = null;
13602                 cpr.notifyAll();
13603             }
13604             mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
13605             String names[] = cpr.info.authority.split(";");
13606             for (int j = 0; j < names.length; j++) {
13607                 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
13608             }
13609         }
13610 
13611         for (int i = cpr.connections.size() - 1; i >= 0; i--) {
13612             ContentProviderConnection conn = cpr.connections.get(i);
13613             if (conn.waiting) {
13614                 // If this connection is waiting for the provider, then we don't
13615                 // need to mess with its process unless we are always removing
13616                 // or for some reason the provider is not currently launching.
13617                 if (inLaunching && !always) {
13618                     continue;
13619                 }
13620             }
13621             ProcessRecord capp = conn.client;
13622             conn.dead = true;
13623             if (conn.stableCount > 0) {
13624                 if (!capp.isPersistent() && capp.thread != null
13625                         && capp.pid != 0
13626                         && capp.pid != MY_PID) {
13627                     capp.kill("depends on provider "
13628                             + cpr.name.flattenToShortString()
13629                             + " in dying proc " + (proc != null ? proc.processName : "??")
13630                             + " (adj " + (proc != null ? proc.setAdj : "??") + ")", true);
13631                 }
13632             } else if (capp.thread != null && conn.provider.provider != null) {
13633                 try {
13634                     capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
13635                 } catch (RemoteException e) {
13636                 }
13637                 // In the protocol here, we don't expect the client to correctly
13638                 // clean up this connection, we'll just remove it.
13639                 cpr.connections.remove(i);
13640                 if (conn.client.conProviders.remove(conn)) {
13641                     stopAssociationLocked(capp.uid, capp.processName, cpr.uid,
13642                             cpr.appInfo.longVersionCode, cpr.name, cpr.info.processName);
13643                 }
13644             }
13645         }
13646 
13647         if (inLaunching && always) {
13648             mLaunchingProviders.remove(cpr);
13649         }
13650         return inLaunching;
13651     }
13652 
13653     /**
13654      * Main code for cleaning up a process when it has gone away.  This is
13655      * called both as a result of the process dying, or directly when stopping
13656      * a process when running in single process mode.
13657      *
13658      * @return Returns true if the given process has been restarted, so the
13659      * app that was passed in must remain on the process lists.
13660      */
13661     @GuardedBy("this")
cleanUpApplicationRecordLocked(ProcessRecord app, boolean restarting, boolean allowRestart, int index, boolean replacingPid)13662     final boolean cleanUpApplicationRecordLocked(ProcessRecord app,
13663             boolean restarting, boolean allowRestart, int index, boolean replacingPid) {
13664         if (index >= 0) {
13665             removeLruProcessLocked(app);
13666             ProcessList.remove(app.pid);
13667         }
13668 
13669         mProcessesToGc.remove(app);
13670         mPendingPssProcesses.remove(app);
13671         ProcessList.abortNextPssTime(app.procStateMemTracker);
13672 
13673         // Dismiss any open dialogs.
13674         if (app.crashDialog != null && !app.forceCrashReport) {
13675             app.crashDialog.dismiss();
13676             app.crashDialog = null;
13677         }
13678         if (app.anrDialog != null) {
13679             app.anrDialog.dismiss();
13680             app.anrDialog = null;
13681         }
13682         if (app.waitDialog != null) {
13683             app.waitDialog.dismiss();
13684             app.waitDialog = null;
13685         }
13686 
13687         app.setCrashing(false);
13688         app.setNotResponding(false);
13689 
13690         app.resetPackageList(mProcessStats);
13691         app.unlinkDeathRecipient();
13692         app.makeInactive(mProcessStats);
13693         app.waitingToKill = null;
13694         app.forcingToImportant = null;
13695         updateProcessForegroundLocked(app, false, 0, false);
13696         app.setHasForegroundActivities(false);
13697         app.hasShownUi = false;
13698         app.treatLikeActivity = false;
13699         app.hasAboveClient = false;
13700         app.setHasClientActivities(false);
13701 
13702         mServices.killServicesLocked(app, allowRestart);
13703 
13704         boolean restart = false;
13705 
13706         // Remove published content providers.
13707         for (int i = app.pubProviders.size() - 1; i >= 0; i--) {
13708             ContentProviderRecord cpr = app.pubProviders.valueAt(i);
13709             final boolean always = app.bad || !allowRestart;
13710             boolean inLaunching = removeDyingProviderLocked(app, cpr, always);
13711             if ((inLaunching || always) && cpr.hasConnectionOrHandle()) {
13712                 // We left the provider in the launching list, need to
13713                 // restart it.
13714                 restart = true;
13715             }
13716 
13717             cpr.provider = null;
13718             cpr.setProcess(null);
13719         }
13720         app.pubProviders.clear();
13721 
13722         // Take care of any launching providers waiting for this process.
13723         if (cleanupAppInLaunchingProvidersLocked(app, false)) {
13724             restart = true;
13725         }
13726 
13727         // Unregister from connected content providers.
13728         if (!app.conProviders.isEmpty()) {
13729             for (int i = app.conProviders.size() - 1; i >= 0; i--) {
13730                 ContentProviderConnection conn = app.conProviders.get(i);
13731                 conn.provider.connections.remove(conn);
13732                 stopAssociationLocked(app.uid, app.processName, conn.provider.uid,
13733                         conn.provider.appInfo.longVersionCode, conn.provider.name,
13734                         conn.provider.info.processName);
13735             }
13736             app.conProviders.clear();
13737         }
13738 
13739         // At this point there may be remaining entries in mLaunchingProviders
13740         // where we were the only one waiting, so they are no longer of use.
13741         // Look for these and clean up if found.
13742         // XXX Commented out for now.  Trying to figure out a way to reproduce
13743         // the actual situation to identify what is actually going on.
13744         if (false) {
13745             for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
13746                 ContentProviderRecord cpr = mLaunchingProviders.get(i);
13747                 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
13748                     synchronized (cpr) {
13749                         cpr.launchingApp = null;
13750                         cpr.notifyAll();
13751                     }
13752                 }
13753             }
13754         }
13755 
13756         skipCurrentReceiverLocked(app);
13757 
13758         // Unregister any receivers.
13759         for (int i = app.receivers.size() - 1; i >= 0; i--) {
13760             removeReceiverLocked(app.receivers.valueAt(i));
13761         }
13762         app.receivers.clear();
13763 
13764         // If the app is undergoing backup, tell the backup manager about it
13765         final BackupRecord backupTarget = mBackupTargets.get(app.userId);
13766         if (backupTarget != null && app.pid == backupTarget.app.pid) {
13767             if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App "
13768                     + backupTarget.appInfo + " died during backup");
13769             mHandler.post(new Runnable() {
13770                 @Override
13771                 public void run(){
13772                     try {
13773                         IBackupManager bm = IBackupManager.Stub.asInterface(
13774                                 ServiceManager.getService(Context.BACKUP_SERVICE));
13775                         bm.agentDisconnectedForUser(app.userId, app.info.packageName);
13776                     } catch (RemoteException e) {
13777                         // can't happen; backup manager is local
13778                     }
13779                 }
13780             });
13781         }
13782 
13783         for (int i = mPendingProcessChanges.size() - 1; i >= 0; i--) {
13784             ProcessChangeItem item = mPendingProcessChanges.get(i);
13785             if (app.pid > 0 && item.pid == app.pid) {
13786                 mPendingProcessChanges.remove(i);
13787                 mAvailProcessChanges.add(item);
13788             }
13789         }
13790         mUiHandler.obtainMessage(DISPATCH_PROCESS_DIED_UI_MSG, app.pid, app.info.uid,
13791                 null).sendToTarget();
13792 
13793         // If the caller is restarting this app, then leave it in its
13794         // current lists and let the caller take care of it.
13795         if (restarting) {
13796             return false;
13797         }
13798 
13799         if (!app.isPersistent() || app.isolated) {
13800             if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP,
13801                     "Removing non-persistent process during cleanup: " + app);
13802             if (!replacingPid) {
13803                 mProcessList.removeProcessNameLocked(app.processName, app.uid, app);
13804             }
13805             mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController());
13806         } else if (!app.removed) {
13807             // This app is persistent, so we need to keep its record around.
13808             // If it is not already on the pending app list, add it there
13809             // and start a new process for it.
13810             if (mPersistentStartingProcesses.indexOf(app) < 0) {
13811                 mPersistentStartingProcesses.add(app);
13812                 restart = true;
13813             }
13814         }
13815         if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(
13816                 TAG_CLEANUP, "Clean-up removing on hold: " + app);
13817         mProcessesOnHold.remove(app);
13818 
13819         mAtmInternal.onCleanUpApplicationRecord(app.getWindowProcessController());
13820 
13821         if (restart && !app.isolated) {
13822             // We have components that still need to be running in the
13823             // process, so re-launch it.
13824             if (index < 0) {
13825                 ProcessList.remove(app.pid);
13826             }
13827             mProcessList.addProcessNameLocked(app);
13828             app.pendingStart = false;
13829             mProcessList.startProcessLocked(app,
13830                     new HostingRecord("restart", app.processName));
13831             return true;
13832         } else if (app.pid > 0 && app.pid != MY_PID) {
13833             // Goodbye!
13834             mPidsSelfLocked.remove(app);
13835             mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
13836             mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
13837             if (app.isolated) {
13838                 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
13839             }
13840             app.setPid(0);
13841         }
13842         return false;
13843     }
13844 
checkAppInLaunchingProvidersLocked(ProcessRecord app)13845     boolean checkAppInLaunchingProvidersLocked(ProcessRecord app) {
13846         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
13847             ContentProviderRecord cpr = mLaunchingProviders.get(i);
13848             if (cpr.launchingApp == app) {
13849                 return true;
13850             }
13851         }
13852         return false;
13853     }
13854 
cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad)13855     boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
13856         // Look through the content providers we are waiting to have launched,
13857         // and if any run in this process then either schedule a restart of
13858         // the process or kill the client waiting for it if this process has
13859         // gone bad.
13860         boolean restart = false;
13861         for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) {
13862             ContentProviderRecord cpr = mLaunchingProviders.get(i);
13863             if (cpr.launchingApp == app) {
13864                 if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) {
13865                     restart = true;
13866                 } else {
13867                     removeDyingProviderLocked(app, cpr, true);
13868                 }
13869             }
13870         }
13871         return restart;
13872     }
13873 
13874     // =========================================================
13875     // SERVICES
13876     // =========================================================
13877 
13878     @Override
getServices(int maxNum, int flags)13879     public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, int flags) {
13880         enforceNotIsolatedCaller("getServices");
13881 
13882         final int callingUid = Binder.getCallingUid();
13883         final boolean canInteractAcrossUsers = (ActivityManager.checkUidPermission(
13884             INTERACT_ACROSS_USERS_FULL, callingUid) == PERMISSION_GRANTED);
13885         final boolean allowed = mAtmInternal.isGetTasksAllowed("getServices",
13886                 Binder.getCallingPid(), callingUid);
13887         synchronized (this) {
13888             return mServices.getRunningServiceInfoLocked(maxNum, flags, callingUid,
13889                 allowed, canInteractAcrossUsers);
13890         }
13891     }
13892 
13893     @Override
getRunningServiceControlPanel(ComponentName name)13894     public PendingIntent getRunningServiceControlPanel(ComponentName name) {
13895         enforceNotIsolatedCaller("getRunningServiceControlPanel");
13896         synchronized (this) {
13897             return mServices.getRunningServiceControlPanelLocked(name);
13898         }
13899     }
13900 
13901     @Override
startService(IApplicationThread caller, Intent service, String resolvedType, boolean requireForeground, String callingPackage, int userId)13902     public ComponentName startService(IApplicationThread caller, Intent service,
13903             String resolvedType, boolean requireForeground, String callingPackage, int userId)
13904             throws TransactionTooLargeException {
13905         enforceNotIsolatedCaller("startService");
13906         // Refuse possible leaked file descriptors
13907         if (service != null && service.hasFileDescriptors() == true) {
13908             throw new IllegalArgumentException("File descriptors passed in Intent");
13909         }
13910 
13911         if (callingPackage == null) {
13912             throw new IllegalArgumentException("callingPackage cannot be null");
13913         }
13914 
13915         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
13916                 "*** startService: " + service + " type=" + resolvedType + " fg=" + requireForeground);
13917         synchronized(this) {
13918             final int callingPid = Binder.getCallingPid();
13919             final int callingUid = Binder.getCallingUid();
13920             final long origId = Binder.clearCallingIdentity();
13921             ComponentName res;
13922             try {
13923                 res = mServices.startServiceLocked(caller, service,
13924                         resolvedType, callingPid, callingUid,
13925                         requireForeground, callingPackage, userId);
13926             } finally {
13927                 Binder.restoreCallingIdentity(origId);
13928             }
13929             return res;
13930         }
13931     }
13932 
13933     @Override
stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)13934     public int stopService(IApplicationThread caller, Intent service,
13935             String resolvedType, int userId) {
13936         enforceNotIsolatedCaller("stopService");
13937         // Refuse possible leaked file descriptors
13938         if (service != null && service.hasFileDescriptors() == true) {
13939             throw new IllegalArgumentException("File descriptors passed in Intent");
13940         }
13941 
13942         synchronized(this) {
13943             return mServices.stopServiceLocked(caller, service, resolvedType, userId);
13944         }
13945     }
13946 
13947     @Override
peekService(Intent service, String resolvedType, String callingPackage)13948     public IBinder peekService(Intent service, String resolvedType, String callingPackage) {
13949         enforceNotIsolatedCaller("peekService");
13950         // Refuse possible leaked file descriptors
13951         if (service != null && service.hasFileDescriptors() == true) {
13952             throw new IllegalArgumentException("File descriptors passed in Intent");
13953         }
13954 
13955         if (callingPackage == null) {
13956             throw new IllegalArgumentException("callingPackage cannot be null");
13957         }
13958 
13959         synchronized(this) {
13960             return mServices.peekServiceLocked(service, resolvedType, callingPackage);
13961         }
13962     }
13963 
13964     @Override
stopServiceToken(ComponentName className, IBinder token, int startId)13965     public boolean stopServiceToken(ComponentName className, IBinder token,
13966             int startId) {
13967         synchronized(this) {
13968             return mServices.stopServiceTokenLocked(className, token, startId);
13969         }
13970     }
13971 
13972     @Override
setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)13973     public void setServiceForeground(ComponentName className, IBinder token,
13974             int id, Notification notification, int flags, int foregroundServiceType) {
13975         synchronized(this) {
13976             mServices.setServiceForegroundLocked(className, token, id, notification, flags,
13977                     foregroundServiceType);
13978         }
13979     }
13980 
13981     @Override
getForegroundServiceType(ComponentName className, IBinder token)13982     public int getForegroundServiceType(ComponentName className, IBinder token) {
13983         synchronized (this) {
13984             return mServices.getForegroundServiceTypeLocked(className, token);
13985         }
13986     }
13987 
13988     @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)13989     public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
13990             boolean requireFull, String name, String callerPackage) {
13991         return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
13992                 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
13993     }
13994 
isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)13995     boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
13996             String className, int flags) {
13997         boolean result = false;
13998         // For apps that don't have pre-defined UIDs, check for permission
13999         if (UserHandle.getAppId(aInfo.uid) >= FIRST_APPLICATION_UID) {
14000             if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
14001                 if (ActivityManager.checkUidPermission(
14002                         INTERACT_ACROSS_USERS,
14003                         aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
14004                     ComponentName comp = new ComponentName(aInfo.packageName, className);
14005                     String msg = "Permission Denial: Component " + comp.flattenToShortString()
14006                             + " requests FLAG_SINGLE_USER, but app does not hold "
14007                             + INTERACT_ACROSS_USERS;
14008                     Slog.w(TAG, msg);
14009                     throw new SecurityException(msg);
14010                 }
14011                 // Permission passed
14012                 result = true;
14013             }
14014         } else if ("system".equals(componentProcessName)) {
14015             result = true;
14016         } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
14017             // Phone app and persistent apps are allowed to export singleuser providers.
14018             result = UserHandle.isSameApp(aInfo.uid, PHONE_UID)
14019                     || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
14020         }
14021         if (DEBUG_MU) Slog.v(TAG_MU,
14022                 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x"
14023                 + Integer.toHexString(flags) + ") = " + result);
14024         return result;
14025     }
14026 
14027     /**
14028      * Checks to see if the caller is in the same app as the singleton
14029      * component, or the component is in a special app. It allows special apps
14030      * to export singleton components but prevents exporting singleton
14031      * components for regular apps.
14032      */
isValidSingletonCall(int callingUid, int componentUid)14033     boolean isValidSingletonCall(int callingUid, int componentUid) {
14034         int componentAppId = UserHandle.getAppId(componentUid);
14035         return UserHandle.isSameApp(callingUid, componentUid)
14036                 || componentAppId == SYSTEM_UID
14037                 || componentAppId == PHONE_UID
14038                 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
14039                         == PackageManager.PERMISSION_GRANTED;
14040     }
14041 
bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)14042     public int bindService(IApplicationThread caller, IBinder token, Intent service,
14043             String resolvedType, IServiceConnection connection, int flags,
14044             String callingPackage, int userId) throws TransactionTooLargeException {
14045         return bindIsolatedService(caller, token, service, resolvedType, connection, flags,
14046                 null, callingPackage, userId);
14047     }
14048 
bindIsolatedService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String instanceName, String callingPackage, int userId)14049     public int bindIsolatedService(IApplicationThread caller, IBinder token, Intent service,
14050             String resolvedType, IServiceConnection connection, int flags, String instanceName,
14051             String callingPackage, int userId) throws TransactionTooLargeException {
14052         enforceNotIsolatedCaller("bindService");
14053 
14054         // Refuse possible leaked file descriptors
14055         if (service != null && service.hasFileDescriptors() == true) {
14056             throw new IllegalArgumentException("File descriptors passed in Intent");
14057         }
14058 
14059         if (callingPackage == null) {
14060             throw new IllegalArgumentException("callingPackage cannot be null");
14061         }
14062 
14063         // Ensure that instanceName, which is caller provided, does not contain
14064         // unusual characters.
14065         if (instanceName != null) {
14066             for (int i = 0; i < instanceName.length(); ++i) {
14067                 char c = instanceName.charAt(i);
14068                 if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
14069                             || (c >= '0' && c <= '9') || c == '_' || c == '.')) {
14070                     throw new IllegalArgumentException("Illegal instanceName");
14071                 }
14072             }
14073         }
14074 
14075         synchronized(this) {
14076             return mServices.bindServiceLocked(caller, token, service,
14077                     resolvedType, connection, flags, instanceName, callingPackage, userId);
14078         }
14079     }
14080 
updateServiceGroup(IServiceConnection connection, int group, int importance)14081     public void updateServiceGroup(IServiceConnection connection, int group, int importance) {
14082         synchronized (this) {
14083             mServices.updateServiceGroupLocked(connection, group, importance);
14084         }
14085     }
14086 
unbindService(IServiceConnection connection)14087     public boolean unbindService(IServiceConnection connection) {
14088         synchronized (this) {
14089             return mServices.unbindServiceLocked(connection);
14090         }
14091     }
14092 
publishService(IBinder token, Intent intent, IBinder service)14093     public void publishService(IBinder token, Intent intent, IBinder service) {
14094         // Refuse possible leaked file descriptors
14095         if (intent != null && intent.hasFileDescriptors() == true) {
14096             throw new IllegalArgumentException("File descriptors passed in Intent");
14097         }
14098 
14099         synchronized(this) {
14100             if (!(token instanceof ServiceRecord)) {
14101                 throw new IllegalArgumentException("Invalid service token");
14102             }
14103             mServices.publishServiceLocked((ServiceRecord)token, intent, service);
14104         }
14105     }
14106 
unbindFinished(IBinder token, Intent intent, boolean doRebind)14107     public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
14108         // Refuse possible leaked file descriptors
14109         if (intent != null && intent.hasFileDescriptors() == true) {
14110             throw new IllegalArgumentException("File descriptors passed in Intent");
14111         }
14112 
14113         synchronized(this) {
14114             mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
14115         }
14116     }
14117 
serviceDoneExecuting(IBinder token, int type, int startId, int res)14118     public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
14119         synchronized(this) {
14120             if (!(token instanceof ServiceRecord)) {
14121                 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token);
14122                 throw new IllegalArgumentException("Invalid service token");
14123             }
14124             mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
14125         }
14126     }
14127 
14128     // =========================================================
14129     // BACKUP AND RESTORE
14130     // =========================================================
14131 
14132     // Cause the target app to be launched if necessary and its backup agent
14133     // instantiated.  The backup agent will invoke backupAgentCreated() on the
14134     // activity manager to announce its creation.
bindBackupAgent(String packageName, int backupMode, int targetUserId)14135     public boolean bindBackupAgent(String packageName, int backupMode, int targetUserId) {
14136         if (DEBUG_BACKUP) {
14137             Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode
14138                     + " targetUserId=" + targetUserId + " callingUid = " + Binder.getCallingUid()
14139                     + " uid = " + Process.myUid());
14140         }
14141         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
14142 
14143         // The instantiatedUserId is the user of the process the backup agent is started in. This is
14144         // different from the targetUserId which is the user whose data is to be backed up or
14145         // restored. This distinction is important for system-process packages that live in the
14146         // system user's process but backup/restore data for non-system users.
14147         // TODO (b/123688746): Handle all system-process packages with singleton check.
14148         final int instantiatedUserId =
14149                 PLATFORM_PACKAGE_NAME.equals(packageName) ? UserHandle.USER_SYSTEM : targetUserId;
14150 
14151         IPackageManager pm = AppGlobals.getPackageManager();
14152         ApplicationInfo app = null;
14153         try {
14154             app = pm.getApplicationInfo(packageName, STOCK_PM_FLAGS, instantiatedUserId);
14155         } catch (RemoteException e) {
14156             // can't happen; package manager is process-local
14157         }
14158         if (app == null) {
14159             Slog.w(TAG, "Unable to bind backup agent for " + packageName);
14160             return false;
14161         }
14162 
14163         int oldBackupUid;
14164         int newBackupUid;
14165 
14166         synchronized(this) {
14167             // !!! TODO: currently no check here that we're already bound
14168             // Backup agent is now in use, its package can't be stopped.
14169             try {
14170                 AppGlobals.getPackageManager().setPackageStoppedState(
14171                         app.packageName, false, UserHandle.getUserId(app.uid));
14172             } catch (RemoteException e) {
14173             } catch (IllegalArgumentException e) {
14174                 Slog.w(TAG, "Failed trying to unstop package "
14175                         + app.packageName + ": " + e);
14176             }
14177 
14178             BackupRecord r = new BackupRecord(app, backupMode, targetUserId);
14179             ComponentName hostingName =
14180                     (backupMode == ApplicationThreadConstants.BACKUP_MODE_INCREMENTAL)
14181                             ? new ComponentName(app.packageName, app.backupAgentName)
14182                             : new ComponentName("android", "FullBackupAgent");
14183 
14184             // startProcessLocked() returns existing proc's record if it's already running
14185             ProcessRecord proc = startProcessLocked(app.processName, app,
14186                     false, 0,
14187                     new HostingRecord("backup", hostingName),
14188                     false, false, false);
14189             if (proc == null) {
14190                 Slog.e(TAG, "Unable to start backup agent process " + r);
14191                 return false;
14192             }
14193 
14194             // If the app is a regular app (uid >= 10000) and not the system server or phone
14195             // process, etc, then mark it as being in full backup so that certain calls to the
14196             // process can be blocked. This is not reset to false anywhere because we kill the
14197             // process after the full backup is done and the ProcessRecord will vaporize anyway.
14198             if (UserHandle.isApp(app.uid) &&
14199                     backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL) {
14200                 proc.inFullBackup = true;
14201             }
14202             r.app = proc;
14203             final BackupRecord backupTarget = mBackupTargets.get(targetUserId);
14204             oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
14205             newBackupUid = proc.inFullBackup ? r.appInfo.uid : -1;
14206             mBackupTargets.put(targetUserId, r);
14207 
14208             // Try not to kill the process during backup
14209             updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE);
14210 
14211             // If the process is already attached, schedule the creation of the backup agent now.
14212             // If it is not yet live, this will be done when it attaches to the framework.
14213             if (proc.thread != null) {
14214                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc);
14215                 try {
14216                     proc.thread.scheduleCreateBackupAgent(app,
14217                             compatibilityInfoForPackage(app), backupMode, targetUserId);
14218                 } catch (RemoteException e) {
14219                     // Will time out on the backup manager side
14220                 }
14221             } else {
14222                 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach");
14223             }
14224             // Invariants: at this point, the target app process exists and the application
14225             // is either already running or in the process of coming up.  mBackupTarget and
14226             // mBackupAppName describe the app, so that when it binds back to the AM we
14227             // know that it's scheduled for a backup-agent operation.
14228         }
14229 
14230         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
14231         if (oldBackupUid != -1) {
14232             js.removeBackingUpUid(oldBackupUid);
14233         }
14234         if (newBackupUid != -1) {
14235             js.addBackingUpUid(newBackupUid);
14236         }
14237 
14238         return true;
14239     }
14240 
clearPendingBackup(int userId)14241     private void clearPendingBackup(int userId) {
14242         if (DEBUG_BACKUP) {
14243             Slog.v(TAG_BACKUP, "clearPendingBackup: userId = " + userId + " callingUid = "
14244                     + Binder.getCallingUid() + " uid = " + Process.myUid());
14245         }
14246 
14247         synchronized (this) {
14248             mBackupTargets.delete(userId);
14249         }
14250 
14251         JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
14252         js.clearAllBackingUpUids();
14253     }
14254 
14255     // A backup agent has just come up
14256     @Override
backupAgentCreated(String agentPackageName, IBinder agent, int userId)14257     public void backupAgentCreated(String agentPackageName, IBinder agent, int userId) {
14258         // Resolve the target user id and enforce permissions.
14259         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
14260                 userId, /* allowAll */ false, ALLOW_FULL_ONLY, "backupAgentCreated", null);
14261         if (DEBUG_BACKUP) {
14262             Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName + " = " + agent
14263                     + " callingUserId = " + UserHandle.getCallingUserId() + " userId = " + userId
14264                     + " callingUid = " + Binder.getCallingUid() + " uid = " + Process.myUid());
14265         }
14266 
14267         synchronized(this) {
14268             final BackupRecord backupTarget = mBackupTargets.get(userId);
14269             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
14270             if (!agentPackageName.equals(backupAppName)) {
14271                 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
14272                 return;
14273             }
14274         }
14275 
14276         long oldIdent = Binder.clearCallingIdentity();
14277         try {
14278             IBackupManager bm = IBackupManager.Stub.asInterface(
14279                     ServiceManager.getService(Context.BACKUP_SERVICE));
14280             bm.agentConnectedForUser(userId, agentPackageName, agent);
14281         } catch (RemoteException e) {
14282             // can't happen; the backup manager service is local
14283         } catch (Exception e) {
14284             Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
14285             e.printStackTrace();
14286         } finally {
14287             Binder.restoreCallingIdentity(oldIdent);
14288         }
14289     }
14290 
14291     // done with this agent
unbindBackupAgent(ApplicationInfo appInfo)14292     public void unbindBackupAgent(ApplicationInfo appInfo) {
14293         if (DEBUG_BACKUP) {
14294             Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo + " appInfo.uid = "
14295                     + appInfo.uid + " callingUid = " + Binder.getCallingUid() + " uid = "
14296                     + Process.myUid());
14297         }
14298 
14299         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "unbindBackupAgent");
14300         if (appInfo == null) {
14301             Slog.w(TAG, "unbind backup agent for null app");
14302             return;
14303         }
14304 
14305         int oldBackupUid;
14306 
14307         final int userId = UserHandle.getUserId(appInfo.uid);
14308         synchronized(this) {
14309             final BackupRecord backupTarget = mBackupTargets.get(userId);
14310             String backupAppName = backupTarget == null ? null : backupTarget.appInfo.packageName;
14311             try {
14312                 if (backupAppName == null) {
14313                     Slog.w(TAG, "Unbinding backup agent with no active backup");
14314                     return;
14315                 }
14316 
14317                 if (!backupAppName.equals(appInfo.packageName)) {
14318                     Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
14319                     return;
14320                 }
14321 
14322                 // Not backing this app up any more; reset its OOM adjustment
14323                 final ProcessRecord proc = backupTarget.app;
14324                 updateOomAdjLocked(proc, true, OomAdjuster.OOM_ADJ_REASON_NONE);
14325                 proc.inFullBackup = false;
14326 
14327                 oldBackupUid = backupTarget != null ? backupTarget.appInfo.uid : -1;
14328 
14329                 // If the app crashed during backup, 'thread' will be null here
14330                 if (proc.thread != null) {
14331                     try {
14332                         proc.thread.scheduleDestroyBackupAgent(appInfo,
14333                                 compatibilityInfoForPackage(appInfo), userId);
14334                     } catch (Exception e) {
14335                         Slog.e(TAG, "Exception when unbinding backup agent:");
14336                         e.printStackTrace();
14337                     }
14338                 }
14339             } finally {
14340                 mBackupTargets.delete(userId);
14341             }
14342         }
14343 
14344         if (oldBackupUid != -1) {
14345             JobSchedulerInternal js = LocalServices.getService(JobSchedulerInternal.class);
14346             js.removeBackingUpUid(oldBackupUid);
14347         }
14348     }
14349 
14350     // =========================================================
14351     // BROADCASTS
14352     // =========================================================
14353 
isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid)14354     private boolean isInstantApp(ProcessRecord record, @Nullable String callerPackage, int uid) {
14355         if (UserHandle.getAppId(uid) < FIRST_APPLICATION_UID) {
14356             return false;
14357         }
14358         // Easy case -- we have the app's ProcessRecord.
14359         if (record != null) {
14360             return record.info.isInstantApp();
14361         }
14362         // Otherwise check with PackageManager.
14363         IPackageManager pm = AppGlobals.getPackageManager();
14364         try {
14365             if (callerPackage == null) {
14366                 final String[] packageNames = pm.getPackagesForUid(uid);
14367                 if (packageNames == null || packageNames.length == 0) {
14368                     throw new IllegalArgumentException("Unable to determine caller package name");
14369                 }
14370                 // Instant Apps can't use shared uids, so its safe to only check the first package.
14371                 callerPackage = packageNames[0];
14372             }
14373             mAppOpsService.checkPackage(uid, callerPackage);
14374             return pm.isInstantApp(callerPackage, UserHandle.getUserId(uid));
14375         } catch (RemoteException e) {
14376             Slog.e(TAG, "Error looking up if " + callerPackage + " is an instant app.", e);
14377             return true;
14378         }
14379     }
14380 
isPendingBroadcastProcessLocked(int pid)14381     boolean isPendingBroadcastProcessLocked(int pid) {
14382         return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
14383                 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
14384                 || mOffloadBroadcastQueue.isPendingBroadcastProcessLocked(pid);
14385     }
14386 
skipPendingBroadcastLocked(int pid)14387     void skipPendingBroadcastLocked(int pid) {
14388             Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
14389             for (BroadcastQueue queue : mBroadcastQueues) {
14390                 queue.skipPendingBroadcastLocked(pid);
14391             }
14392     }
14393 
14394     // The app just attached; send any pending broadcasts that it should receive
sendPendingBroadcastsLocked(ProcessRecord app)14395     boolean sendPendingBroadcastsLocked(ProcessRecord app) {
14396         boolean didSomething = false;
14397         for (BroadcastQueue queue : mBroadcastQueues) {
14398             didSomething |= queue.sendPendingBroadcastsLocked(app);
14399         }
14400         return didSomething;
14401     }
14402 
registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId, int flags)14403     public Intent registerReceiver(IApplicationThread caller, String callerPackage,
14404             IIntentReceiver receiver, IntentFilter filter, String permission, int userId,
14405             int flags) {
14406         enforceNotIsolatedCaller("registerReceiver");
14407         ArrayList<Intent> stickyIntents = null;
14408         ProcessRecord callerApp = null;
14409         final boolean visibleToInstantApps
14410                 = (flags & Context.RECEIVER_VISIBLE_TO_INSTANT_APPS) != 0;
14411         int callingUid;
14412         int callingPid;
14413         boolean instantApp;
14414         synchronized(this) {
14415             if (caller != null) {
14416                 callerApp = getRecordForAppLocked(caller);
14417                 if (callerApp == null) {
14418                     throw new SecurityException(
14419                             "Unable to find app for caller " + caller
14420                             + " (pid=" + Binder.getCallingPid()
14421                             + ") when registering receiver " + receiver);
14422                 }
14423                 if (callerApp.info.uid != SYSTEM_UID &&
14424                         !callerApp.pkgList.containsKey(callerPackage) &&
14425                         !"android".equals(callerPackage)) {
14426                     throw new SecurityException("Given caller package " + callerPackage
14427                             + " is not running in process " + callerApp);
14428                 }
14429                 callingUid = callerApp.info.uid;
14430                 callingPid = callerApp.pid;
14431             } else {
14432                 callerPackage = null;
14433                 callingUid = Binder.getCallingUid();
14434                 callingPid = Binder.getCallingPid();
14435             }
14436 
14437             instantApp = isInstantApp(callerApp, callerPackage, callingUid);
14438             userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
14439                     ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
14440 
14441             Iterator<String> actions = filter.actionsIterator();
14442             if (actions == null) {
14443                 ArrayList<String> noAction = new ArrayList<String>(1);
14444                 noAction.add(null);
14445                 actions = noAction.iterator();
14446             }
14447 
14448             // Collect stickies of users
14449             int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) };
14450             while (actions.hasNext()) {
14451                 String action = actions.next();
14452                 for (int id : userIds) {
14453                     ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id);
14454                     if (stickies != null) {
14455                         ArrayList<Intent> intents = stickies.get(action);
14456                         if (intents != null) {
14457                             if (stickyIntents == null) {
14458                                 stickyIntents = new ArrayList<Intent>();
14459                             }
14460                             stickyIntents.addAll(intents);
14461                         }
14462                     }
14463                 }
14464             }
14465         }
14466 
14467         ArrayList<Intent> allSticky = null;
14468         if (stickyIntents != null) {
14469             final ContentResolver resolver = mContext.getContentResolver();
14470             // Look for any matching sticky broadcasts...
14471             for (int i = 0, N = stickyIntents.size(); i < N; i++) {
14472                 Intent intent = stickyIntents.get(i);
14473                 // Don't provided intents that aren't available to instant apps.
14474                 if (instantApp &&
14475                         (intent.getFlags() & Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS) == 0) {
14476                     continue;
14477                 }
14478                 // If intent has scheme "content", it will need to acccess
14479                 // provider that needs to lock mProviderMap in ActivityThread
14480                 // and also it may need to wait application response, so we
14481                 // cannot lock ActivityManagerService here.
14482                 if (filter.match(resolver, intent, true, TAG) >= 0) {
14483                     if (allSticky == null) {
14484                         allSticky = new ArrayList<Intent>();
14485                     }
14486                     allSticky.add(intent);
14487                 }
14488             }
14489         }
14490 
14491         // The first sticky in the list is returned directly back to the client.
14492         Intent sticky = allSticky != null ? allSticky.get(0) : null;
14493         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky);
14494         if (receiver == null) {
14495             return sticky;
14496         }
14497 
14498         synchronized (this) {
14499             if (callerApp != null && (callerApp.thread == null
14500                     || callerApp.thread.asBinder() != caller.asBinder())) {
14501                 // Original caller already died
14502                 return null;
14503             }
14504             ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14505             if (rl == null) {
14506                 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
14507                         userId, receiver);
14508                 if (rl.app != null) {
14509                     final int totalReceiversForApp = rl.app.receivers.size();
14510                     if (totalReceiversForApp >= MAX_RECEIVERS_ALLOWED_PER_APP) {
14511                         throw new IllegalStateException("Too many receivers, total of "
14512                                 + totalReceiversForApp + ", registered for pid: "
14513                                 + rl.pid + ", callerPackage: " + callerPackage);
14514                     }
14515                     rl.app.receivers.add(rl);
14516                 } else {
14517                     try {
14518                         receiver.asBinder().linkToDeath(rl, 0);
14519                     } catch (RemoteException e) {
14520                         return sticky;
14521                     }
14522                     rl.linkedToDeath = true;
14523                 }
14524                 mRegisteredReceivers.put(receiver.asBinder(), rl);
14525             } else if (rl.uid != callingUid) {
14526                 throw new IllegalArgumentException(
14527                         "Receiver requested to register for uid " + callingUid
14528                         + " was previously registered for uid " + rl.uid
14529                         + " callerPackage is " + callerPackage);
14530             } else if (rl.pid != callingPid) {
14531                 throw new IllegalArgumentException(
14532                         "Receiver requested to register for pid " + callingPid
14533                         + " was previously registered for pid " + rl.pid
14534                         + " callerPackage is " + callerPackage);
14535             } else if (rl.userId != userId) {
14536                 throw new IllegalArgumentException(
14537                         "Receiver requested to register for user " + userId
14538                         + " was previously registered for user " + rl.userId
14539                         + " callerPackage is " + callerPackage);
14540             }
14541             BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
14542                     permission, callingUid, userId, instantApp, visibleToInstantApps);
14543             if (rl.containsFilter(filter)) {
14544                 Slog.w(TAG, "Receiver with filter " + filter
14545                         + " already registered for pid " + rl.pid
14546                         + ", callerPackage is " + callerPackage);
14547             } else {
14548                 rl.add(bf);
14549                 if (!bf.debugCheck()) {
14550                     Slog.w(TAG, "==> For Dynamic broadcast");
14551                 }
14552                 mReceiverResolver.addFilter(bf);
14553             }
14554 
14555             // Enqueue broadcasts for all existing stickies that match
14556             // this filter.
14557             if (allSticky != null) {
14558                 ArrayList receivers = new ArrayList();
14559                 receivers.add(bf);
14560 
14561                 final int stickyCount = allSticky.size();
14562                 for (int i = 0; i < stickyCount; i++) {
14563                     Intent intent = allSticky.get(i);
14564                     BroadcastQueue queue = broadcastQueueForIntent(intent);
14565                     BroadcastRecord r = new BroadcastRecord(queue, intent, null,
14566                             null, -1, -1, false, null, null, OP_NONE, null, receivers,
14567                             null, 0, null, null, false, true, true, -1, false,
14568                             false /* only PRE_BOOT_COMPLETED should be exempt, no stickies */);
14569                     queue.enqueueParallelBroadcastLocked(r);
14570                     queue.scheduleBroadcastsLocked();
14571                 }
14572             }
14573 
14574             return sticky;
14575         }
14576     }
14577 
unregisterReceiver(IIntentReceiver receiver)14578     public void unregisterReceiver(IIntentReceiver receiver) {
14579         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver);
14580 
14581         final long origId = Binder.clearCallingIdentity();
14582         try {
14583             boolean doTrim = false;
14584 
14585             synchronized(this) {
14586                 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14587                 if (rl != null) {
14588                     final BroadcastRecord r = rl.curBroadcast;
14589                     if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) {
14590                         final boolean doNext = r.queue.finishReceiverLocked(
14591                                 r, r.resultCode, r.resultData, r.resultExtras,
14592                                 r.resultAbort, false);
14593                         if (doNext) {
14594                             doTrim = true;
14595                             r.queue.processNextBroadcast(false);
14596                         }
14597                     }
14598 
14599                     if (rl.app != null) {
14600                         rl.app.receivers.remove(rl);
14601                     }
14602                     removeReceiverLocked(rl);
14603                     if (rl.linkedToDeath) {
14604                         rl.linkedToDeath = false;
14605                         rl.receiver.asBinder().unlinkToDeath(rl, 0);
14606                     }
14607                 }
14608             }
14609 
14610             // If we actually concluded any broadcasts, we might now be able
14611             // to trim the recipients' apps from our working set
14612             if (doTrim) {
14613                 trimApplications(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
14614                 return;
14615             }
14616 
14617         } finally {
14618             Binder.restoreCallingIdentity(origId);
14619         }
14620     }
14621 
removeReceiverLocked(ReceiverList rl)14622     void removeReceiverLocked(ReceiverList rl) {
14623         mRegisteredReceivers.remove(rl.receiver.asBinder());
14624         for (int i = rl.size() - 1; i >= 0; i--) {
14625             mReceiverResolver.removeFilter(rl.get(i));
14626         }
14627     }
14628 
sendPackageBroadcastLocked(int cmd, String[] packages, int userId)14629     private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
14630         mProcessList.sendPackageBroadcastLocked(cmd, packages, userId);
14631     }
14632 
collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users)14633     private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
14634             int callingUid, int[] users) {
14635         // TODO: come back and remove this assumption to triage all broadcasts
14636         int pmFlags = STOCK_PM_FLAGS | MATCH_DEBUG_TRIAGED_MISSING;
14637 
14638         List<ResolveInfo> receivers = null;
14639         try {
14640             HashSet<ComponentName> singleUserReceivers = null;
14641             boolean scannedFirstReceivers = false;
14642             for (int user : users) {
14643                 // Skip users that have Shell restrictions, with exception of always permitted
14644                 // Shell broadcasts
14645                 if (callingUid == SHELL_UID
14646                         && mUserController.hasUserRestriction(
14647                                 UserManager.DISALLOW_DEBUGGING_FEATURES, user)
14648                         && !isPermittedShellBroadcast(intent)) {
14649                     continue;
14650                 }
14651                 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
14652                         .queryIntentReceivers(intent, resolvedType, pmFlags, user).getList();
14653                 if (user != UserHandle.USER_SYSTEM && newReceivers != null) {
14654                     // If this is not the system user, we need to check for
14655                     // any receivers that should be filtered out.
14656                     for (int i=0; i<newReceivers.size(); i++) {
14657                         ResolveInfo ri = newReceivers.get(i);
14658                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
14659                             newReceivers.remove(i);
14660                             i--;
14661                         }
14662                     }
14663                 }
14664                 if (newReceivers != null && newReceivers.size() == 0) {
14665                     newReceivers = null;
14666                 }
14667                 if (receivers == null) {
14668                     receivers = newReceivers;
14669                 } else if (newReceivers != null) {
14670                     // We need to concatenate the additional receivers
14671                     // found with what we have do far.  This would be easy,
14672                     // but we also need to de-dup any receivers that are
14673                     // singleUser.
14674                     if (!scannedFirstReceivers) {
14675                         // Collect any single user receivers we had already retrieved.
14676                         scannedFirstReceivers = true;
14677                         for (int i=0; i<receivers.size(); i++) {
14678                             ResolveInfo ri = receivers.get(i);
14679                             if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14680                                 ComponentName cn = new ComponentName(
14681                                         ri.activityInfo.packageName, ri.activityInfo.name);
14682                                 if (singleUserReceivers == null) {
14683                                     singleUserReceivers = new HashSet<ComponentName>();
14684                                 }
14685                                 singleUserReceivers.add(cn);
14686                             }
14687                         }
14688                     }
14689                     // Add the new results to the existing results, tracking
14690                     // and de-dupping single user receivers.
14691                     for (int i=0; i<newReceivers.size(); i++) {
14692                         ResolveInfo ri = newReceivers.get(i);
14693                         if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14694                             ComponentName cn = new ComponentName(
14695                                     ri.activityInfo.packageName, ri.activityInfo.name);
14696                             if (singleUserReceivers == null) {
14697                                 singleUserReceivers = new HashSet<ComponentName>();
14698                             }
14699                             if (!singleUserReceivers.contains(cn)) {
14700                                 singleUserReceivers.add(cn);
14701                                 receivers.add(ri);
14702                             }
14703                         } else {
14704                             receivers.add(ri);
14705                         }
14706                     }
14707                 }
14708             }
14709         } catch (RemoteException ex) {
14710             // pm is in same process, this will never happen.
14711         }
14712         return receivers;
14713     }
14714 
isPermittedShellBroadcast(Intent intent)14715     private boolean isPermittedShellBroadcast(Intent intent) {
14716         // remote bugreport should always be allowed to be taken
14717         return INTENT_REMOTE_BUGREPORT_FINISHED.equals(intent.getAction());
14718     }
14719 
checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp, String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers)14720     private void checkBroadcastFromSystem(Intent intent, ProcessRecord callerApp,
14721             String callerPackage, int callingUid, boolean isProtectedBroadcast, List receivers) {
14722         if ((intent.getFlags() & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
14723             // Don't yell about broadcasts sent via shell
14724             return;
14725         }
14726 
14727         final String action = intent.getAction();
14728         if (isProtectedBroadcast
14729                 || Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
14730                 || Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS.equals(action)
14731                 || Intent.ACTION_MEDIA_BUTTON.equals(action)
14732                 || Intent.ACTION_MEDIA_SCANNER_SCAN_FILE.equals(action)
14733                 || Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS.equals(action)
14734                 || Intent.ACTION_MASTER_CLEAR.equals(action)
14735                 || Intent.ACTION_FACTORY_RESET.equals(action)
14736                 || AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14737                 || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)
14738                 || LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION.equals(action)
14739                 || TelephonyIntents.ACTION_REQUEST_OMADM_CONFIGURATION_UPDATE.equals(action)
14740                 || SuggestionSpan.ACTION_SUGGESTION_PICKED.equals(action)
14741                 || AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION.equals(action)
14742                 || AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION.equals(action)) {
14743             // Broadcast is either protected, or it's a public action that
14744             // we've relaxed, so it's fine for system internals to send.
14745             return;
14746         }
14747 
14748         // This broadcast may be a problem...  but there are often system components that
14749         // want to send an internal broadcast to themselves, which is annoying to have to
14750         // explicitly list each action as a protected broadcast, so we will check for that
14751         // one safe case and allow it: an explicit broadcast, only being received by something
14752         // that has protected itself.
14753         if (intent.getPackage() != null || intent.getComponent() != null) {
14754             if (receivers == null || receivers.size() == 0) {
14755                 // Intent is explicit and there's no receivers.
14756                 // This happens, e.g. , when a system component sends a broadcast to
14757                 // its own runtime receiver, and there's no manifest receivers for it,
14758                 // because this method is called twice for each broadcast,
14759                 // for runtime receivers and manifest receivers and the later check would find
14760                 // no receivers.
14761                 return;
14762             }
14763             boolean allProtected = true;
14764             for (int i = receivers.size()-1; i >= 0; i--) {
14765                 Object target = receivers.get(i);
14766                 if (target instanceof ResolveInfo) {
14767                     ResolveInfo ri = (ResolveInfo)target;
14768                     if (ri.activityInfo.exported && ri.activityInfo.permission == null) {
14769                         allProtected = false;
14770                         break;
14771                     }
14772                 } else {
14773                     BroadcastFilter bf = (BroadcastFilter)target;
14774                     if (bf.requiredPermission == null) {
14775                         allProtected = false;
14776                         break;
14777                     }
14778                 }
14779             }
14780             if (allProtected) {
14781                 // All safe!
14782                 return;
14783             }
14784         }
14785 
14786         // The vast majority of broadcasts sent from system internals
14787         // should be protected to avoid security holes, so yell loudly
14788         // to ensure we examine these cases.
14789         if (callerApp != null) {
14790             Log.wtf(TAG, "Sending non-protected broadcast " + action
14791                             + " from system " + callerApp.toShortString() + " pkg " + callerPackage,
14792                     new Throwable());
14793         } else {
14794             Log.wtf(TAG, "Sending non-protected broadcast " + action
14795                             + " from system uid " + UserHandle.formatUid(callingUid)
14796                             + " pkg " + callerPackage,
14797                     new Throwable());
14798         }
14799     }
14800 
14801     @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)14802     final int broadcastIntentLocked(ProcessRecord callerApp,
14803             String callerPackage, Intent intent, String resolvedType,
14804             IIntentReceiver resultTo, int resultCode, String resultData,
14805             Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
14806             boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
14807             int realCallingPid, int userId) {
14808         return broadcastIntentLocked(callerApp, callerPackage, intent, resolvedType, resultTo,
14809             resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions, ordered,
14810             sticky, callingPid, callingUid, realCallingUid, realCallingPid, userId,
14811             false /* allowBackgroundActivityStarts */);
14812     }
14813 
14814     @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)14815     final int broadcastIntentLocked(ProcessRecord callerApp,
14816             String callerPackage, Intent intent, String resolvedType,
14817             IIntentReceiver resultTo, int resultCode, String resultData,
14818             Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
14819             boolean ordered, boolean sticky, int callingPid, int callingUid, int realCallingUid,
14820             int realCallingPid, int userId, boolean allowBackgroundActivityStarts) {
14821         intent = new Intent(intent);
14822 
14823         final boolean callerInstantApp = isInstantApp(callerApp, callerPackage, callingUid);
14824         // Instant Apps cannot use FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS
14825         if (callerInstantApp) {
14826             intent.setFlags(intent.getFlags() & ~Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
14827         }
14828 
14829         // By default broadcasts do not go to stopped apps.
14830         intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
14831 
14832         // If we have not finished booting, don't allow this to launch new processes.
14833         if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
14834             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14835         }
14836 
14837         if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST,
14838                 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
14839                 + " ordered=" + ordered + " userid=" + userId);
14840         if ((resultTo != null) && !ordered) {
14841             Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
14842         }
14843 
14844         userId = mUserController.handleIncomingUser(callingPid, callingUid, userId, true,
14845                 ALLOW_NON_FULL, "broadcast", callerPackage);
14846 
14847         // Make sure that the user who is receiving this broadcast or its parent is running.
14848         // If not, we will just skip it. Make an exception for shutdown broadcasts, upgrade steps.
14849         if (userId != UserHandle.USER_ALL && !mUserController.isUserOrItsParentRunning(userId)) {
14850             if ((callingUid != SYSTEM_UID
14851                     || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0)
14852                     && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
14853                 Slog.w(TAG, "Skipping broadcast of " + intent
14854                         + ": user " + userId + " and its parent (if any) are stopped");
14855                 return ActivityManager.BROADCAST_FAILED_USER_STOPPED;
14856             }
14857         }
14858 
14859         final String action = intent.getAction();
14860         BroadcastOptions brOptions = null;
14861         if (bOptions != null) {
14862             brOptions = new BroadcastOptions(bOptions);
14863             if (brOptions.getTemporaryAppWhitelistDuration() > 0) {
14864                 // See if the caller is allowed to do this.  Note we are checking against
14865                 // the actual real caller (not whoever provided the operation as say a
14866                 // PendingIntent), because that who is actually supplied the arguments.
14867                 if (checkComponentPermission(
14868                         android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST,
14869                         realCallingPid, realCallingUid, -1, true)
14870                         != PackageManager.PERMISSION_GRANTED) {
14871                     String msg = "Permission Denial: " + intent.getAction()
14872                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14873                             + ", uid=" + callingUid + ")"
14874                             + " requires "
14875                             + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST;
14876                     Slog.w(TAG, msg);
14877                     throw new SecurityException(msg);
14878                 }
14879             }
14880             if (brOptions.isDontSendToRestrictedApps()
14881                     && !isUidActiveLocked(callingUid)
14882                     && isBackgroundRestrictedNoCheck(callingUid, callerPackage)) {
14883                 Slog.i(TAG, "Not sending broadcast " + action + " - app " + callerPackage
14884                         + " has background restrictions");
14885                 return ActivityManager.START_CANCELED;
14886             }
14887             if (brOptions.allowsBackgroundActivityStarts()) {
14888                 // See if the caller is allowed to do this.  Note we are checking against
14889                 // the actual real caller (not whoever provided the operation as say a
14890                 // PendingIntent), because that who is actually supplied the arguments.
14891                 if (checkComponentPermission(
14892                         android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
14893                         realCallingPid, realCallingUid, -1, true)
14894                         != PackageManager.PERMISSION_GRANTED) {
14895                     String msg = "Permission Denial: " + intent.getAction()
14896                             + " broadcast from " + callerPackage + " (pid=" + callingPid
14897                             + ", uid=" + callingUid + ")"
14898                             + " requires "
14899                             + android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
14900                     Slog.w(TAG, msg);
14901                     throw new SecurityException(msg);
14902                 } else {
14903                     allowBackgroundActivityStarts = true;
14904                 }
14905             }
14906         }
14907 
14908         // Verify that protected broadcasts are only being sent by system code,
14909         // and that system code is only sending protected broadcasts.
14910         final boolean isProtectedBroadcast;
14911         try {
14912             isProtectedBroadcast = AppGlobals.getPackageManager().isProtectedBroadcast(action);
14913         } catch (RemoteException e) {
14914             Slog.w(TAG, "Remote exception", e);
14915             return ActivityManager.BROADCAST_SUCCESS;
14916         }
14917 
14918         final boolean isCallerSystem;
14919         switch (UserHandle.getAppId(callingUid)) {
14920             case ROOT_UID:
14921             case SYSTEM_UID:
14922             case PHONE_UID:
14923             case BLUETOOTH_UID:
14924             case NFC_UID:
14925             case SE_UID:
14926             case NETWORK_STACK_UID:
14927                 isCallerSystem = true;
14928                 break;
14929             default:
14930                 isCallerSystem = (callerApp != null) && callerApp.isPersistent();
14931                 break;
14932         }
14933 
14934         // First line security check before anything else: stop non-system apps from
14935         // sending protected broadcasts.
14936         if (!isCallerSystem) {
14937             if (isProtectedBroadcast) {
14938                 String msg = "Permission Denial: not allowed to send broadcast "
14939                         + action + " from pid="
14940                         + callingPid + ", uid=" + callingUid;
14941                 Slog.w(TAG, msg);
14942                 throw new SecurityException(msg);
14943 
14944             } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(action)
14945                     || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
14946                 // Special case for compatibility: we don't want apps to send this,
14947                 // but historically it has not been protected and apps may be using it
14948                 // to poke their own app widget.  So, instead of making it protected,
14949                 // just limit it to the caller.
14950                 if (callerPackage == null) {
14951                     String msg = "Permission Denial: not allowed to send broadcast "
14952                             + action + " from unknown caller.";
14953                     Slog.w(TAG, msg);
14954                     throw new SecurityException(msg);
14955                 } else if (intent.getComponent() != null) {
14956                     // They are good enough to send to an explicit component...  verify
14957                     // it is being sent to the calling app.
14958                     if (!intent.getComponent().getPackageName().equals(
14959                             callerPackage)) {
14960                         String msg = "Permission Denial: not allowed to send broadcast "
14961                                 + action + " to "
14962                                 + intent.getComponent().getPackageName() + " from "
14963                                 + callerPackage;
14964                         Slog.w(TAG, msg);
14965                         throw new SecurityException(msg);
14966                     }
14967                 } else {
14968                     // Limit broadcast to their own package.
14969                     intent.setPackage(callerPackage);
14970                 }
14971             }
14972         }
14973 
14974         boolean timeoutExempt = false;
14975 
14976         if (action != null) {
14977             if (getBackgroundLaunchBroadcasts().contains(action)) {
14978                 if (DEBUG_BACKGROUND_CHECK) {
14979                     Slog.i(TAG, "Broadcast action " + action + " forcing include-background");
14980                 }
14981                 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
14982             }
14983 
14984             switch (action) {
14985                 case Intent.ACTION_UID_REMOVED:
14986                 case Intent.ACTION_PACKAGE_REMOVED:
14987                 case Intent.ACTION_PACKAGE_CHANGED:
14988                 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
14989                 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
14990                 case Intent.ACTION_PACKAGES_SUSPENDED:
14991                 case Intent.ACTION_PACKAGES_UNSUSPENDED:
14992                     // Handle special intents: if this broadcast is from the package
14993                     // manager about a package being removed, we need to remove all of
14994                     // its activities from the history stack.
14995                     if (checkComponentPermission(
14996                             android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
14997                             callingPid, callingUid, -1, true)
14998                             != PackageManager.PERMISSION_GRANTED) {
14999                         String msg = "Permission Denial: " + intent.getAction()
15000                                 + " broadcast from " + callerPackage + " (pid=" + callingPid
15001                                 + ", uid=" + callingUid + ")"
15002                                 + " requires "
15003                                 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
15004                         Slog.w(TAG, msg);
15005                         throw new SecurityException(msg);
15006                     }
15007                     switch (action) {
15008                         case Intent.ACTION_UID_REMOVED:
15009                             final int uid = getUidFromIntent(intent);
15010                             if (uid >= 0) {
15011                                 mBatteryStatsService.removeUid(uid);
15012                                 mAppOpsService.uidRemoved(uid);
15013                             }
15014                             break;
15015                         case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
15016                             // If resources are unavailable just force stop all those packages
15017                             // and flush the attribute cache as well.
15018                             String list[] =
15019                                     intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15020                             if (list != null && list.length > 0) {
15021                                 for (int i = 0; i < list.length; i++) {
15022                                     forceStopPackageLocked(list[i], -1, false, true, true,
15023                                             false, false, userId, "storage unmount");
15024                                 }
15025                                 mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
15026                                 sendPackageBroadcastLocked(
15027                                         ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE,
15028                                         list, userId);
15029                             }
15030                             break;
15031                         case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
15032                             mAtmInternal.cleanupRecentTasksForUser(UserHandle.USER_ALL);
15033                             break;
15034                         case Intent.ACTION_PACKAGE_REMOVED:
15035                         case Intent.ACTION_PACKAGE_CHANGED:
15036                             Uri data = intent.getData();
15037                             String ssp;
15038                             if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
15039                                 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action);
15040                                 final boolean replacing =
15041                                         intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
15042                                 final boolean killProcess =
15043                                         !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false);
15044                                 final boolean fullUninstall = removed && !replacing;
15045                                 if (removed) {
15046                                     if (killProcess) {
15047                                         forceStopPackageLocked(ssp, UserHandle.getAppId(
15048                                                 intent.getIntExtra(Intent.EXTRA_UID, -1)),
15049                                                 false, true, true, false, fullUninstall, userId,
15050                                                 removed ? "pkg removed" : "pkg changed");
15051                                     }
15052                                     final int cmd = killProcess
15053                                             ? ApplicationThreadConstants.PACKAGE_REMOVED
15054                                             : ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL;
15055                                     sendPackageBroadcastLocked(cmd,
15056                                             new String[] {ssp}, userId);
15057                                     if (fullUninstall) {
15058                                         mAppOpsService.packageRemoved(
15059                                                 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
15060 
15061                                         // Remove all permissions granted from/to this package
15062                                         mUgmInternal.removeUriPermissionsForPackage(ssp, userId,
15063                                                 true, false);
15064 
15065                                         mAtmInternal.removeRecentTasksByPackageName(ssp, userId);
15066 
15067                                         mServices.forceStopPackageLocked(ssp, userId);
15068                                         mAtmInternal.onPackageUninstalled(ssp);
15069                                         mBatteryStatsService.notePackageUninstalled(ssp);
15070                                     }
15071                                 } else {
15072                                     if (killProcess) {
15073                                         final int extraUid = intent.getIntExtra(Intent.EXTRA_UID,
15074                                                 -1);
15075                                         mProcessList.killPackageProcessesLocked(ssp,
15076                                                 UserHandle.getAppId(extraUid),
15077                                                 userId, ProcessList.INVALID_ADJ, "change " + ssp);
15078                                     }
15079                                     cleanupDisabledPackageComponentsLocked(ssp, userId,
15080                                             intent.getStringArrayExtra(
15081                                                     Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST));
15082                                 }
15083                             }
15084                             break;
15085                         case Intent.ACTION_PACKAGES_SUSPENDED:
15086                         case Intent.ACTION_PACKAGES_UNSUSPENDED:
15087                             final boolean suspended = Intent.ACTION_PACKAGES_SUSPENDED.equals(
15088                                     intent.getAction());
15089                             final String[] packageNames = intent.getStringArrayExtra(
15090                                     Intent.EXTRA_CHANGED_PACKAGE_LIST);
15091                             final int userHandle = intent.getIntExtra(
15092                                     Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
15093 
15094                             mAtmInternal.onPackagesSuspendedChanged(packageNames, suspended,
15095                                     userHandle);
15096                             break;
15097                     }
15098                     break;
15099                 case Intent.ACTION_PACKAGE_REPLACED:
15100                 {
15101                     final Uri data = intent.getData();
15102                     final String ssp;
15103                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
15104                         ApplicationInfo aInfo = null;
15105                         try {
15106                             aInfo = AppGlobals.getPackageManager()
15107                                     .getApplicationInfo(ssp, STOCK_PM_FLAGS, userId);
15108                         } catch (RemoteException ignore) {}
15109                         if (aInfo == null) {
15110                             Slog.w(TAG, "Dropping ACTION_PACKAGE_REPLACED for non-existent pkg:"
15111                                     + " ssp=" + ssp + " data=" + data);
15112                             return ActivityManager.BROADCAST_SUCCESS;
15113                         }
15114                         updateAssociationForApp(aInfo);
15115                         mAtmInternal.onPackageReplaced(aInfo);
15116                         mServices.updateServiceApplicationInfoLocked(aInfo);
15117                         sendPackageBroadcastLocked(ApplicationThreadConstants.PACKAGE_REPLACED,
15118                                 new String[] {ssp}, userId);
15119                     }
15120                     break;
15121                 }
15122                 case Intent.ACTION_PACKAGE_ADDED:
15123                 {
15124                     // Special case for adding a package: by default turn on compatibility mode.
15125                     Uri data = intent.getData();
15126                     String ssp;
15127                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
15128                         final boolean replacing =
15129                                 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
15130                         mAtmInternal.onPackageAdded(ssp, replacing);
15131 
15132                         try {
15133                             ApplicationInfo ai = AppGlobals.getPackageManager().
15134                                     getApplicationInfo(ssp, STOCK_PM_FLAGS, 0);
15135                             mBatteryStatsService.notePackageInstalled(ssp,
15136                                     ai != null ? ai.longVersionCode : 0);
15137                         } catch (RemoteException e) {
15138                         }
15139                     }
15140                     break;
15141                 }
15142                 case Intent.ACTION_PACKAGE_DATA_CLEARED:
15143                 {
15144                     Uri data = intent.getData();
15145                     String ssp;
15146                     if (data != null && (ssp = data.getSchemeSpecificPart()) != null) {
15147                         mAtmInternal.onPackageDataCleared(ssp);
15148                     }
15149                     break;
15150                 }
15151                 case Intent.ACTION_TIMEZONE_CHANGED:
15152                     // If this is the time zone changed action, queue up a message that will reset
15153                     // the timezone of all currently running processes. This message will get
15154                     // queued up before the broadcast happens.
15155                     mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
15156                     break;
15157                 case Intent.ACTION_TIME_CHANGED:
15158                     // EXTRA_TIME_PREF_24_HOUR_FORMAT is optional so we must distinguish between
15159                     // the tri-state value it may contain and "unknown".
15160                     // For convenience we re-use the Intent extra values.
15161                     final int NO_EXTRA_VALUE_FOUND = -1;
15162                     final int timeFormatPreferenceMsgValue = intent.getIntExtra(
15163                             Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT,
15164                             NO_EXTRA_VALUE_FOUND /* defaultValue */);
15165                     // Only send a message if the time preference is available.
15166                     if (timeFormatPreferenceMsgValue != NO_EXTRA_VALUE_FOUND) {
15167                         Message updateTimePreferenceMsg =
15168                                 mHandler.obtainMessage(UPDATE_TIME_PREFERENCE_MSG,
15169                                         timeFormatPreferenceMsgValue, 0);
15170                         mHandler.sendMessage(updateTimePreferenceMsg);
15171                     }
15172                     BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
15173                     synchronized (stats) {
15174                         stats.noteCurrentTimeChangedLocked();
15175                     }
15176                     break;
15177                 case Intent.ACTION_CLEAR_DNS_CACHE:
15178                     mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
15179                     break;
15180                 case Proxy.PROXY_CHANGE_ACTION:
15181                     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG));
15182                     break;
15183                 case android.hardware.Camera.ACTION_NEW_PICTURE:
15184                 case android.hardware.Camera.ACTION_NEW_VIDEO:
15185                     // In N we just turned these off; in O we are turing them back on partly,
15186                     // only for registered receivers.  This will still address the main problem
15187                     // (a spam of apps waking up when a picture is taken putting significant
15188                     // memory pressure on the system at a bad point), while still allowing apps
15189                     // that are already actively running to know about this happening.
15190                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
15191                     break;
15192                 case android.security.KeyChain.ACTION_TRUST_STORE_CHANGED:
15193                     mHandler.sendEmptyMessage(HANDLE_TRUST_STORAGE_UPDATE_MSG);
15194                     break;
15195                 case "com.android.launcher.action.INSTALL_SHORTCUT":
15196                     // As of O, we no longer support this broadcasts, even for pre-O apps.
15197                     // Apps should now be using ShortcutManager.pinRequestShortcut().
15198                     Log.w(TAG, "Broadcast " + action
15199                             + " no longer supported. It will not be delivered.");
15200                     return ActivityManager.BROADCAST_SUCCESS;
15201                 case Intent.ACTION_PRE_BOOT_COMPLETED:
15202                     timeoutExempt = true;
15203                     break;
15204             }
15205 
15206             if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
15207                     Intent.ACTION_PACKAGE_REMOVED.equals(action) ||
15208                     Intent.ACTION_PACKAGE_REPLACED.equals(action)) {
15209                 final int uid = getUidFromIntent(intent);
15210                 if (uid != -1) {
15211                     final UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
15212                     if (uidRec != null) {
15213                         uidRec.updateHasInternetPermission();
15214                     }
15215                 }
15216             }
15217         }
15218 
15219         // Add to the sticky list if requested.
15220         if (sticky) {
15221             if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
15222                     callingPid, callingUid)
15223                     != PackageManager.PERMISSION_GRANTED) {
15224                 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
15225                         + callingPid + ", uid=" + callingUid
15226                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15227                 Slog.w(TAG, msg);
15228                 throw new SecurityException(msg);
15229             }
15230             if (requiredPermissions != null && requiredPermissions.length > 0) {
15231                 Slog.w(TAG, "Can't broadcast sticky intent " + intent
15232                         + " and enforce permissions " + Arrays.toString(requiredPermissions));
15233                 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
15234             }
15235             if (intent.getComponent() != null) {
15236                 throw new SecurityException(
15237                         "Sticky broadcasts can't target a specific component");
15238             }
15239             // We use userId directly here, since the "all" target is maintained
15240             // as a separate set of sticky broadcasts.
15241             if (userId != UserHandle.USER_ALL) {
15242                 // But first, if this is not a broadcast to all users, then
15243                 // make sure it doesn't conflict with an existing broadcast to
15244                 // all users.
15245                 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
15246                         UserHandle.USER_ALL);
15247                 if (stickies != null) {
15248                     ArrayList<Intent> list = stickies.get(intent.getAction());
15249                     if (list != null) {
15250                         int N = list.size();
15251                         int i;
15252                         for (i=0; i<N; i++) {
15253                             if (intent.filterEquals(list.get(i))) {
15254                                 throw new IllegalArgumentException(
15255                                         "Sticky broadcast " + intent + " for user "
15256                                         + userId + " conflicts with existing global broadcast");
15257                             }
15258                         }
15259                     }
15260                 }
15261             }
15262             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
15263             if (stickies == null) {
15264                 stickies = new ArrayMap<>();
15265                 mStickyBroadcasts.put(userId, stickies);
15266             }
15267             ArrayList<Intent> list = stickies.get(intent.getAction());
15268             if (list == null) {
15269                 list = new ArrayList<>();
15270                 stickies.put(intent.getAction(), list);
15271             }
15272             final int stickiesCount = list.size();
15273             int i;
15274             for (i = 0; i < stickiesCount; i++) {
15275                 if (intent.filterEquals(list.get(i))) {
15276                     // This sticky already exists, replace it.
15277                     list.set(i, new Intent(intent));
15278                     break;
15279                 }
15280             }
15281             if (i >= stickiesCount) {
15282                 list.add(new Intent(intent));
15283             }
15284         }
15285 
15286         int[] users;
15287         if (userId == UserHandle.USER_ALL) {
15288             // Caller wants broadcast to go to all started users.
15289             users = mUserController.getStartedUserArray();
15290         } else {
15291             // Caller wants broadcast to go to one specific user.
15292             users = new int[] {userId};
15293         }
15294 
15295         // Figure out who all will receive this broadcast.
15296         List receivers = null;
15297         List<BroadcastFilter> registeredReceivers = null;
15298         // Need to resolve the intent to interested receivers...
15299         if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
15300                  == 0) {
15301             receivers = collectReceiverComponents(intent, resolvedType, callingUid, users);
15302         }
15303         if (intent.getComponent() == null) {
15304             if (userId == UserHandle.USER_ALL && callingUid == SHELL_UID) {
15305                 // Query one target user at a time, excluding shell-restricted users
15306                 for (int i = 0; i < users.length; i++) {
15307                     if (mUserController.hasUserRestriction(
15308                             UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) {
15309                         continue;
15310                     }
15311                     List<BroadcastFilter> registeredReceiversForUser =
15312                             mReceiverResolver.queryIntent(intent,
15313                                     resolvedType, false /*defaultOnly*/, users[i]);
15314                     if (registeredReceivers == null) {
15315                         registeredReceivers = registeredReceiversForUser;
15316                     } else if (registeredReceiversForUser != null) {
15317                         registeredReceivers.addAll(registeredReceiversForUser);
15318                     }
15319                 }
15320             } else {
15321                 registeredReceivers = mReceiverResolver.queryIntent(intent,
15322                         resolvedType, false /*defaultOnly*/, userId);
15323             }
15324         }
15325 
15326         final boolean replacePending =
15327                 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
15328 
15329         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing broadcast: " + intent.getAction()
15330                 + " replacePending=" + replacePending);
15331 
15332         int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
15333         if (!ordered && NR > 0) {
15334             // If we are not serializing this broadcast, then send the
15335             // registered receivers separately so they don't wait for the
15336             // components to be launched.
15337             if (isCallerSystem) {
15338                 checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15339                         isProtectedBroadcast, registeredReceivers);
15340             }
15341             final BroadcastQueue queue = broadcastQueueForIntent(intent);
15342             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
15343                     callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
15344                     requiredPermissions, appOp, brOptions, registeredReceivers, resultTo,
15345                     resultCode, resultData, resultExtras, ordered, sticky, false, userId,
15346                     allowBackgroundActivityStarts, timeoutExempt);
15347             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r);
15348             final boolean replaced = replacePending
15349                     && (queue.replaceParallelBroadcastLocked(r) != null);
15350             // Note: We assume resultTo is null for non-ordered broadcasts.
15351             if (!replaced) {
15352                 queue.enqueueParallelBroadcastLocked(r);
15353                 queue.scheduleBroadcastsLocked();
15354             }
15355             registeredReceivers = null;
15356             NR = 0;
15357         }
15358 
15359         // Merge into one list.
15360         int ir = 0;
15361         if (receivers != null) {
15362             // A special case for PACKAGE_ADDED: do not allow the package
15363             // being added to see this broadcast.  This prevents them from
15364             // using this as a back door to get run as soon as they are
15365             // installed.  Maybe in the future we want to have a special install
15366             // broadcast or such for apps, but we'd like to deliberately make
15367             // this decision.
15368             String skipPackages[] = null;
15369             if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
15370                     || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
15371                     || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
15372                 Uri data = intent.getData();
15373                 if (data != null) {
15374                     String pkgName = data.getSchemeSpecificPart();
15375                     if (pkgName != null) {
15376                         skipPackages = new String[] { pkgName };
15377                     }
15378                 }
15379             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
15380                 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
15381             }
15382             if (skipPackages != null && (skipPackages.length > 0)) {
15383                 for (String skipPackage : skipPackages) {
15384                     if (skipPackage != null) {
15385                         int NT = receivers.size();
15386                         for (int it=0; it<NT; it++) {
15387                             ResolveInfo curt = (ResolveInfo)receivers.get(it);
15388                             if (curt.activityInfo.packageName.equals(skipPackage)) {
15389                                 receivers.remove(it);
15390                                 it--;
15391                                 NT--;
15392                             }
15393                         }
15394                     }
15395                 }
15396             }
15397 
15398             int NT = receivers != null ? receivers.size() : 0;
15399             int it = 0;
15400             ResolveInfo curt = null;
15401             BroadcastFilter curr = null;
15402             while (it < NT && ir < NR) {
15403                 if (curt == null) {
15404                     curt = (ResolveInfo)receivers.get(it);
15405                 }
15406                 if (curr == null) {
15407                     curr = registeredReceivers.get(ir);
15408                 }
15409                 if (curr.getPriority() >= curt.priority) {
15410                     // Insert this broadcast record into the final list.
15411                     receivers.add(it, curr);
15412                     ir++;
15413                     curr = null;
15414                     it++;
15415                     NT++;
15416                 } else {
15417                     // Skip to the next ResolveInfo in the final list.
15418                     it++;
15419                     curt = null;
15420                 }
15421             }
15422         }
15423         while (ir < NR) {
15424             if (receivers == null) {
15425                 receivers = new ArrayList();
15426             }
15427             receivers.add(registeredReceivers.get(ir));
15428             ir++;
15429         }
15430 
15431         if (isCallerSystem) {
15432             checkBroadcastFromSystem(intent, callerApp, callerPackage, callingUid,
15433                     isProtectedBroadcast, receivers);
15434         }
15435 
15436         if ((receivers != null && receivers.size() > 0)
15437                 || resultTo != null) {
15438             BroadcastQueue queue = broadcastQueueForIntent(intent);
15439             BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
15440                     callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
15441                     requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
15442                     resultData, resultExtras, ordered, sticky, false, userId,
15443                     allowBackgroundActivityStarts, timeoutExempt);
15444 
15445             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
15446 
15447             final BroadcastRecord oldRecord =
15448                     replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
15449             if (oldRecord != null) {
15450                 // Replaced, fire the result-to receiver.
15451                 if (oldRecord.resultTo != null) {
15452                     final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
15453                     try {
15454                         oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
15455                                 oldRecord.intent,
15456                                 Activity.RESULT_CANCELED, null, null,
15457                                 false, false, oldRecord.userId);
15458                     } catch (RemoteException e) {
15459                         Slog.w(TAG, "Failure ["
15460                                 + queue.mQueueName + "] sending broadcast result of "
15461                                 + intent, e);
15462 
15463                     }
15464                 }
15465             } else {
15466                 queue.enqueueOrderedBroadcastLocked(r);
15467                 queue.scheduleBroadcastsLocked();
15468             }
15469         } else {
15470             // There was nobody interested in the broadcast, but we still want to record
15471             // that it happened.
15472             if (intent.getComponent() == null && intent.getPackage() == null
15473                     && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15474                 // This was an implicit broadcast... let's record it for posterity.
15475                 addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
15476             }
15477         }
15478 
15479         return ActivityManager.BROADCAST_SUCCESS;
15480     }
15481 
15482     /**
15483      * @return uid from the extra field {@link Intent#EXTRA_UID} if present, Otherwise -1
15484      */
getUidFromIntent(Intent intent)15485     private int getUidFromIntent(Intent intent) {
15486         if (intent == null) {
15487             return -1;
15488         }
15489         final Bundle intentExtras = intent.getExtras();
15490         return intent.hasExtra(Intent.EXTRA_UID)
15491                 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
15492     }
15493 
rotateBroadcastStatsIfNeededLocked()15494     final void rotateBroadcastStatsIfNeededLocked() {
15495         final long now = SystemClock.elapsedRealtime();
15496         if (mCurBroadcastStats == null ||
15497                 (mCurBroadcastStats.mStartRealtime +(24*60*60*1000) < now)) {
15498             mLastBroadcastStats = mCurBroadcastStats;
15499             if (mLastBroadcastStats != null) {
15500                 mLastBroadcastStats.mEndRealtime = SystemClock.elapsedRealtime();
15501                 mLastBroadcastStats.mEndUptime = SystemClock.uptimeMillis();
15502             }
15503             mCurBroadcastStats = new BroadcastStats();
15504         }
15505     }
15506 
addBroadcastStatLocked(String action, String srcPackage, int receiveCount, int skipCount, long dispatchTime)15507     final void addBroadcastStatLocked(String action, String srcPackage, int receiveCount,
15508             int skipCount, long dispatchTime) {
15509         rotateBroadcastStatsIfNeededLocked();
15510         mCurBroadcastStats.addBroadcast(action, srcPackage, receiveCount, skipCount, dispatchTime);
15511     }
15512 
addBackgroundCheckViolationLocked(String action, String targetPackage)15513     final void addBackgroundCheckViolationLocked(String action, String targetPackage) {
15514         rotateBroadcastStatsIfNeededLocked();
15515         mCurBroadcastStats.addBackgroundCheckViolation(action, targetPackage);
15516     }
15517 
verifyBroadcastLocked(Intent intent)15518     final Intent verifyBroadcastLocked(Intent intent) {
15519         // Refuse possible leaked file descriptors
15520         if (intent != null && intent.hasFileDescriptors() == true) {
15521             throw new IllegalArgumentException("File descriptors passed in Intent");
15522         }
15523 
15524         int flags = intent.getFlags();
15525 
15526         if (!mProcessesReady) {
15527             // if the caller really truly claims to know what they're doing, go
15528             // ahead and allow the broadcast without launching any receivers
15529             if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
15530                 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed.
15531             } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
15532                 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
15533                         + " before boot completion");
15534                 throw new IllegalStateException("Cannot broadcast before boot completed");
15535             }
15536         }
15537 
15538         if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
15539             throw new IllegalArgumentException(
15540                     "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
15541         }
15542 
15543         if ((flags & Intent.FLAG_RECEIVER_FROM_SHELL) != 0) {
15544             switch (Binder.getCallingUid()) {
15545                 case ROOT_UID:
15546                 case SHELL_UID:
15547                     break;
15548                 default:
15549                     Slog.w(TAG, "Removing FLAG_RECEIVER_FROM_SHELL because caller is UID "
15550                             + Binder.getCallingUid());
15551                     intent.removeFlags(Intent.FLAG_RECEIVER_FROM_SHELL);
15552                     break;
15553             }
15554         }
15555 
15556         return intent;
15557     }
15558 
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)15559     public final int broadcastIntent(IApplicationThread caller,
15560             Intent intent, String resolvedType, IIntentReceiver resultTo,
15561             int resultCode, String resultData, Bundle resultExtras,
15562             String[] requiredPermissions, int appOp, Bundle bOptions,
15563             boolean serialized, boolean sticky, int userId) {
15564         enforceNotIsolatedCaller("broadcastIntent");
15565         synchronized(this) {
15566             intent = verifyBroadcastLocked(intent);
15567 
15568             final ProcessRecord callerApp = getRecordForAppLocked(caller);
15569             final int callingPid = Binder.getCallingPid();
15570             final int callingUid = Binder.getCallingUid();
15571 
15572             final long origId = Binder.clearCallingIdentity();
15573             try {
15574                 return broadcastIntentLocked(callerApp,
15575                         callerApp != null ? callerApp.info.packageName : null,
15576                         intent, resolvedType, resultTo, resultCode, resultData, resultExtras,
15577                         requiredPermissions, appOp, bOptions, serialized, sticky,
15578                         callingPid, callingUid, callingUid, callingPid, userId);
15579             } finally {
15580                 Binder.restoreCallingIdentity(origId);
15581             }
15582         }
15583     }
15584 
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)15585     int broadcastIntentInPackage(String packageName, int uid, int realCallingUid,
15586             int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo,
15587             int resultCode, String resultData, Bundle resultExtras,
15588             String requiredPermission, Bundle bOptions, boolean serialized, boolean sticky,
15589             int userId, boolean allowBackgroundActivityStarts) {
15590         synchronized(this) {
15591             intent = verifyBroadcastLocked(intent);
15592 
15593             final long origId = Binder.clearCallingIdentity();
15594             String[] requiredPermissions = requiredPermission == null ? null
15595                     : new String[] {requiredPermission};
15596             try {
15597                 return broadcastIntentLocked(null, packageName, intent, resolvedType,
15598                         resultTo, resultCode, resultData, resultExtras,
15599                         requiredPermissions, OP_NONE, bOptions, serialized,
15600                         sticky, -1, uid, realCallingUid, realCallingPid, userId,
15601                         allowBackgroundActivityStarts);
15602             } finally {
15603                 Binder.restoreCallingIdentity(origId);
15604             }
15605         }
15606     }
15607 
unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)15608     public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
15609         // Refuse possible leaked file descriptors
15610         if (intent != null && intent.hasFileDescriptors() == true) {
15611             throw new IllegalArgumentException("File descriptors passed in Intent");
15612         }
15613 
15614         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
15615                 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
15616 
15617         synchronized(this) {
15618             if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
15619                     != PackageManager.PERMISSION_GRANTED) {
15620                 String msg = "Permission Denial: unbroadcastIntent() from pid="
15621                         + Binder.getCallingPid()
15622                         + ", uid=" + Binder.getCallingUid()
15623                         + " requires " + android.Manifest.permission.BROADCAST_STICKY;
15624                 Slog.w(TAG, msg);
15625                 throw new SecurityException(msg);
15626             }
15627             ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
15628             if (stickies != null) {
15629                 ArrayList<Intent> list = stickies.get(intent.getAction());
15630                 if (list != null) {
15631                     int N = list.size();
15632                     int i;
15633                     for (i=0; i<N; i++) {
15634                         if (intent.filterEquals(list.get(i))) {
15635                             list.remove(i);
15636                             break;
15637                         }
15638                     }
15639                     if (list.size() <= 0) {
15640                         stickies.remove(intent.getAction());
15641                     }
15642                 }
15643                 if (stickies.size() <= 0) {
15644                     mStickyBroadcasts.remove(userId);
15645                 }
15646             }
15647         }
15648     }
15649 
backgroundServicesFinishedLocked(int userId)15650     void backgroundServicesFinishedLocked(int userId) {
15651         for (BroadcastQueue queue : mBroadcastQueues) {
15652             queue.backgroundServicesFinishedLocked(userId);
15653         }
15654     }
15655 
finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)15656     public void finishReceiver(IBinder who, int resultCode, String resultData,
15657             Bundle resultExtras, boolean resultAbort, int flags) {
15658         if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who);
15659 
15660         // Refuse possible leaked file descriptors
15661         if (resultExtras != null && resultExtras.hasFileDescriptors()) {
15662             throw new IllegalArgumentException("File descriptors passed in Bundle");
15663         }
15664 
15665         final long origId = Binder.clearCallingIdentity();
15666         try {
15667             boolean doNext = false;
15668             BroadcastRecord r;
15669             BroadcastQueue queue;
15670 
15671             synchronized(this) {
15672                 if (isOnOffloadQueue(flags)) {
15673                     queue = mOffloadBroadcastQueue;
15674                 } else {
15675                     queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0
15676                             ? mFgBroadcastQueue : mBgBroadcastQueue;
15677                 }
15678 
15679                 r = queue.getMatchingOrderedReceiver(who);
15680                 if (r != null) {
15681                     doNext = r.queue.finishReceiverLocked(r, resultCode,
15682                         resultData, resultExtras, resultAbort, true);
15683                 }
15684                 if (doNext) {
15685                     r.queue.processNextBroadcastLocked(/*fromMsg=*/ false, /*skipOomAdj=*/ true);
15686                 }
15687                 // updateOomAdjLocked() will be done here
15688                 trimApplicationsLocked(OomAdjuster.OOM_ADJ_REASON_FINISH_RECEIVER);
15689             }
15690 
15691         } finally {
15692             Binder.restoreCallingIdentity(origId);
15693         }
15694     }
15695 
15696     // =========================================================
15697     // INSTRUMENTATION
15698     // =========================================================
15699 
startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)15700     public boolean startInstrumentation(ComponentName className,
15701             String profileFile, int flags, Bundle arguments,
15702             IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
15703             int userId, String abiOverride) {
15704         enforceNotIsolatedCaller("startInstrumentation");
15705         final int callingUid = Binder.getCallingUid();
15706         final int callingPid = Binder.getCallingPid();
15707         userId = mUserController.handleIncomingUser(callingPid, callingUid,
15708                 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
15709         // Refuse possible leaked file descriptors
15710         if (arguments != null && arguments.hasFileDescriptors()) {
15711             throw new IllegalArgumentException("File descriptors passed in Bundle");
15712         }
15713 
15714         synchronized(this) {
15715             InstrumentationInfo ii = null;
15716             ApplicationInfo ai = null;
15717             try {
15718                 ii = mContext.getPackageManager().getInstrumentationInfo(
15719                     className, STOCK_PM_FLAGS);
15720                 ai = AppGlobals.getPackageManager().getApplicationInfo(
15721                         ii.targetPackage, STOCK_PM_FLAGS, userId);
15722             } catch (PackageManager.NameNotFoundException e) {
15723             } catch (RemoteException e) {
15724             }
15725             if (ii == null) {
15726                 reportStartInstrumentationFailureLocked(watcher, className,
15727                         "Unable to find instrumentation info for: " + className);
15728                 return false;
15729             }
15730             if (ai == null) {
15731                 reportStartInstrumentationFailureLocked(watcher, className,
15732                         "Unable to find instrumentation target package: " + ii.targetPackage);
15733                 return false;
15734             }
15735             if (!ai.hasCode()) {
15736                 reportStartInstrumentationFailureLocked(watcher, className,
15737                         "Instrumentation target has no code: " + ii.targetPackage);
15738                 return false;
15739             }
15740 
15741             int match = mContext.getPackageManager().checkSignatures(
15742                     ii.targetPackage, ii.packageName);
15743             if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
15744                 String msg = "Permission Denial: starting instrumentation "
15745                         + className + " from pid="
15746                         + Binder.getCallingPid()
15747                         + ", uid=" + Binder.getCallingPid()
15748                         + " not allowed because package " + ii.packageName
15749                         + " does not have a signature matching the target "
15750                         + ii.targetPackage;
15751                 reportStartInstrumentationFailureLocked(watcher, className, msg);
15752                 throw new SecurityException(msg);
15753             }
15754 
15755             ActiveInstrumentation activeInstr = new ActiveInstrumentation(this);
15756             activeInstr.mClass = className;
15757             String defProcess = ai.processName;;
15758             if (ii.targetProcesses == null) {
15759                 activeInstr.mTargetProcesses = new String[]{ai.processName};
15760             } else if (ii.targetProcesses.equals("*")) {
15761                 activeInstr.mTargetProcesses = new String[0];
15762             } else {
15763                 activeInstr.mTargetProcesses = ii.targetProcesses.split(",");
15764                 defProcess = activeInstr.mTargetProcesses[0];
15765             }
15766             activeInstr.mTargetInfo = ai;
15767             activeInstr.mProfileFile = profileFile;
15768             activeInstr.mArguments = arguments;
15769             activeInstr.mWatcher = watcher;
15770             activeInstr.mUiAutomationConnection = uiAutomationConnection;
15771             activeInstr.mResultClass = className;
15772             activeInstr.mHasBackgroundActivityStartsPermission = checkPermission(
15773                     START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
15774                             == PackageManager.PERMISSION_GRANTED;
15775 
15776             boolean disableHiddenApiChecks = ai.usesNonSdkApi()
15777                     || (flags & INSTR_FLAG_DISABLE_HIDDEN_API_CHECKS) != 0;
15778             if (disableHiddenApiChecks) {
15779                 enforceCallingPermission(android.Manifest.permission.DISABLE_HIDDEN_API_CHECKS,
15780                         "disable hidden API checks");
15781             }
15782             final boolean mountExtStorageFull = isCallerShell()
15783                     && (flags & INSTR_FLAG_MOUNT_EXTERNAL_STORAGE_FULL) != 0;
15784 
15785             final long origId = Binder.clearCallingIdentity();
15786             // Instrumentation can kill and relaunch even persistent processes
15787             forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId,
15788                     "start instr");
15789             // Inform usage stats to make the target package active
15790             if (mUsageStatsService != null) {
15791                 mUsageStatsService.reportEvent(ii.targetPackage, userId,
15792                         UsageEvents.Event.SYSTEM_INTERACTION);
15793             }
15794 
15795             ProcessRecord app = addAppLocked(ai, defProcess, false, disableHiddenApiChecks,
15796                     mountExtStorageFull, abiOverride);
15797             app.setActiveInstrumentation(activeInstr);
15798             activeInstr.mFinished = false;
15799             activeInstr.mRunningProcesses.add(app);
15800             if (!mActiveInstrumentation.contains(activeInstr)) {
15801                 mActiveInstrumentation.add(activeInstr);
15802             }
15803             Binder.restoreCallingIdentity(origId);
15804         }
15805 
15806         return true;
15807     }
15808 
isCallerShell()15809     private boolean isCallerShell() {
15810         final int callingUid = Binder.getCallingUid();
15811         return callingUid == SHELL_UID || callingUid == ROOT_UID;
15812     }
15813 
15814     /**
15815      * Report errors that occur while attempting to start Instrumentation.  Always writes the
15816      * error to the logs, but if somebody is watching, send the report there too.  This enables
15817      * the "am" command to report errors with more information.
15818      *
15819      * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
15820      * @param cn The component name of the instrumentation.
15821      * @param report The error report.
15822      */
reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher, ComponentName cn, String report)15823     private void reportStartInstrumentationFailureLocked(IInstrumentationWatcher watcher,
15824             ComponentName cn, String report) {
15825         Slog.w(TAG, report);
15826         if (watcher != null) {
15827             Bundle results = new Bundle();
15828             results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
15829             results.putString("Error", report);
15830             mInstrumentationReporter.reportStatus(watcher, cn, -1, results);
15831         }
15832     }
15833 
addInstrumentationResultsLocked(ProcessRecord app, Bundle results)15834     void addInstrumentationResultsLocked(ProcessRecord app, Bundle results) {
15835         final ActiveInstrumentation instr = app.getActiveInstrumentation();
15836         if (instr == null) {
15837             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15838             return;
15839         }
15840 
15841         if (!instr.mFinished && results != null) {
15842             if (instr.mCurResults == null) {
15843                 instr.mCurResults = new Bundle(results);
15844             } else {
15845                 instr.mCurResults.putAll(results);
15846             }
15847         }
15848     }
15849 
addInstrumentationResults(IApplicationThread target, Bundle results)15850     public void addInstrumentationResults(IApplicationThread target, Bundle results) {
15851         int userId = UserHandle.getCallingUserId();
15852         // Refuse possible leaked file descriptors
15853         if (results != null && results.hasFileDescriptors()) {
15854             throw new IllegalArgumentException("File descriptors passed in Intent");
15855         }
15856 
15857         synchronized(this) {
15858             ProcessRecord app = getRecordForAppLocked(target);
15859             if (app == null) {
15860                 Slog.w(TAG, "addInstrumentationResults: no app for " + target);
15861                 return;
15862             }
15863             final long origId = Binder.clearCallingIdentity();
15864             addInstrumentationResultsLocked(app, results);
15865             Binder.restoreCallingIdentity(origId);
15866         }
15867     }
15868 
15869     @GuardedBy("this")
finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)15870     void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
15871         final ActiveInstrumentation instr = app.getActiveInstrumentation();
15872         if (instr == null) {
15873             Slog.w(TAG, "finishInstrumentation called on non-instrumented: " + app);
15874             return;
15875         }
15876 
15877         if (!instr.mFinished) {
15878             if (instr.mWatcher != null) {
15879                 Bundle finalResults = instr.mCurResults;
15880                 if (finalResults != null) {
15881                     if (instr.mCurResults != null && results != null) {
15882                         finalResults.putAll(results);
15883                     }
15884                 } else {
15885                     finalResults = results;
15886                 }
15887                 mInstrumentationReporter.reportFinished(instr.mWatcher,
15888                         instr.mClass, resultCode, finalResults);
15889             }
15890 
15891             // Can't call out of the system process with a lock held, so post a message.
15892             if (instr.mUiAutomationConnection != null) {
15893                 mAppOpsService.setAppOpsServiceDelegate(null);
15894                 getPackageManagerInternalLocked().setCheckPermissionDelegate(null);
15895                 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
15896                         instr.mUiAutomationConnection).sendToTarget();
15897             }
15898             instr.mFinished = true;
15899         }
15900 
15901         instr.removeProcess(app);
15902         app.setActiveInstrumentation(null);
15903 
15904         forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId,
15905                 "finished inst");
15906     }
15907 
finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)15908     public void finishInstrumentation(IApplicationThread target,
15909             int resultCode, Bundle results) {
15910         int userId = UserHandle.getCallingUserId();
15911         // Refuse possible leaked file descriptors
15912         if (results != null && results.hasFileDescriptors()) {
15913             throw new IllegalArgumentException("File descriptors passed in Intent");
15914         }
15915 
15916         synchronized(this) {
15917             ProcessRecord app = getRecordForAppLocked(target);
15918             if (app == null) {
15919                 Slog.w(TAG, "finishInstrumentation: no app for " + target);
15920                 return;
15921             }
15922             final long origId = Binder.clearCallingIdentity();
15923             finishInstrumentationLocked(app, resultCode, results);
15924             Binder.restoreCallingIdentity(origId);
15925         }
15926     }
15927 
15928     @Override
getFocusedStackInfo()15929     public StackInfo getFocusedStackInfo() throws RemoteException {
15930         return mActivityTaskManager.getFocusedStackInfo();
15931     }
15932 
15933     @Override
getConfiguration()15934     public Configuration getConfiguration() {
15935         return mActivityTaskManager.getConfiguration();
15936     }
15937 
15938     @Override
suppressResizeConfigChanges(boolean suppress)15939     public void suppressResizeConfigChanges(boolean suppress) throws RemoteException {
15940         mActivityTaskManager.suppressResizeConfigChanges(suppress);
15941     }
15942 
15943     @Override
updatePersistentConfiguration(Configuration values)15944     public void updatePersistentConfiguration(Configuration values) {
15945         enforceCallingPermission(CHANGE_CONFIGURATION, "updatePersistentConfiguration()");
15946         enforceWriteSettingsPermission("updatePersistentConfiguration()");
15947         if (values == null) {
15948             throw new NullPointerException("Configuration must not be null");
15949         }
15950 
15951         int userId = UserHandle.getCallingUserId();
15952 
15953         mActivityTaskManager.updatePersistentConfiguration(values, userId);
15954     }
15955 
enforceWriteSettingsPermission(String func)15956     private void enforceWriteSettingsPermission(String func) {
15957         int uid = Binder.getCallingUid();
15958         if (uid == ROOT_UID) {
15959             return;
15960         }
15961 
15962         if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
15963                 Settings.getPackageNameForUid(mContext, uid), false)) {
15964             return;
15965         }
15966 
15967         String msg = "Permission Denial: " + func + " from pid="
15968                 + Binder.getCallingPid()
15969                 + ", uid=" + uid
15970                 + " requires " + android.Manifest.permission.WRITE_SETTINGS;
15971         Slog.w(TAG, msg);
15972         throw new SecurityException(msg);
15973     }
15974 
15975     @Override
updateConfiguration(Configuration values)15976     public boolean updateConfiguration(Configuration values) {
15977         return mActivityTaskManager.updateConfiguration(values);
15978     }
15979 
15980     @Override
getLaunchedFromUid(IBinder activityToken)15981     public int getLaunchedFromUid(IBinder activityToken) {
15982         return mActivityTaskManager.getLaunchedFromUid(activityToken);
15983     }
15984 
getLaunchedFromPackage(IBinder activityToken)15985     public String getLaunchedFromPackage(IBinder activityToken) {
15986         return mActivityTaskManager.getLaunchedFromPackage(activityToken);
15987     }
15988 
15989     // =========================================================
15990     // LIFETIME MANAGEMENT
15991     // =========================================================
15992 
15993     // Returns whether the app is receiving broadcast.
15994     // If receiving, fetch all broadcast queues which the app is
15995     // the current [or imminent] receiver on.
isReceivingBroadcastLocked(ProcessRecord app, ArraySet<BroadcastQueue> receivingQueues)15996     boolean isReceivingBroadcastLocked(ProcessRecord app,
15997             ArraySet<BroadcastQueue> receivingQueues) {
15998         final int N = app.curReceivers.size();
15999         if (N > 0) {
16000             for (int i = 0; i < N; i++) {
16001                 receivingQueues.add(app.curReceivers.valueAt(i).queue);
16002             }
16003             return true;
16004         }
16005 
16006         // It's not the current receiver, but it might be starting up to become one
16007         for (BroadcastQueue queue : mBroadcastQueues) {
16008             final BroadcastRecord r = queue.mPendingBroadcast;
16009             if (r != null && r.curApp == app) {
16010                 // found it; report which queue it's in
16011                 receivingQueues.add(queue);
16012             }
16013         }
16014 
16015         return !receivingQueues.isEmpty();
16016     }
16017 
startAssociationLocked(int sourceUid, String sourceProcess, int sourceState, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16018     Association startAssociationLocked(int sourceUid, String sourceProcess, int sourceState,
16019             int targetUid, long targetVersionCode, ComponentName targetComponent,
16020             String targetProcess) {
16021         if (!mTrackingAssociations) {
16022             return null;
16023         }
16024         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16025                 = mAssociations.get(targetUid);
16026         if (components == null) {
16027             components = new ArrayMap<>();
16028             mAssociations.put(targetUid, components);
16029         }
16030         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16031         if (sourceUids == null) {
16032             sourceUids = new SparseArray<>();
16033             components.put(targetComponent, sourceUids);
16034         }
16035         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16036         if (sourceProcesses == null) {
16037             sourceProcesses = new ArrayMap<>();
16038             sourceUids.put(sourceUid, sourceProcesses);
16039         }
16040         Association ass = sourceProcesses.get(sourceProcess);
16041         if (ass == null) {
16042             ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent,
16043                     targetProcess);
16044             sourceProcesses.put(sourceProcess, ass);
16045         }
16046         ass.mCount++;
16047         ass.mNesting++;
16048         if (ass.mNesting == 1) {
16049             ass.mStartTime = ass.mLastStateUptime = SystemClock.uptimeMillis();
16050             ass.mLastState = sourceState;
16051         }
16052         return ass;
16053     }
16054 
stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, long targetVersionCode, ComponentName targetComponent, String targetProcess)16055     void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid,
16056             long targetVersionCode, ComponentName targetComponent, String targetProcess) {
16057         if (!mTrackingAssociations) {
16058             return;
16059         }
16060         ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components
16061                 = mAssociations.get(targetUid);
16062         if (components == null) {
16063             return;
16064         }
16065         SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent);
16066         if (sourceUids == null) {
16067             return;
16068         }
16069         ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid);
16070         if (sourceProcesses == null) {
16071             return;
16072         }
16073         Association ass = sourceProcesses.get(sourceProcess);
16074         if (ass == null || ass.mNesting <= 0) {
16075             return;
16076         }
16077         ass.mNesting--;
16078         if (ass.mNesting == 0) {
16079             long uptime = SystemClock.uptimeMillis();
16080             ass.mTime += uptime - ass.mStartTime;
16081             ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16082                     += uptime - ass.mLastStateUptime;
16083             ass.mLastState = ActivityManager.MAX_PROCESS_STATE + 2;
16084         }
16085     }
16086 
noteUidProcessState(final int uid, final int state)16087     void noteUidProcessState(final int uid, final int state) {
16088         mBatteryStatsService.noteUidProcessState(uid, state);
16089         mAppOpsService.updateUidProcState(uid, state);
16090         if (mTrackingAssociations) {
16091             for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) {
16092                 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents
16093                         = mAssociations.valueAt(i1);
16094                 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) {
16095                     SparseArray<ArrayMap<String, Association>> sourceUids
16096                             = targetComponents.valueAt(i2);
16097                     ArrayMap<String, Association> sourceProcesses = sourceUids.get(uid);
16098                     if (sourceProcesses != null) {
16099                         for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) {
16100                             Association ass = sourceProcesses.valueAt(i4);
16101                             if (ass.mNesting >= 1) {
16102                                 // currently associated
16103                                 long uptime = SystemClock.uptimeMillis();
16104                                 ass.mStateTimes[ass.mLastState-ActivityManager.MIN_PROCESS_STATE]
16105                                         += uptime - ass.mLastStateUptime;
16106                                 ass.mLastState = state;
16107                                 ass.mLastStateUptime = uptime;
16108                             }
16109                         }
16110                     }
16111                 }
16112             }
16113         }
16114     }
16115 
16116     private static final class RecordPssRunnable implements Runnable {
16117         private final ActivityManagerService mService;
16118         private final ProcessRecord mProc;
16119         private final File mHeapdumpFile;
16120 
RecordPssRunnable(ActivityManagerService service, ProcessRecord proc, File heapdumpFile)16121         RecordPssRunnable(ActivityManagerService service, ProcessRecord proc, File heapdumpFile) {
16122             this.mService = service;
16123             this.mProc = proc;
16124             this.mHeapdumpFile = heapdumpFile;
16125         }
16126 
16127         @Override
run()16128         public void run() {
16129             mService.revokeUriPermission(ActivityThread.currentActivityThread()
16130                             .getApplicationThread(),
16131                     null, DumpHeapActivity.JAVA_URI,
16132                     Intent.FLAG_GRANT_READ_URI_PERMISSION
16133                             | Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
16134                     UserHandle.myUserId());
16135             ParcelFileDescriptor fd = null;
16136             try {
16137                 mHeapdumpFile.delete();
16138                 fd = ParcelFileDescriptor.open(mHeapdumpFile,
16139                         ParcelFileDescriptor.MODE_CREATE
16140                         | ParcelFileDescriptor.MODE_TRUNCATE
16141                         | ParcelFileDescriptor.MODE_WRITE_ONLY
16142                         | ParcelFileDescriptor.MODE_APPEND);
16143                 IApplicationThread thread = mProc.thread;
16144                 if (thread != null) {
16145                     try {
16146                         if (DEBUG_PSS) {
16147                             Slog.d(TAG_PSS, "Requesting dump heap from "
16148                                     + mProc + " to " + mHeapdumpFile);
16149                         }
16150                         thread.dumpHeap(/* managed= */ true,
16151                                 /* mallocInfo= */ false, /* runGc= */ false,
16152                                 mHeapdumpFile.toString(), fd,
16153                                 /* finishCallback= */ null);
16154                     } catch (RemoteException e) {
16155                     }
16156                 }
16157             } catch (FileNotFoundException e) {
16158                 e.printStackTrace();
16159             } finally {
16160                 if (fd != null) {
16161                     try {
16162                         fd.close();
16163                     } catch (IOException e) {
16164                     }
16165                 }
16166             }
16167         }
16168     }
16169 
16170     /**
16171      * Record new PSS sample for a process.
16172      */
recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss, long rss, int statType, long pssDuration, long now)16173     void recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long swapPss,
16174             long rss, int statType, long pssDuration, long now) {
16175         EventLogTags.writeAmPss(proc.pid, proc.uid, proc.processName, pss * 1024, uss * 1024,
16176                 swapPss * 1024, rss * 1024, statType, procState, pssDuration);
16177         proc.lastPssTime = now;
16178         proc.baseProcessTracker.addPss(
16179                 pss, uss, rss, true, statType, pssDuration, proc.pkgList.mPkgList);
16180         for (int ipkg = proc.pkgList.mPkgList.size() - 1; ipkg >= 0; ipkg--) {
16181             ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg);
16182             StatsLog.write(StatsLog.PROCESS_MEMORY_STAT_REPORTED,
16183                     proc.info.uid,
16184                     holder.state.getName(),
16185                     holder.state.getPackage(),
16186                     pss, uss, rss, statType, pssDuration,
16187                     holder.appVersion);
16188         }
16189         if (DEBUG_PSS) Slog.d(TAG_PSS,
16190                 "pss of " + proc.toShortString() + ": " + pss + " lastPss=" + proc.lastPss
16191                 + " state=" + ProcessList.makeProcStateString(procState));
16192         if (proc.initialIdlePss == 0) {
16193             proc.initialIdlePss = pss;
16194         }
16195         proc.lastPss = pss;
16196         proc.lastSwapPss = swapPss;
16197         if (procState >= ActivityManager.PROCESS_STATE_HOME) {
16198             proc.lastCachedPss = pss;
16199             proc.lastCachedSwapPss = swapPss;
16200         }
16201 
16202         final SparseArray<Pair<Long, String>> watchUids
16203                 = mMemWatchProcesses.getMap().get(proc.processName);
16204         Long check = null;
16205         if (watchUids != null) {
16206             Pair<Long, String> val = watchUids.get(proc.uid);
16207             if (val == null) {
16208                 val = watchUids.get(0);
16209             }
16210             if (val != null) {
16211                 check = val.first;
16212             }
16213         }
16214         if (check != null) {
16215             if ((pss * 1024) >= check && proc.thread != null && mMemWatchDumpProcName == null) {
16216                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
16217                 if (!isDebuggable) {
16218                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
16219                         isDebuggable = true;
16220                     }
16221                 }
16222                 if (isDebuggable) {
16223                     Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting");
16224                     startHeapDumpLocked(proc, false);
16225                 } else {
16226                     Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check
16227                             + ", but debugging not enabled");
16228                 }
16229             }
16230         }
16231     }
16232 
startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated)16233     private void startHeapDumpLocked(ProcessRecord proc, boolean isUserInitiated) {
16234         final File heapdumpFile = DumpHeapProvider.getJavaFile();
16235         mMemWatchDumpProcName = proc.processName;
16236         mMemWatchDumpFile = heapdumpFile.toString();
16237         mMemWatchDumpPid = proc.pid;
16238         mMemWatchDumpUid = proc.uid;
16239         mMemWatchIsUserInitiated = isUserInitiated;
16240         BackgroundThread.getHandler().post(new RecordPssRunnable(this, proc, heapdumpFile));
16241     }
16242 
16243     /**
16244      * Schedule PSS collection of a process.
16245      */
requestPssLocked(ProcessRecord proc, int procState)16246     boolean requestPssLocked(ProcessRecord proc, int procState) {
16247         if (mPendingPssProcesses.contains(proc)) {
16248             return false;
16249         }
16250         if (mPendingPssProcesses.size() == 0) {
16251             final long deferral = (mPssDeferralTime > 0 && mActivityStartingNesting.get() > 0)
16252                     ? mPssDeferralTime : 0;
16253             if (DEBUG_PSS && deferral > 0) {
16254                 Slog.d(TAG_PSS, "requestPssLocked() deferring PSS request by "
16255                         + deferral + " ms");
16256             }
16257             mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, deferral);
16258         }
16259         if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of: " + proc);
16260         proc.pssProcState = procState;
16261         proc.pssStatType = ProcessStats.ADD_PSS_INTERNAL_SINGLE;
16262         mPendingPssProcesses.add(proc);
16263         return true;
16264     }
16265 
16266     /**
16267      * Re-defer a posted PSS collection pass, if one exists.  Assumes deferral is
16268      * currently active policy when called.
16269      */
deferPssIfNeededLocked()16270     private void deferPssIfNeededLocked() {
16271         if (mPendingPssProcesses.size() > 0) {
16272             mBgHandler.removeMessages(COLLECT_PSS_BG_MSG);
16273             mBgHandler.sendEmptyMessageDelayed(COLLECT_PSS_BG_MSG, mPssDeferralTime);
16274         }
16275     }
16276 
deferPssForActivityStart()16277     private void deferPssForActivityStart() {
16278         synchronized (ActivityManagerService.this) {
16279             if (mPssDeferralTime > 0) {
16280                 if (DEBUG_PSS) {
16281                     Slog.d(TAG_PSS, "Deferring PSS collection for activity start");
16282                 }
16283                 deferPssIfNeededLocked();
16284                 mActivityStartingNesting.getAndIncrement();
16285                 mBgHandler.sendEmptyMessageDelayed(STOP_DEFERRING_PSS_MSG, mPssDeferralTime);
16286             }
16287         }
16288     }
16289 
16290     /**
16291      * Schedule PSS collection of all processes.
16292      */
requestPssAllProcsLocked(long now, boolean always, boolean memLowered)16293     void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) {
16294         if (!always) {
16295             if (now < (mLastFullPssTime +
16296                     (memLowered ? mConstants.FULL_PSS_LOWERED_INTERVAL
16297                             : mConstants.FULL_PSS_MIN_INTERVAL))) {
16298                 return;
16299             }
16300         }
16301         if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting pss of all procs!  memLowered=" + memLowered);
16302         mLastFullPssTime = now;
16303         mFullPssPending = true;
16304         for (int i = mPendingPssProcesses.size() - 1; i >= 0; i--) {
16305             ProcessList.abortNextPssTime(mPendingPssProcesses.get(i).procStateMemTracker);;
16306         }
16307         mPendingPssProcesses.ensureCapacity(mProcessList.getLruSizeLocked());
16308         mPendingPssProcesses.clear();
16309         for (int i = mProcessList.getLruSizeLocked() - 1; i >= 0; i--) {
16310             ProcessRecord app = mProcessList.mLruProcesses.get(i);
16311             if (app.thread == null || app.getCurProcState() == PROCESS_STATE_NONEXISTENT) {
16312                 continue;
16313             }
16314             if (memLowered || (always && now >
16315                             app.lastStateTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE)
16316                     || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) {
16317                 app.pssProcState = app.setProcState;
16318                 app.pssStatType = always ? ProcessStats.ADD_PSS_INTERNAL_ALL_POLL
16319                         : ProcessStats.ADD_PSS_INTERNAL_ALL_MEM;
16320                 app.nextPssTime = ProcessList.computeNextPssTime(app.getCurProcState(),
16321                         app.procStateMemTracker, mTestPssMode, mAtmInternal.isSleeping(), now);
16322                 mPendingPssProcesses.add(app);
16323             }
16324         }
16325         if (!mBgHandler.hasMessages(COLLECT_PSS_BG_MSG)) {
16326             mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
16327         }
16328     }
16329 
setTestPssMode(boolean enabled)16330     public void setTestPssMode(boolean enabled) {
16331         synchronized (this) {
16332             mTestPssMode = enabled;
16333             if (enabled) {
16334                 // Whenever we enable the mode, we want to take a snapshot all of current
16335                 // process mem use.
16336                 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, true);
16337             }
16338         }
16339     }
16340 
16341     /**
16342      * Ask a given process to GC right now.
16343      */
performAppGcLocked(ProcessRecord app)16344     final void performAppGcLocked(ProcessRecord app) {
16345         try {
16346             app.lastRequestedGc = SystemClock.uptimeMillis();
16347             if (app.thread != null) {
16348                 if (app.reportLowMemory) {
16349                     app.reportLowMemory = false;
16350                     app.thread.scheduleLowMemory();
16351                 } else {
16352                     app.thread.processInBackground();
16353                 }
16354             }
16355         } catch (Exception e) {
16356             // whatever.
16357         }
16358     }
16359 
16360     /**
16361      * Returns true if things are idle enough to perform GCs.
16362      */
canGcNowLocked()16363     private final boolean canGcNowLocked() {
16364         for (BroadcastQueue q : mBroadcastQueues) {
16365             if (!q.mParallelBroadcasts.isEmpty() || !q.mDispatcher.isEmpty()) {
16366                 return false;
16367             }
16368         }
16369         return mAtmInternal.canGcNow();
16370     }
16371 
16372     /**
16373      * Perform GCs on all processes that are waiting for it, but only
16374      * if things are idle.
16375      */
performAppGcsLocked()16376     final void performAppGcsLocked() {
16377         final int N = mProcessesToGc.size();
16378         if (N <= 0) {
16379             return;
16380         }
16381         if (canGcNowLocked()) {
16382             while (mProcessesToGc.size() > 0) {
16383                 ProcessRecord proc = mProcessesToGc.remove(0);
16384                 if (proc.getCurRawAdj() > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
16385                     if ((proc.lastRequestedGc+mConstants.GC_MIN_INTERVAL)
16386                             <= SystemClock.uptimeMillis()) {
16387                         // To avoid spamming the system, we will GC processes one
16388                         // at a time, waiting a few seconds between each.
16389                         performAppGcLocked(proc);
16390                         scheduleAppGcsLocked();
16391                         return;
16392                     } else {
16393                         // It hasn't been long enough since we last GCed this
16394                         // process...  put it in the list to wait for its time.
16395                         addProcessToGcListLocked(proc);
16396                         break;
16397                     }
16398                 }
16399             }
16400 
16401             scheduleAppGcsLocked();
16402         }
16403     }
16404 
16405     /**
16406      * If all looks good, perform GCs on all processes waiting for them.
16407      */
performAppGcsIfAppropriateLocked()16408     final void performAppGcsIfAppropriateLocked() {
16409         if (canGcNowLocked()) {
16410             performAppGcsLocked();
16411             return;
16412         }
16413         // Still not idle, wait some more.
16414         scheduleAppGcsLocked();
16415     }
16416 
16417     /**
16418      * Schedule the execution of all pending app GCs.
16419      */
scheduleAppGcsLocked()16420     final void scheduleAppGcsLocked() {
16421         mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
16422 
16423         if (mProcessesToGc.size() > 0) {
16424             // Schedule a GC for the time to the next process.
16425             ProcessRecord proc = mProcessesToGc.get(0);
16426             Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
16427 
16428             long when = proc.lastRequestedGc + mConstants.GC_MIN_INTERVAL;
16429             long now = SystemClock.uptimeMillis();
16430             if (when < (now+mConstants.GC_TIMEOUT)) {
16431                 when = now + mConstants.GC_TIMEOUT;
16432             }
16433             mHandler.sendMessageAtTime(msg, when);
16434         }
16435     }
16436 
16437     /**
16438      * Add a process to the array of processes waiting to be GCed.  Keeps the
16439      * list in sorted order by the last GC time.  The process can't already be
16440      * on the list.
16441      */
addProcessToGcListLocked(ProcessRecord proc)16442     final void addProcessToGcListLocked(ProcessRecord proc) {
16443         boolean added = false;
16444         for (int i=mProcessesToGc.size()-1; i>=0; i--) {
16445             if (mProcessesToGc.get(i).lastRequestedGc <
16446                     proc.lastRequestedGc) {
16447                 added = true;
16448                 mProcessesToGc.add(i+1, proc);
16449                 break;
16450             }
16451         }
16452         if (!added) {
16453             mProcessesToGc.add(0, proc);
16454         }
16455     }
16456 
16457     /**
16458      * Set up to ask a process to GC itself.  This will either do it
16459      * immediately, or put it on the list of processes to gc the next
16460      * time things are idle.
16461      */
scheduleAppGcLocked(ProcessRecord app)16462     final void scheduleAppGcLocked(ProcessRecord app) {
16463         long now = SystemClock.uptimeMillis();
16464         if ((app.lastRequestedGc+mConstants.GC_MIN_INTERVAL) > now) {
16465             return;
16466         }
16467         if (!mProcessesToGc.contains(app)) {
16468             addProcessToGcListLocked(app);
16469             scheduleAppGcsLocked();
16470         }
16471     }
16472 
checkExcessivePowerUsageLocked()16473     final void checkExcessivePowerUsageLocked() {
16474         updateCpuStatsNow();
16475 
16476         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
16477         boolean doCpuKills = true;
16478         if (mLastPowerCheckUptime == 0) {
16479             doCpuKills = false;
16480         }
16481         final long curUptime = SystemClock.uptimeMillis();
16482         final long uptimeSince = curUptime - mLastPowerCheckUptime;
16483         mLastPowerCheckUptime = curUptime;
16484         int i = mProcessList.mLruProcesses.size();
16485         while (i > 0) {
16486             i--;
16487             ProcessRecord app = mProcessList.mLruProcesses.get(i);
16488             if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
16489                 if (app.lastCpuTime <= 0) {
16490                     continue;
16491                 }
16492                 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
16493                 if (DEBUG_POWER) {
16494                     StringBuilder sb = new StringBuilder(128);
16495                     sb.append("CPU for ");
16496                     app.toShortString(sb);
16497                     sb.append(": over ");
16498                     TimeUtils.formatDuration(uptimeSince, sb);
16499                     sb.append(" used ");
16500                     TimeUtils.formatDuration(cputimeUsed, sb);
16501                     sb.append(" (");
16502                     sb.append((cputimeUsed*100)/uptimeSince);
16503                     sb.append("%)");
16504                     Slog.i(TAG_POWER, sb.toString());
16505                 }
16506                 // If the process has used too much CPU over the last duration, the
16507                 // user probably doesn't want this, so kill!
16508                 if (doCpuKills && uptimeSince > 0) {
16509                     // What is the limit for this process?
16510                     int cpuLimit;
16511                     long checkDur = curUptime - app.getWhenUnimportant();
16512                     if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
16513                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
16514                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*2)
16515                             || app.setProcState <= ActivityManager.PROCESS_STATE_HOME) {
16516                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
16517                     } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*3)) {
16518                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
16519                     } else {
16520                         cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
16521                     }
16522                     if (((cputimeUsed*100)/uptimeSince) >= cpuLimit) {
16523                         synchronized (stats) {
16524                             stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
16525                                     uptimeSince, cputimeUsed);
16526                         }
16527                         app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince
16528                                 + " dur=" + checkDur + " limit=" + cpuLimit, true);
16529                         app.baseProcessTracker.reportExcessiveCpu(app.pkgList.mPkgList);
16530                         for (int ipkg = app.pkgList.size() - 1; ipkg >= 0; ipkg--) {
16531                             ProcessStats.ProcessStateHolder holder = app.pkgList.valueAt(ipkg);
16532                             StatsLog.write(StatsLog.EXCESSIVE_CPU_USAGE_REPORTED,
16533                                     app.info.uid,
16534                                     holder.state.getName(),
16535                                     holder.state.getPackage(),
16536                                     holder.appVersion);
16537                         }
16538                     }
16539                 }
16540                 app.lastCpuTime = app.curCpuTime;
16541             }
16542         }
16543     }
16544 
isEphemeralLocked(int uid)16545     private boolean isEphemeralLocked(int uid) {
16546         String packages[] = mContext.getPackageManager().getPackagesForUid(uid);
16547         if (packages == null || packages.length != 1) { // Ephemeral apps cannot share uid
16548             return false;
16549         }
16550         return getPackageManagerInternalLocked().isPackageEphemeral(UserHandle.getUserId(uid),
16551                 packages[0]);
16552     }
16553 
16554     @VisibleForTesting
enqueueUidChangeLocked(UidRecord uidRec, int uid, int change)16555     final void enqueueUidChangeLocked(UidRecord uidRec, int uid, int change) {
16556         final UidRecord.ChangeItem pendingChange;
16557         if (uidRec == null || uidRec.pendingChange == null) {
16558             if (mPendingUidChanges.size() == 0) {
16559                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
16560                         "*** Enqueueing dispatch uid changed!");
16561                 mUiHandler.obtainMessage(DISPATCH_UIDS_CHANGED_UI_MSG).sendToTarget();
16562             }
16563             final int NA = mAvailUidChanges.size();
16564             if (NA > 0) {
16565                 pendingChange = mAvailUidChanges.remove(NA-1);
16566                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
16567                         "Retrieving available item: " + pendingChange);
16568             } else {
16569                 pendingChange = new UidRecord.ChangeItem();
16570                 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS,
16571                         "Allocating new item: " + pendingChange);
16572             }
16573             if (uidRec != null) {
16574                 uidRec.pendingChange = pendingChange;
16575                 if ((change & UidRecord.CHANGE_GONE) != 0 && !uidRec.idle) {
16576                     // If this uid is going away, and we haven't yet reported it is gone,
16577                     // then do so now.
16578                     change |= UidRecord.CHANGE_IDLE;
16579                 }
16580             } else if (uid < 0) {
16581                 throw new IllegalArgumentException("No UidRecord or uid");
16582             }
16583             pendingChange.uidRecord = uidRec;
16584             pendingChange.uid = uidRec != null ? uidRec.uid : uid;
16585             mPendingUidChanges.add(pendingChange);
16586         } else {
16587             pendingChange = uidRec.pendingChange;
16588             // If there is no change in idle or active state, then keep whatever was pending.
16589             if ((change & (UidRecord.CHANGE_IDLE | UidRecord.CHANGE_ACTIVE)) == 0) {
16590                 change |= (pendingChange.change & (UidRecord.CHANGE_IDLE
16591                         | UidRecord.CHANGE_ACTIVE));
16592             }
16593             // If there is no change in cached or uncached state, then keep whatever was pending.
16594             if ((change & (UidRecord.CHANGE_CACHED | UidRecord.CHANGE_UNCACHED)) == 0) {
16595                 change |= (pendingChange.change & (UidRecord.CHANGE_CACHED
16596                         | UidRecord.CHANGE_UNCACHED));
16597             }
16598             // If this is a report of the UID being gone, then we shouldn't keep any previous
16599             // report of it being active or cached.  (That is, a gone uid is never active,
16600             // and never cached.)
16601             if ((change & UidRecord.CHANGE_GONE) != 0) {
16602                 change &= ~(UidRecord.CHANGE_ACTIVE | UidRecord.CHANGE_CACHED);
16603                 if (!uidRec.idle) {
16604                     // If this uid is going away, and we haven't yet reported it is gone,
16605                     // then do so now.
16606                     change |= UidRecord.CHANGE_IDLE;
16607                 }
16608             }
16609         }
16610         pendingChange.change = change;
16611         pendingChange.processState = uidRec != null ? uidRec.setProcState : PROCESS_STATE_NONEXISTENT;
16612         pendingChange.ephemeral = uidRec != null ? uidRec.ephemeral : isEphemeralLocked(uid);
16613         pendingChange.procStateSeq = uidRec != null ? uidRec.curProcStateSeq : 0;
16614         if (uidRec != null) {
16615             uidRec.lastReportedChange = change;
16616             uidRec.updateLastDispatchedProcStateSeq(change);
16617         }
16618 
16619         // Directly update the power manager, since we sit on top of it and it is critical
16620         // it be kept in sync (so wake locks will be held as soon as appropriate).
16621         if (mLocalPowerManager != null) {
16622             // TO DO: dispatch cached/uncached changes here, so we don't need to report
16623             // all proc state changes.
16624             if ((change & UidRecord.CHANGE_ACTIVE) != 0) {
16625                 mLocalPowerManager.uidActive(pendingChange.uid);
16626             }
16627             if ((change & UidRecord.CHANGE_IDLE) != 0) {
16628                 mLocalPowerManager.uidIdle(pendingChange.uid);
16629             }
16630             if ((change & UidRecord.CHANGE_GONE) != 0) {
16631                 mLocalPowerManager.uidGone(pendingChange.uid);
16632             } else {
16633                 mLocalPowerManager.updateUidProcState(pendingChange.uid,
16634                         pendingChange.processState);
16635             }
16636         }
16637     }
16638 
maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, String authority)16639     private void maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName,
16640             String authority) {
16641         if (app == null) return;
16642         if (app.getCurProcState() <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
16643             UserState userState = mUserController.getStartedUserState(app.userId);
16644             if (userState == null) return;
16645             final long now = SystemClock.elapsedRealtime();
16646             Long lastReported = userState.mProviderLastReportedFg.get(authority);
16647             if (lastReported == null || lastReported < now - 60 * 1000L) {
16648                 if (mSystemReady) {
16649                     // Cannot touch the user stats if not system ready
16650                     mUsageStatsService.reportContentProviderUsage(
16651                             authority, providerPkgName, app.userId);
16652                 }
16653                 userState.mProviderLastReportedFg.put(authority, now);
16654             }
16655         }
16656     }
16657 
setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now)16658     final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) {
16659         if (proc.thread != null && proc.baseProcessTracker != null) {
16660             proc.baseProcessTracker.setState(
16661                     proc.getReportedProcState(), memFactor, now, proc.pkgList.mPkgList);
16662         }
16663     }
16664 
16665     @GuardedBy("this")
updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, int fgServiceTypes, boolean oomAdj)16666     final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
16667             int fgServiceTypes, boolean oomAdj) {
16668 
16669         if (isForeground != proc.hasForegroundServices()
16670                 || proc.getForegroundServiceTypes() != fgServiceTypes) {
16671             proc.setHasForegroundServices(isForeground, fgServiceTypes);
16672             ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
16673                     proc.info.uid);
16674             if (isForeground) {
16675                 if (curProcs == null) {
16676                     curProcs = new ArrayList<ProcessRecord>();
16677                     mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
16678                 }
16679                 if (!curProcs.contains(proc)) {
16680                     curProcs.add(proc);
16681                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
16682                             proc.info.packageName, proc.info.uid);
16683                 }
16684             } else {
16685                 if (curProcs != null) {
16686                     if (curProcs.remove(proc)) {
16687                         mBatteryStatsService.noteEvent(
16688                                 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
16689                                 proc.info.packageName, proc.info.uid);
16690                         if (curProcs.size() <= 0) {
16691                             mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
16692                         }
16693                     }
16694                 }
16695             }
16696 
16697             proc.setReportedForegroundServiceTypes(fgServiceTypes);
16698             ProcessChangeItem item = enqueueProcessChangeItemLocked(proc.pid, proc.info.uid);
16699             item.changes = ProcessChangeItem.CHANGE_FOREGROUND_SERVICES;
16700             item.foregroundServiceTypes = fgServiceTypes;
16701 
16702             if (oomAdj) {
16703                 updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
16704             }
16705         }
16706     }
16707 
16708     // TODO(b/111541062): This method is only used for updating OOM adjustments. We need to update
16709     // the logic there and in mBatteryStatsService to make them aware of multiple resumed activities
getTopAppLocked()16710     ProcessRecord getTopAppLocked() {
16711         final WindowProcessController wpc = mAtmInternal != null ? mAtmInternal.getTopApp() : null;
16712         final ProcessRecord r = wpc != null ? (ProcessRecord) wpc.mOwner : null;
16713         String pkg;
16714         int uid;
16715         if (r != null) {
16716             pkg = r.processName;
16717             uid = r.info.uid;
16718         } else {
16719             pkg = null;
16720             uid = -1;
16721         }
16722         // Has the UID or resumed package name changed?
16723         if (uid != mCurResumedUid || (pkg != mCurResumedPackage
16724                 && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
16725 
16726             final long identity = Binder.clearCallingIdentity();
16727             try {
16728                 if (mCurResumedPackage != null) {
16729                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
16730                             mCurResumedPackage, mCurResumedUid);
16731                 }
16732                 mCurResumedPackage = pkg;
16733                 mCurResumedUid = uid;
16734                 if (mCurResumedPackage != null) {
16735                     mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
16736                             mCurResumedPackage, mCurResumedUid);
16737                 }
16738             } finally {
16739                 Binder.restoreCallingIdentity(identity);
16740             }
16741 
16742         }
16743         return r;
16744     }
16745 
16746     /**
16747      * Update OomAdj for a specific process.
16748      * @param app The process to update
16749      * @param oomAdjAll If it's ok to call updateOomAdjLocked() for all running apps
16750      *                  if necessary, or skip.
16751      * @param oomAdjReason
16752      * @return whether updateOomAdjLocked(app) was successful.
16753      */
16754     @GuardedBy("this")
updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll, String oomAdjReason)16755     final boolean updateOomAdjLocked(ProcessRecord app, boolean oomAdjAll,
16756             String oomAdjReason) {
16757         return mOomAdjuster.updateOomAdjLocked(app, oomAdjAll, oomAdjReason);
16758     }
16759 
16760     static final class ProcStatsRunnable implements Runnable {
16761         private final ActivityManagerService mService;
16762         private final ProcessStatsService mProcessStats;
16763 
ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats)16764         ProcStatsRunnable(ActivityManagerService service, ProcessStatsService mProcessStats) {
16765             this.mService = service;
16766             this.mProcessStats = mProcessStats;
16767         }
16768 
run()16769         @Override public void run() {
16770             synchronized (mService) {
16771                 mProcessStats.writeStateAsyncLocked();
16772             }
16773         }
16774     }
16775 
16776     @GuardedBy("this")
updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming)16777     final boolean updateLowMemStateLocked(int numCached, int numEmpty, int numTrimming) {
16778         final int N = mProcessList.getLruSizeLocked();
16779         final long now = SystemClock.uptimeMillis();
16780         int memFactor;
16781         if (mLowMemDetector != null && mLowMemDetector.isAvailable()) {
16782             memFactor = mLowMemDetector.getMemFactor();
16783         } else {
16784             // Now determine the memory trimming level of background processes.
16785             // Unfortunately we need to start at the back of the list to do this
16786             // properly.  We only do this if the number of background apps we
16787             // are managing to keep around is less than half the maximum we desire;
16788             // if we are keeping a good number around, we'll let them use whatever
16789             // memory they want.
16790             if (numCached <= mConstants.CUR_TRIM_CACHED_PROCESSES
16791                 && numEmpty <= mConstants.CUR_TRIM_EMPTY_PROCESSES) {
16792                 final int numCachedAndEmpty = numCached + numEmpty;
16793                 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
16794                     memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL;
16795                 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
16796                     memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW;
16797                 } else {
16798                     memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE;
16799                 }
16800             } else {
16801                 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
16802             }
16803         }
16804         // We always allow the memory level to go up (better).  We only allow it to go
16805         // down if we are in a state where that is allowed, *and* the total number of processes
16806         // has gone down since last time.
16807         if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "oom: memFactor=" + memFactor
16808                 + " last=" + mLastMemoryLevel + " allowLow=" + mAllowLowerMemLevel
16809                 + " numProcs=" + mProcessList.getLruSizeLocked() + " last=" + mLastNumProcesses);
16810         if (memFactor > mLastMemoryLevel) {
16811             if (!mAllowLowerMemLevel || mProcessList.getLruSizeLocked() >= mLastNumProcesses) {
16812                 memFactor = mLastMemoryLevel;
16813                 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "Keeping last mem factor!");
16814             }
16815         }
16816         if (memFactor != mLastMemoryLevel) {
16817             EventLogTags.writeAmMemFactor(memFactor, mLastMemoryLevel);
16818             StatsLog.write(StatsLog.MEMORY_FACTOR_STATE_CHANGED, memFactor);
16819         }
16820         mLastMemoryLevel = memFactor;
16821         mLastNumProcesses = mProcessList.getLruSizeLocked();
16822         boolean allChanged = mProcessStats.setMemFactorLocked(
16823                 memFactor, mAtmInternal != null ? !mAtmInternal.isSleeping() : true, now);
16824         final int trackerMemFactor = mProcessStats.getMemFactorLocked();
16825         if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) {
16826             if (mLowRamStartTime == 0) {
16827                 mLowRamStartTime = now;
16828             }
16829             int step = 0;
16830             int fgTrimLevel;
16831             switch (memFactor) {
16832                 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
16833                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
16834                     break;
16835                 case ProcessStats.ADJ_MEM_FACTOR_LOW:
16836                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
16837                     break;
16838                 default:
16839                     fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
16840                     break;
16841             }
16842             int factor = numTrimming/3;
16843             int minFactor = 2;
16844             if (mAtmInternal.getHomeProcess() != null) minFactor++;
16845             if (mAtmInternal.getPreviousProcess() != null) minFactor++;
16846             if (factor < minFactor) factor = minFactor;
16847             int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
16848             for (int i=N-1; i>=0; i--) {
16849                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
16850                 if (allChanged || app.procStateChanged) {
16851                     setProcessTrackerStateLocked(app, trackerMemFactor, now);
16852                     app.procStateChanged = false;
16853                 }
16854                 if (app.getCurProcState() >= ActivityManager.PROCESS_STATE_HOME
16855                         && !app.killedByAm) {
16856                     if (app.trimMemoryLevel < curLevel && app.thread != null) {
16857                         try {
16858                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16859                                     "Trimming memory of " + app.processName + " to " + curLevel);
16860                             app.thread.scheduleTrimMemory(curLevel);
16861                         } catch (RemoteException e) {
16862                         }
16863                     }
16864                     app.trimMemoryLevel = curLevel;
16865                     step++;
16866                     if (step >= factor) {
16867                         step = 0;
16868                         switch (curLevel) {
16869                             case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
16870                                 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
16871                                 break;
16872                             case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
16873                                 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
16874                                 break;
16875                         }
16876                     }
16877                 } else if (app.getCurProcState() == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
16878                         && !app.killedByAm) {
16879                     if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
16880                             && app.thread != null) {
16881                         try {
16882                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16883                                     "Trimming memory of heavy-weight " + app.processName
16884                                     + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
16885                             app.thread.scheduleTrimMemory(
16886                                     ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
16887                         } catch (RemoteException e) {
16888                         }
16889                     }
16890                     app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
16891                 } else {
16892                     if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
16893                             || app.systemNoUi) && app.hasPendingUiClean()) {
16894                         // If this application is now in the background and it
16895                         // had done UI, then give it the special trim level to
16896                         // have it free UI resources.
16897                         final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
16898                         if (app.trimMemoryLevel < level && app.thread != null) {
16899                             try {
16900                                 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16901                                         "Trimming memory of bg-ui " + app.processName
16902                                         + " to " + level);
16903                                 app.thread.scheduleTrimMemory(level);
16904                             } catch (RemoteException e) {
16905                             }
16906                         }
16907                         app.setPendingUiClean(false);
16908                     }
16909                     if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
16910                         try {
16911                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16912                                     "Trimming memory of fg " + app.processName
16913                                     + " to " + fgTrimLevel);
16914                             app.thread.scheduleTrimMemory(fgTrimLevel);
16915                         } catch (RemoteException e) {
16916                         }
16917                     }
16918                     app.trimMemoryLevel = fgTrimLevel;
16919                 }
16920             }
16921         } else {
16922             if (mLowRamStartTime != 0) {
16923                 mLowRamTimeSinceLastIdle += now - mLowRamStartTime;
16924                 mLowRamStartTime = 0;
16925             }
16926             for (int i=N-1; i>=0; i--) {
16927                 ProcessRecord app = mProcessList.mLruProcesses.get(i);
16928                 if (allChanged || app.procStateChanged) {
16929                     setProcessTrackerStateLocked(app, trackerMemFactor, now);
16930                     app.procStateChanged = false;
16931                 }
16932                 if ((app.getCurProcState() >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
16933                         || app.systemNoUi) && app.hasPendingUiClean()) {
16934                     if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
16935                             && app.thread != null) {
16936                         try {
16937                             if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ,
16938                                     "Trimming memory of ui hidden " + app.processName
16939                                     + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
16940                             app.thread.scheduleTrimMemory(
16941                                     ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
16942                         } catch (RemoteException e) {
16943                         }
16944                     }
16945                     app.setPendingUiClean(false);
16946                 }
16947                 app.trimMemoryLevel = 0;
16948             }
16949         }
16950         return allChanged;
16951     }
16952 
16953     @GuardedBy("this")
updateOomAdjLocked(String oomAdjReason)16954     final void updateOomAdjLocked(String oomAdjReason) {
16955         mOomAdjuster.updateOomAdjLocked(oomAdjReason);
16956     }
16957 
16958     @Override
makePackageIdle(String packageName, int userId)16959     public void makePackageIdle(String packageName, int userId) {
16960         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
16961                 != PackageManager.PERMISSION_GRANTED) {
16962             String msg = "Permission Denial: makePackageIdle() from pid="
16963                     + Binder.getCallingPid()
16964                     + ", uid=" + Binder.getCallingUid()
16965                     + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
16966             Slog.w(TAG, msg);
16967             throw new SecurityException(msg);
16968         }
16969         final int callingPid = Binder.getCallingPid();
16970         userId = mUserController.handleIncomingUser(callingPid, Binder.getCallingUid(),
16971                 userId, true, ALLOW_FULL_ONLY, "makePackageIdle", null);
16972         long callingId = Binder.clearCallingIdentity();
16973         synchronized(this) {
16974             try {
16975                 IPackageManager pm = AppGlobals.getPackageManager();
16976                 int pkgUid = -1;
16977                 try {
16978                     pkgUid = pm.getPackageUid(packageName, MATCH_UNINSTALLED_PACKAGES
16979                             | MATCH_DEBUG_TRIAGED_MISSING, UserHandle.USER_SYSTEM);
16980                 } catch (RemoteException e) {
16981                 }
16982                 if (pkgUid == -1) {
16983                     throw new IllegalArgumentException("Unknown package name " + packageName);
16984                 }
16985 
16986                 if (mLocalPowerManager != null) {
16987                     mLocalPowerManager.startUidChanges();
16988                 }
16989                 final int appId = UserHandle.getAppId(pkgUid);
16990                 final int N = mProcessList.mActiveUids.size();
16991                 for (int i = N - 1; i >= 0; i--) {
16992                     final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
16993                     final long bgTime = uidRec.lastBackgroundTime;
16994                     if (bgTime > 0 && !uidRec.idle) {
16995                         if (UserHandle.getAppId(uidRec.uid) == appId) {
16996                             if (userId == UserHandle.USER_ALL ||
16997                                     userId == UserHandle.getUserId(uidRec.uid)) {
16998                                 EventLogTags.writeAmUidIdle(uidRec.uid);
16999                                 uidRec.idle = true;
17000                                 uidRec.setIdle = true;
17001                                 Slog.w(TAG, "Idling uid " + UserHandle.formatUid(uidRec.uid)
17002                                         + " from package " + packageName + " user " + userId);
17003                                 doStopUidLocked(uidRec.uid, uidRec);
17004                             }
17005                         }
17006                     }
17007                 }
17008             } finally {
17009                 if (mLocalPowerManager != null) {
17010                     mLocalPowerManager.finishUidChanges();
17011                 }
17012                 Binder.restoreCallingIdentity(callingId);
17013             }
17014         }
17015     }
17016 
17017     /** Make the currently active UIDs idle after a certain grace period. */
idleUids()17018     final void idleUids() {
17019         synchronized (this) {
17020             mOomAdjuster.idleUidsLocked();
17021         }
17022     }
17023 
17024     /**
17025      * Checks if any uid is coming from background to foreground or vice versa and if so, increments
17026      * the {@link UidRecord#curProcStateSeq} corresponding to that uid using global seq counter
17027      * {@link ProcessList#mProcStateSeqCounter} and notifies the app if it needs to block.
17028      */
17029     @VisibleForTesting
17030     @GuardedBy("this")
incrementProcStateSeqAndNotifyAppsLocked()17031     void incrementProcStateSeqAndNotifyAppsLocked() {
17032         if (mWaitForNetworkTimeoutMs <= 0) {
17033             return;
17034         }
17035         // Used for identifying which uids need to block for network.
17036         ArrayList<Integer> blockingUids = null;
17037         for (int i = mProcessList.mActiveUids.size() - 1; i >= 0; --i) {
17038             final UidRecord uidRec = mProcessList.mActiveUids.valueAt(i);
17039             // If the network is not restricted for uid, then nothing to do here.
17040             if (!mInjector.isNetworkRestrictedForUid(uidRec.uid)) {
17041                 continue;
17042             }
17043             if (!UserHandle.isApp(uidRec.uid) || !uidRec.hasInternetPermission) {
17044                 continue;
17045             }
17046             // If process state is not changed, then there's nothing to do.
17047             if (uidRec.setProcState == uidRec.getCurProcState()) {
17048                 continue;
17049             }
17050             final int blockState = getBlockStateForUid(uidRec);
17051             // No need to inform the app when the blockState is NETWORK_STATE_NO_CHANGE as
17052             // there's nothing the app needs to do in this scenario.
17053             if (blockState == NETWORK_STATE_NO_CHANGE) {
17054                 continue;
17055             }
17056             synchronized (uidRec.networkStateLock) {
17057                 uidRec.curProcStateSeq = ++mProcessList.mProcStateSeqCounter; // TODO: use method
17058                 if (blockState == NETWORK_STATE_BLOCK) {
17059                     if (blockingUids == null) {
17060                         blockingUids = new ArrayList<>();
17061                     }
17062                     blockingUids.add(uidRec.uid);
17063                 } else {
17064                     if (DEBUG_NETWORK) {
17065                         Slog.d(TAG_NETWORK, "uid going to background, notifying all blocking"
17066                                 + " threads for uid: " + uidRec);
17067                     }
17068                     if (uidRec.waitingForNetwork) {
17069                         uidRec.networkStateLock.notifyAll();
17070                     }
17071                 }
17072             }
17073         }
17074 
17075         // There are no uids that need to block, so nothing more to do.
17076         if (blockingUids == null) {
17077             return;
17078         }
17079 
17080         for (int i = mProcessList.mLruProcesses.size() - 1; i >= 0; --i) {
17081             final ProcessRecord app = mProcessList.mLruProcesses.get(i);
17082             if (!blockingUids.contains(app.uid)) {
17083                 continue;
17084             }
17085             if (!app.killedByAm && app.thread != null) {
17086                 final UidRecord uidRec = mProcessList.getUidRecordLocked(app.uid);
17087                 try {
17088                     if (DEBUG_NETWORK) {
17089                         Slog.d(TAG_NETWORK, "Informing app thread that it needs to block: "
17090                                 + uidRec);
17091                     }
17092                     if (uidRec != null) {
17093                         app.thread.setNetworkBlockSeq(uidRec.curProcStateSeq);
17094                     }
17095                 } catch (RemoteException ignored) {
17096                 }
17097             }
17098         }
17099     }
17100 
17101     /**
17102      * Checks if the uid is coming from background to foreground or vice versa and returns
17103      * appropriate block state based on this.
17104      *
17105      * @return blockState based on whether the uid is coming from background to foreground or
17106      *         vice versa. If bg->fg or fg->bg, then {@link #NETWORK_STATE_BLOCK} or
17107      *         {@link #NETWORK_STATE_UNBLOCK} respectively, otherwise
17108      *         {@link #NETWORK_STATE_NO_CHANGE}.
17109      */
17110     @VisibleForTesting
getBlockStateForUid(UidRecord uidRec)17111     int getBlockStateForUid(UidRecord uidRec) {
17112         // Denotes whether uid's process state is currently allowed network access.
17113         final boolean isAllowed =
17114                 isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.getCurProcState())
17115                 || isProcStateAllowedWhileOnRestrictBackground(uidRec.getCurProcState());
17116         // Denotes whether uid's process state was previously allowed network access.
17117         final boolean wasAllowed = isProcStateAllowedWhileIdleOrPowerSaveMode(uidRec.setProcState)
17118                 || isProcStateAllowedWhileOnRestrictBackground(uidRec.setProcState);
17119 
17120         // When the uid is coming to foreground, AMS should inform the app thread that it should
17121         // block for the network rules to get updated before launching an activity.
17122         if (!wasAllowed && isAllowed) {
17123             return NETWORK_STATE_BLOCK;
17124         }
17125         // When the uid is going to background, AMS should inform the app thread that if an
17126         // activity launch is blocked for the network rules to get updated, it should be unblocked.
17127         if (wasAllowed && !isAllowed) {
17128             return NETWORK_STATE_UNBLOCK;
17129         }
17130         return NETWORK_STATE_NO_CHANGE;
17131     }
17132 
runInBackgroundDisabled(int uid)17133     final void runInBackgroundDisabled(int uid) {
17134         synchronized (this) {
17135             UidRecord uidRec = mProcessList.getUidRecordLocked(uid);
17136             if (uidRec != null) {
17137                 // This uid is actually running...  should it be considered background now?
17138                 if (uidRec.idle) {
17139                     doStopUidLocked(uidRec.uid, uidRec);
17140                 }
17141             } else {
17142                 // This uid isn't actually running...  still send a report about it being "stopped".
17143                 doStopUidLocked(uid, null);
17144             }
17145         }
17146     }
17147 
17148     @GuardedBy("this")
doStopUidLocked(int uid, final UidRecord uidRec)17149     final void doStopUidLocked(int uid, final UidRecord uidRec) {
17150         mServices.stopInBackgroundLocked(uid);
17151         enqueueUidChangeLocked(uidRec, uid, UidRecord.CHANGE_IDLE);
17152     }
17153 
17154     /**
17155      * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
17156      */
17157     @GuardedBy("this")
tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid, long duration, String tag)17158     void tempWhitelistForPendingIntentLocked(int callerPid, int callerUid, int targetUid,
17159             long duration, String tag) {
17160         if (DEBUG_WHITELISTS) {
17161             Slog.d(TAG, "tempWhitelistForPendingIntentLocked(" + callerPid + ", " + callerUid + ", "
17162                     + targetUid + ", " + duration + ")");
17163         }
17164 
17165         synchronized (mPidsSelfLocked) {
17166             final ProcessRecord pr = mPidsSelfLocked.get(callerPid);
17167             if (pr == null) {
17168                 Slog.w(TAG, "tempWhitelistForPendingIntentLocked() no ProcessRecord for pid "
17169                         + callerPid);
17170                 return;
17171             }
17172             if (!pr.whitelistManager) {
17173                 if (checkPermission(CHANGE_DEVICE_IDLE_TEMP_WHITELIST, callerPid, callerUid)
17174                         != PackageManager.PERMISSION_GRANTED) {
17175                     if (DEBUG_WHITELISTS) {
17176                         Slog.d(TAG, "tempWhitelistForPendingIntentLocked() for target " + targetUid
17177                                 + ": pid " + callerPid + " is not allowed");
17178                     }
17179                     return;
17180                 }
17181             }
17182         }
17183 
17184         tempWhitelistUidLocked(targetUid, duration, tag);
17185     }
17186 
17187     /**
17188      * Whitelists {@code targetUid} to temporarily bypass Power Save mode.
17189      */
17190     @GuardedBy("this")
tempWhitelistUidLocked(int targetUid, long duration, String tag)17191     void tempWhitelistUidLocked(int targetUid, long duration, String tag) {
17192         mPendingTempWhitelist.put(targetUid, new PendingTempWhitelist(targetUid, duration, tag));
17193         setUidTempWhitelistStateLocked(targetUid, true);
17194         mUiHandler.obtainMessage(PUSH_TEMP_WHITELIST_UI_MSG).sendToTarget();
17195     }
17196 
pushTempWhitelist()17197     void pushTempWhitelist() {
17198         final int N;
17199         final PendingTempWhitelist[] list;
17200 
17201         // First copy out the pending changes...  we need to leave them in the map for now,
17202         // in case someone needs to check what is coming up while we don't have the lock held.
17203         synchronized(this) {
17204             N = mPendingTempWhitelist.size();
17205             list = new PendingTempWhitelist[N];
17206             for (int i = 0; i < N; i++) {
17207                 list[i] = mPendingTempWhitelist.valueAt(i);
17208             }
17209         }
17210 
17211         // Now safely dispatch changes to device idle controller.
17212         for (int i = 0; i < N; i++) {
17213             PendingTempWhitelist ptw = list[i];
17214             mLocalDeviceIdleController.addPowerSaveTempWhitelistAppDirect(ptw.targetUid,
17215                     ptw.duration, true, ptw.tag);
17216         }
17217 
17218         // And now we can safely remove them from the map.
17219         synchronized(this) {
17220             for (int i = 0; i < N; i++) {
17221                 PendingTempWhitelist ptw = list[i];
17222                 int index = mPendingTempWhitelist.indexOfKey(ptw.targetUid);
17223                 if (index >= 0 && mPendingTempWhitelist.valueAt(index) == ptw) {
17224                     mPendingTempWhitelist.removeAt(index);
17225                 }
17226             }
17227         }
17228     }
17229 
17230     @GuardedBy("this")
setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist)17231     final void setAppIdTempWhitelistStateLocked(int appId, boolean onWhitelist) {
17232         mOomAdjuster.setAppIdTempWhitelistStateLocked(appId, onWhitelist);
17233     }
17234 
17235     @GuardedBy("this")
setUidTempWhitelistStateLocked(int uid, boolean onWhitelist)17236     final void setUidTempWhitelistStateLocked(int uid, boolean onWhitelist) {
17237         mOomAdjuster.setUidTempWhitelistStateLocked(uid, onWhitelist);
17238     }
17239 
trimApplications(String oomAdjReason)17240     final void trimApplications(String oomAdjReason) {
17241         synchronized (this) {
17242             trimApplicationsLocked(oomAdjReason);
17243         }
17244     }
17245 
17246     @GuardedBy("this")
trimApplicationsLocked(String oomAdjReason)17247     final void trimApplicationsLocked(String oomAdjReason) {
17248         // First remove any unused application processes whose package
17249         // has been removed.
17250         for (int i = mProcessList.mRemovedProcesses.size() - 1; i >= 0; i--) {
17251             final ProcessRecord app = mProcessList.mRemovedProcesses.get(i);
17252             if (!app.hasActivitiesOrRecentTasks()
17253                     && app.curReceivers.isEmpty() && app.services.size() == 0) {
17254                 Slog.i(
17255                     TAG, "Exiting empty application process "
17256                     + app.toShortString() + " ("
17257                     + (app.thread != null ? app.thread.asBinder() : null)
17258                     + ")\n");
17259                 if (app.pid > 0 && app.pid != MY_PID) {
17260                     app.kill("empty", false);
17261                 } else if (app.thread != null) {
17262                     try {
17263                         app.thread.scheduleExit();
17264                     } catch (Exception e) {
17265                         // Ignore exceptions.
17266                     }
17267                 }
17268                 cleanUpApplicationRecordLocked(app, false, true, -1, false /*replacingPid*/);
17269                 mProcessList.mRemovedProcesses.remove(i);
17270 
17271                 if (app.isPersistent()) {
17272                     addAppLocked(app.info, null, false, null /* ABI override */);
17273                 }
17274             }
17275         }
17276 
17277         // Now update the oom adj for all processes. Don't skip this, since other callers
17278         // might be depending on it.
17279         updateOomAdjLocked(oomAdjReason);
17280     }
17281 
17282     /** This method sends the specified signal to each of the persistent apps */
signalPersistentProcesses(int sig)17283     public void signalPersistentProcesses(int sig) throws RemoteException {
17284         if (sig != SIGNAL_USR1) {
17285             throw new SecurityException("Only SIGNAL_USR1 is allowed");
17286         }
17287 
17288         synchronized (this) {
17289             if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
17290                     != PackageManager.PERMISSION_GRANTED) {
17291                 throw new SecurityException("Requires permission "
17292                         + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
17293             }
17294 
17295             for (int i = mProcessList.mLruProcesses.size() - 1 ; i >= 0 ; i--) {
17296                 ProcessRecord r = mProcessList.mLruProcesses.get(i);
17297                 if (r.thread != null && r.isPersistent()) {
17298                     sendSignal(r.pid, sig);
17299                 }
17300             }
17301         }
17302     }
17303 
stopProfilerLocked(ProcessRecord proc, int profileType)17304     private void stopProfilerLocked(ProcessRecord proc, int profileType) {
17305         if (proc == null || proc == mProfileData.getProfileProc()) {
17306             proc = mProfileData.getProfileProc();
17307             profileType = mProfileType;
17308             clearProfilerLocked();
17309         }
17310         if (proc == null) {
17311             return;
17312         }
17313         try {
17314             proc.thread.profilerControl(false, null, profileType);
17315         } catch (RemoteException e) {
17316             throw new IllegalStateException("Process disappeared");
17317         }
17318     }
17319 
clearProfilerLocked()17320     void clearProfilerLocked() {
17321         if (mProfileData.getProfilerInfo() != null
17322                 && mProfileData.getProfilerInfo().profileFd != null) {
17323             try {
17324                 mProfileData.getProfilerInfo().profileFd.close();
17325             } catch (IOException e) {
17326             }
17327         }
17328         mProfileData.setProfileApp(null);
17329         mProfileData.setProfileProc(null);
17330         mProfileData.setProfilerInfo(null);
17331     }
17332 
profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)17333     public boolean profileControl(String process, int userId, boolean start,
17334             ProfilerInfo profilerInfo, int profileType) throws RemoteException {
17335 
17336         try {
17337             synchronized (this) {
17338                 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17339                 // its own permission.
17340                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17341                         != PackageManager.PERMISSION_GRANTED) {
17342                     throw new SecurityException("Requires permission "
17343                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17344                 }
17345 
17346                 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) {
17347                     throw new IllegalArgumentException("null profile info or fd");
17348                 }
17349 
17350                 ProcessRecord proc = null;
17351                 if (process != null) {
17352                     proc = findProcessLocked(process, userId, "profileControl");
17353                 }
17354 
17355                 if (start && (proc == null || proc.thread == null)) {
17356                     throw new IllegalArgumentException("Unknown process: " + process);
17357                 }
17358 
17359                 if (start) {
17360                     stopProfilerLocked(null, 0);
17361                     setProfileApp(proc.info, proc.processName, profilerInfo);
17362                     mProfileData.setProfileProc(proc);
17363                     mProfileType = profileType;
17364                     ParcelFileDescriptor fd = profilerInfo.profileFd;
17365                     try {
17366                         fd = fd.dup();
17367                     } catch (IOException e) {
17368                         fd = null;
17369                     }
17370                     profilerInfo.profileFd = fd;
17371                     proc.thread.profilerControl(start, profilerInfo, profileType);
17372                     fd = null;
17373                     try {
17374                         mProfileData.getProfilerInfo().profileFd.close();
17375                     } catch (IOException e) {
17376                     }
17377                     mProfileData.getProfilerInfo().profileFd = null;
17378 
17379                     if (proc.pid == MY_PID) {
17380                         // When profiling the system server itself, avoid closing the file
17381                         // descriptor, as profilerControl will not create a copy.
17382                         // Note: it is also not correct to just set profileFd to null, as the
17383                         //       whole ProfilerInfo instance is passed down!
17384                         profilerInfo = null;
17385                     }
17386                 } else {
17387                     stopProfilerLocked(proc, profileType);
17388                     if (profilerInfo != null && profilerInfo.profileFd != null) {
17389                         try {
17390                             profilerInfo.profileFd.close();
17391                         } catch (IOException e) {
17392                         }
17393                     }
17394                 }
17395 
17396                 return true;
17397             }
17398         } catch (RemoteException e) {
17399             throw new IllegalStateException("Process disappeared");
17400         } finally {
17401             if (profilerInfo != null && profilerInfo.profileFd != null) {
17402                 try {
17403                     profilerInfo.profileFd.close();
17404                 } catch (IOException e) {
17405                 }
17406             }
17407         }
17408     }
17409 
findProcessLocked(String process, int userId, String callName)17410     private ProcessRecord findProcessLocked(String process, int userId, String callName) {
17411         userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
17412                 userId, true, ALLOW_FULL_ONLY, callName, null);
17413         ProcessRecord proc = null;
17414         try {
17415             int pid = Integer.parseInt(process);
17416             synchronized (mPidsSelfLocked) {
17417                 proc = mPidsSelfLocked.get(pid);
17418             }
17419         } catch (NumberFormatException e) {
17420         }
17421 
17422         if (proc == null) {
17423             ArrayMap<String, SparseArray<ProcessRecord>> all
17424                     = mProcessList.mProcessNames.getMap();
17425             SparseArray<ProcessRecord> procs = all.get(process);
17426             if (procs != null && procs.size() > 0) {
17427                 proc = procs.valueAt(0);
17428                 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
17429                     for (int i=1; i<procs.size(); i++) {
17430                         ProcessRecord thisProc = procs.valueAt(i);
17431                         if (thisProc.userId == userId) {
17432                             proc = thisProc;
17433                             break;
17434                         }
17435                     }
17436                 }
17437             }
17438         }
17439 
17440         return proc;
17441     }
17442 
17443     @Override
dumpHeap(String process, int userId, boolean managed, boolean mallocInfo, boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback)17444     public boolean dumpHeap(String process, int userId, boolean managed, boolean mallocInfo,
17445             boolean runGc, String path, ParcelFileDescriptor fd, RemoteCallback finishCallback) {
17446 
17447         try {
17448             synchronized (this) {
17449                 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17450                 // its own permission (same as profileControl).
17451                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17452                         != PackageManager.PERMISSION_GRANTED) {
17453                     throw new SecurityException("Requires permission "
17454                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17455                 }
17456 
17457                 if (fd == null) {
17458                     throw new IllegalArgumentException("null fd");
17459                 }
17460 
17461                 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
17462                 if (proc == null || proc.thread == null) {
17463                     throw new IllegalArgumentException("Unknown process: " + process);
17464                 }
17465 
17466                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
17467                 if (!isDebuggable) {
17468                     if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17469                         throw new SecurityException("Process not debuggable: " + proc);
17470                     }
17471                 }
17472 
17473                 proc.thread.dumpHeap(managed, mallocInfo, runGc, path, fd, finishCallback);
17474                 fd = null;
17475                 return true;
17476             }
17477         } catch (RemoteException e) {
17478             throw new IllegalStateException("Process disappeared");
17479         } finally {
17480             if (fd != null) {
17481                 try {
17482                     fd.close();
17483                 } catch (IOException e) {
17484                 }
17485             }
17486         }
17487     }
17488 
17489     @Override
setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)17490     public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize,
17491             String reportPackage) {
17492         if (processName != null) {
17493             enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
17494                     "setDumpHeapDebugLimit()");
17495         } else {
17496             synchronized (mPidsSelfLocked) {
17497                 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid());
17498                 if (proc == null) {
17499                     throw new SecurityException("No process found for calling pid "
17500                             + Binder.getCallingPid());
17501                 }
17502                 if (!Build.IS_DEBUGGABLE
17503                         && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17504                     throw new SecurityException("Not running a debuggable build");
17505                 }
17506                 processName = proc.processName;
17507                 uid = proc.uid;
17508                 if (reportPackage != null && !proc.pkgList.containsKey(reportPackage)) {
17509                     throw new SecurityException("Package " + reportPackage + " is not running in "
17510                             + proc);
17511                 }
17512             }
17513         }
17514         synchronized (this) {
17515             if (maxMemSize > 0) {
17516                 mMemWatchProcesses.put(processName, uid, new Pair(maxMemSize, reportPackage));
17517             } else {
17518                 if (uid != 0) {
17519                     mMemWatchProcesses.remove(processName, uid);
17520                 } else {
17521                     mMemWatchProcesses.getMap().remove(processName);
17522                 }
17523             }
17524         }
17525     }
17526 
17527     @Override
dumpHeapFinished(String path)17528     public void dumpHeapFinished(String path) {
17529         synchronized (this) {
17530             if (Binder.getCallingPid() != mMemWatchDumpPid) {
17531                 Slog.w(TAG, "dumpHeapFinished: Calling pid " + Binder.getCallingPid()
17532                         + " does not match last pid " + mMemWatchDumpPid);
17533                 return;
17534             }
17535             if (mMemWatchDumpFile == null || !mMemWatchDumpFile.equals(path)) {
17536                 Slog.w(TAG, "dumpHeapFinished: Calling path " + path
17537                         + " does not match last path " + mMemWatchDumpFile);
17538                 return;
17539             }
17540             if (DEBUG_PSS) Slog.d(TAG_PSS, "Dump heap finished for " + path);
17541             mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG);
17542 
17543             // Forced gc to clean up the remnant hprof fd.
17544             Runtime.getRuntime().gc();
17545         }
17546     }
17547 
17548     /** In this method we try to acquire our lock to make sure that we have not deadlocked */
monitor()17549     public void monitor() {
17550         synchronized (this) { }
17551     }
17552 
onCoreSettingsChange(Bundle settings)17553     void onCoreSettingsChange(Bundle settings) {
17554         synchronized (this) {
17555             mProcessList.updateCoreSettingsLocked(settings);
17556         }
17557     }
17558 
17559     // Multi-user methods
17560 
17561     /**
17562      * Start user, if its not already running, but don't bring it to foreground.
17563      */
17564     @Override
startUserInBackground(final int userId)17565     public boolean startUserInBackground(final int userId) {
17566         return startUserInBackgroundWithListener(userId, null);
17567     }
17568 
17569     @Override
startUserInBackgroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17570     public boolean startUserInBackgroundWithListener(final int userId,
17571                 @Nullable IProgressListener unlockListener) {
17572         return mUserController.startUser(userId, /* foreground */ false, unlockListener);
17573     }
17574 
17575     @Override
startUserInForegroundWithListener(final int userId, @Nullable IProgressListener unlockListener)17576     public boolean startUserInForegroundWithListener(final int userId,
17577             @Nullable IProgressListener unlockListener) {
17578         // Permission check done inside UserController.
17579         return mUserController.startUser(userId, /* foreground */ true, unlockListener);
17580     }
17581 
17582     @Override
unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener)17583     public boolean unlockUser(int userId, byte[] token, byte[] secret, IProgressListener listener) {
17584         return mUserController.unlockUser(userId, token, secret, listener);
17585     }
17586 
17587     @Override
switchUser(final int targetUserId)17588     public boolean switchUser(final int targetUserId) {
17589         return mUserController.switchUser(targetUserId);
17590     }
17591 
17592     @Override
stopUser(final int userId, boolean force, final IStopUserCallback callback)17593     public int stopUser(final int userId, boolean force, final IStopUserCallback callback) {
17594         return mUserController.stopUser(userId, force, callback, null /* keyEvictedCallback */);
17595     }
17596 
17597     @Override
getCurrentUser()17598     public UserInfo getCurrentUser() {
17599         return mUserController.getCurrentUser();
17600     }
17601 
getStartedUserState(int userId)17602     String getStartedUserState(int userId) {
17603         final UserState userState = mUserController.getStartedUserState(userId);
17604         return UserState.stateToString(userState.state);
17605     }
17606 
17607     @Override
isUserRunning(int userId, int flags)17608     public boolean isUserRunning(int userId, int flags) {
17609         if (!mUserController.isSameProfileGroup(userId, UserHandle.getCallingUserId())
17610                 && checkCallingPermission(INTERACT_ACROSS_USERS)
17611                     != PackageManager.PERMISSION_GRANTED) {
17612             String msg = "Permission Denial: isUserRunning() from pid="
17613                     + Binder.getCallingPid()
17614                     + ", uid=" + Binder.getCallingUid()
17615                     + " requires " + INTERACT_ACROSS_USERS;
17616             Slog.w(TAG, msg);
17617             throw new SecurityException(msg);
17618         }
17619         return mUserController.isUserRunning(userId, flags);
17620     }
17621 
17622     @Override
getRunningUserIds()17623     public int[] getRunningUserIds() {
17624         if (checkCallingPermission(INTERACT_ACROSS_USERS)
17625                 != PackageManager.PERMISSION_GRANTED) {
17626             String msg = "Permission Denial: isUserRunning() from pid="
17627                     + Binder.getCallingPid()
17628                     + ", uid=" + Binder.getCallingUid()
17629                     + " requires " + INTERACT_ACROSS_USERS;
17630             Slog.w(TAG, msg);
17631             throw new SecurityException(msg);
17632         }
17633         return mUserController.getStartedUserArray();
17634     }
17635 
17636     @Override
registerUserSwitchObserver(IUserSwitchObserver observer, String name)17637     public void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
17638         mUserController.registerUserSwitchObserver(observer, name);
17639     }
17640 
17641     @Override
unregisterUserSwitchObserver(IUserSwitchObserver observer)17642     public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
17643         mUserController.unregisterUserSwitchObserver(observer);
17644     }
17645 
getAppInfoForUser(ApplicationInfo info, int userId)17646     ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
17647         if (info == null) return null;
17648         ApplicationInfo newInfo = new ApplicationInfo(info);
17649         newInfo.initForUser(userId);
17650         return newInfo;
17651     }
17652 
isUserStopped(int userId)17653     public boolean isUserStopped(int userId) {
17654         return mUserController.getStartedUserState(userId) == null;
17655     }
17656 
getActivityInfoForUser(ActivityInfo aInfo, int userId)17657     ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
17658         if (aInfo == null
17659                 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
17660             return aInfo;
17661         }
17662 
17663         ActivityInfo info = new ActivityInfo(aInfo);
17664         info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
17665         return info;
17666     }
17667 
processSanityChecksLocked(ProcessRecord process)17668     private boolean processSanityChecksLocked(ProcessRecord process) {
17669         if (process == null || process.thread == null) {
17670             return false;
17671         }
17672 
17673         boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
17674         if (!isDebuggable) {
17675             if ((process.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17676                 return false;
17677             }
17678         }
17679 
17680         return true;
17681     }
17682 
startBinderTracking()17683     public boolean startBinderTracking() throws RemoteException {
17684         synchronized (this) {
17685             mBinderTransactionTrackingEnabled = true;
17686             // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17687             // permission (same as profileControl).
17688             if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17689                     != PackageManager.PERMISSION_GRANTED) {
17690                 throw new SecurityException("Requires permission "
17691                         + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17692             }
17693 
17694             for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
17695                 ProcessRecord process = mProcessList.mLruProcesses.get(i);
17696                 if (!processSanityChecksLocked(process)) {
17697                     continue;
17698                 }
17699                 try {
17700                     process.thread.startBinderTracking();
17701                 } catch (RemoteException e) {
17702                     Log.v(TAG, "Process disappared");
17703                 }
17704             }
17705             return true;
17706         }
17707     }
17708 
stopBinderTrackingAndDump(ParcelFileDescriptor fd)17709     public boolean stopBinderTrackingAndDump(ParcelFileDescriptor fd) throws RemoteException {
17710         try {
17711             synchronized (this) {
17712                 mBinderTransactionTrackingEnabled = false;
17713                 // TODO: hijacking SET_ACTIVITY_WATCHER, but should be changed to its own
17714                 // permission (same as profileControl).
17715                 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17716                         != PackageManager.PERMISSION_GRANTED) {
17717                     throw new SecurityException("Requires permission "
17718                             + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17719                 }
17720 
17721                 if (fd == null) {
17722                     throw new IllegalArgumentException("null fd");
17723                 }
17724 
17725                 PrintWriter pw = new FastPrintWriter(new FileOutputStream(fd.getFileDescriptor()));
17726                 pw.println("Binder transaction traces for all processes.\n");
17727                 for (ProcessRecord process : mProcessList.mLruProcesses) {
17728                     if (!processSanityChecksLocked(process)) {
17729                         continue;
17730                     }
17731 
17732                     pw.println("Traces for process: " + process.processName);
17733                     pw.flush();
17734                     try {
17735                         TransferPipe tp = new TransferPipe();
17736                         try {
17737                             process.thread.stopBinderTrackingAndDump(tp.getWriteFd());
17738                             tp.go(fd.getFileDescriptor());
17739                         } finally {
17740                             tp.kill();
17741                         }
17742                     } catch (IOException e) {
17743                         pw.println("Failure while dumping IPC traces from " + process +
17744                                 ".  Exception: " + e);
17745                         pw.flush();
17746                     } catch (RemoteException e) {
17747                         pw.println("Got a RemoteException while dumping IPC traces from " +
17748                                 process + ".  Exception: " + e);
17749                         pw.flush();
17750                     }
17751                 }
17752                 fd = null;
17753                 return true;
17754             }
17755         } finally {
17756             if (fd != null) {
17757                 try {
17758                     fd.close();
17759                 } catch (IOException e) {
17760                 }
17761             }
17762         }
17763     }
17764 
17765     @VisibleForTesting
17766     public final class LocalService extends ActivityManagerInternal {
17767         @Override
checkContentProviderAccess(String authority, int userId)17768         public String checkContentProviderAccess(String authority, int userId) {
17769             return ActivityManagerService.this.checkContentProviderAccess(authority, userId);
17770         }
17771 
17772         @Override
onWakefulnessChanged(int wakefulness)17773         public void onWakefulnessChanged(int wakefulness) {
17774             ActivityManagerService.this.onWakefulnessChanged(wakefulness);
17775         }
17776 
17777         @Override
startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)17778         public boolean startIsolatedProcess(String entryPoint, String[] entryPointArgs,
17779                 String processName, String abiOverride, int uid, Runnable crashHandler) {
17780             return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
17781                     processName, abiOverride, uid, crashHandler);
17782         }
17783 
17784         @Override
killForegroundAppsForUser(int userHandle)17785         public void killForegroundAppsForUser(int userHandle) {
17786             synchronized (ActivityManagerService.this) {
17787                 final ArrayList<ProcessRecord> procs = new ArrayList<>();
17788                 final int NP = mProcessList.mProcessNames.getMap().size();
17789                 for (int ip = 0; ip < NP; ip++) {
17790                     final SparseArray<ProcessRecord> apps =
17791                             mProcessList.mProcessNames.getMap().valueAt(ip);
17792                     final int NA = apps.size();
17793                     for (int ia = 0; ia < NA; ia++) {
17794                         final ProcessRecord app = apps.valueAt(ia);
17795                         if (app.isPersistent()) {
17796                             // We don't kill persistent processes.
17797                             continue;
17798                         }
17799                         if (app.removed
17800                                 || (app.userId == userHandle && app.hasForegroundActivities())) {
17801                             procs.add(app);
17802                         }
17803                     }
17804                 }
17805 
17806                 final int N = procs.size();
17807                 for (int i = 0; i < N; i++) {
17808                     mProcessList.removeProcessLocked(procs.get(i), false, true, "kill all fg");
17809                 }
17810             }
17811         }
17812 
17813         @Override
setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken, long duration)17814         public void setPendingIntentWhitelistDuration(IIntentSender target, IBinder whitelistToken,
17815                 long duration) {
17816             mPendingIntentController.setPendingIntentWhitelistDuration(target, whitelistToken,
17817                     duration);
17818         }
17819 
17820         @Override
setPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken, int flags)17821         public void setPendingIntentAllowBgActivityStarts(IIntentSender target,
17822                 IBinder whitelistToken, int flags) {
17823             if (!(target instanceof PendingIntentRecord)) {
17824                 Slog.w(TAG, "setPendingIntentAllowBgActivityStarts():"
17825                         + " not a PendingIntentRecord: " + target);
17826                 return;
17827             }
17828             synchronized (ActivityManagerService.this) {
17829                 ((PendingIntentRecord) target).setAllowBgActivityStarts(whitelistToken, flags);
17830             }
17831         }
17832 
17833         @Override
clearPendingIntentAllowBgActivityStarts(IIntentSender target, IBinder whitelistToken)17834         public void clearPendingIntentAllowBgActivityStarts(IIntentSender target,
17835                 IBinder whitelistToken) {
17836             if (!(target instanceof PendingIntentRecord)) {
17837                 Slog.w(TAG, "clearPendingIntentAllowBgActivityStarts():"
17838                         + " not a PendingIntentRecord: " + target);
17839                 return;
17840             }
17841             synchronized (ActivityManagerService.this) {
17842                 ((PendingIntentRecord) target).clearAllowBgActivityStarts(whitelistToken);
17843             }
17844         }
17845 
17846         @Override
setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids)17847         public void setDeviceIdleWhitelist(int[] allAppids, int[] exceptIdleAppids) {
17848             synchronized (ActivityManagerService.this) {
17849                 mDeviceIdleWhitelist = allAppids;
17850                 mDeviceIdleExceptIdleWhitelist = exceptIdleAppids;
17851             }
17852         }
17853 
17854         @Override
updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding)17855         public void updateDeviceIdleTempWhitelist(int[] appids, int changingAppId, boolean adding) {
17856             synchronized (ActivityManagerService.this) {
17857                 mDeviceIdleTempWhitelist = appids;
17858                 setAppIdTempWhitelistStateLocked(changingAppId, adding);
17859             }
17860         }
17861 
17862         @Override
getUidProcessState(int uid)17863         public int getUidProcessState(int uid) {
17864             return getUidState(uid);
17865         }
17866 
17867         @Override
isSystemReady()17868         public boolean isSystemReady() {
17869             // no need to synchronize(this) just to read & return the value
17870             return mSystemReady;
17871         }
17872 
17873         /**
17874          * Sets if the given pid has an overlay UI or not.
17875          *
17876          * @param pid The pid we are setting overlay UI for.
17877          * @param hasOverlayUi True if the process has overlay UI.
17878          * @see android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
17879          */
17880         @Override
setHasOverlayUi(int pid, boolean hasOverlayUi)17881         public void setHasOverlayUi(int pid, boolean hasOverlayUi) {
17882             synchronized (ActivityManagerService.this) {
17883                 final ProcessRecord pr;
17884                 synchronized (mPidsSelfLocked) {
17885                     pr = mPidsSelfLocked.get(pid);
17886                     if (pr == null) {
17887                         Slog.w(TAG, "setHasOverlayUi called on unknown pid: " + pid);
17888                         return;
17889                     }
17890                 }
17891                 if (pr.hasOverlayUi() == hasOverlayUi) {
17892                     return;
17893                 }
17894                 pr.setHasOverlayUi(hasOverlayUi);
17895                 //Slog.i(TAG, "Setting hasOverlayUi=" + pr.hasOverlayUi + " for pid=" + pid);
17896                 updateOomAdjLocked(pr, true, OomAdjuster.OOM_ADJ_REASON_UI_VISIBILITY);
17897             }
17898         }
17899 
17900         /**
17901          * Called after the network policy rules are updated by
17902          * {@link com.android.server.net.NetworkPolicyManagerService} for a specific {@param uid}
17903          * and {@param procStateSeq}.
17904          */
17905         @Override
notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq)17906         public void notifyNetworkPolicyRulesUpdated(int uid, long procStateSeq) {
17907             if (DEBUG_NETWORK) {
17908                 Slog.d(TAG_NETWORK, "Got update from NPMS for uid: "
17909                         + uid + " seq: " + procStateSeq);
17910             }
17911             UidRecord record;
17912             synchronized (ActivityManagerService.this) {
17913                 record = mProcessList.getUidRecordLocked(uid);
17914                 if (record == null) {
17915                     if (DEBUG_NETWORK) {
17916                         Slog.d(TAG_NETWORK, "No active uidRecord for uid: " + uid
17917                                 + " procStateSeq: " + procStateSeq);
17918                     }
17919                     return;
17920                 }
17921             }
17922             synchronized (record.networkStateLock) {
17923                 if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
17924                     if (DEBUG_NETWORK) {
17925                         Slog.d(TAG_NETWORK, "procStateSeq: " + procStateSeq + " has already"
17926                                 + " been handled for uid: " + uid);
17927                     }
17928                     return;
17929                 }
17930                 record.lastNetworkUpdatedProcStateSeq = procStateSeq;
17931                 if (record.curProcStateSeq > procStateSeq) {
17932                     if (DEBUG_NETWORK) {
17933                         Slog.d(TAG_NETWORK, "No need to handle older seq no., Uid: " + uid
17934                                 + ", curProcstateSeq: " + record.curProcStateSeq
17935                                 + ", procStateSeq: " + procStateSeq);
17936                     }
17937                     return;
17938                 }
17939                 if (record.waitingForNetwork) {
17940                     if (DEBUG_NETWORK) {
17941                         Slog.d(TAG_NETWORK, "Notifying all blocking threads for uid: " + uid
17942                                 + ", procStateSeq: " + procStateSeq);
17943                     }
17944                     record.networkStateLock.notifyAll();
17945                 }
17946             }
17947         }
17948 
17949         @Override
isRuntimeRestarted()17950         public boolean isRuntimeRestarted() {
17951             return mSystemServiceManager.isRuntimeRestarted();
17952         }
17953 
17954         @Override
canStartMoreUsers()17955         public boolean canStartMoreUsers() {
17956             return mUserController.canStartMoreUsers();
17957         }
17958 
17959         @Override
setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage)17960         public void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
17961             mUserController.setSwitchingFromSystemUserMessage(switchingFromSystemUserMessage);
17962         }
17963 
17964         @Override
setSwitchingToSystemUserMessage(String switchingToSystemUserMessage)17965         public void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
17966             mUserController.setSwitchingToSystemUserMessage(switchingToSystemUserMessage);
17967         }
17968 
17969         @Override
getMaxRunningUsers()17970         public int getMaxRunningUsers() {
17971             return mUserController.mMaxRunningUsers;
17972         }
17973 
17974         @Override
isUidActive(int uid)17975         public boolean isUidActive(int uid) {
17976             synchronized (ActivityManagerService.this) {
17977                 return isUidActiveLocked(uid);
17978             }
17979         }
17980 
17981         @Override
setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation)17982         public void setRunningRemoteAnimation(int pid, boolean runningRemoteAnimation) {
17983             ActivityManagerService.this.setRunningRemoteAnimation(pid, runningRemoteAnimation);
17984         }
17985 
17986         @Override
getMemoryStateForProcesses()17987         public List<ProcessMemoryState> getMemoryStateForProcesses() {
17988             List<ProcessMemoryState> processMemoryStates = new ArrayList<>();
17989             synchronized (mPidsSelfLocked) {
17990                 for (int i = 0, size = mPidsSelfLocked.size(); i < size; i++) {
17991                     final ProcessRecord r = mPidsSelfLocked.valueAt(i);
17992                     processMemoryStates.add(
17993                             new ProcessMemoryState(r.uid, r.pid, r.processName, r.curAdj));
17994                 }
17995             }
17996             return processMemoryStates;
17997         }
17998 
17999         @Override
handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)18000         public int handleIncomingUser(int callingPid, int callingUid, int userId,
18001                 boolean allowAll, int allowMode, String name, String callerPackage) {
18002             return mUserController.handleIncomingUser(callingPid, callingUid, userId, allowAll,
18003                     allowMode, name, callerPackage);
18004         }
18005 
18006         @Override
enforceCallingPermission(String permission, String func)18007         public void enforceCallingPermission(String permission, String func) {
18008             ActivityManagerService.this.enforceCallingPermission(permission, func);
18009         }
18010 
18011         @Override
getCurrentUserId()18012         public int getCurrentUserId() {
18013             return mUserController.getCurrentUserIdLU();
18014         }
18015 
18016         @Override
isUserRunning(int userId, int flags)18017         public boolean isUserRunning(int userId, int flags) {
18018             // Holding am lock isn't required to call into user controller.
18019             return mUserController.isUserRunning(userId, flags);
18020         }
18021 
18022         @Override
trimApplications()18023         public void trimApplications() {
18024             ActivityManagerService.this.trimApplications(OomAdjuster.OOM_ADJ_REASON_ACTIVITY);
18025         }
18026 
killProcessesForRemovedTask(ArrayList<Object> procsToKill)18027         public void killProcessesForRemovedTask(ArrayList<Object> procsToKill) {
18028             synchronized (ActivityManagerService.this) {
18029                 for (int i = 0; i < procsToKill.size(); i++) {
18030                     final WindowProcessController wpc =
18031                             (WindowProcessController) procsToKill.get(i);
18032                     final ProcessRecord pr = (ProcessRecord) wpc.mOwner;
18033                     if (pr.setSchedGroup == ProcessList.SCHED_GROUP_BACKGROUND
18034                             && pr.curReceivers.isEmpty()) {
18035                         pr.kill("remove task", true);
18036                     } else {
18037                         // We delay killing processes that are not in the background or running a
18038                         // receiver.
18039                         pr.waitingToKill = "remove task";
18040                     }
18041                 }
18042             }
18043         }
18044 
18045         @Override
killProcess(String processName, int uid, String reason)18046         public void killProcess(String processName, int uid, String reason) {
18047             synchronized (ActivityManagerService.this) {
18048                 final ProcessRecord proc = getProcessRecordLocked(processName, uid,
18049                         true /* keepIfLarge */);
18050                 if (proc != null) {
18051                     mProcessList.removeProcessLocked(proc, false /* callerWillRestart */,
18052                             true /* allowRestart */, reason);
18053                 }
18054             }
18055         }
18056 
18057         @Override
hasRunningActivity(int uid, @Nullable String packageName)18058         public boolean hasRunningActivity(int uid, @Nullable String packageName) {
18059             if (packageName == null) return false;
18060 
18061             synchronized (ActivityManagerService.this) {
18062                 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
18063                     final ProcessRecord pr = mProcessList.mLruProcesses.get(i);
18064                     if (pr.uid != uid) {
18065                         continue;
18066                     }
18067                     if (pr.getWindowProcessController().hasRunningActivity(packageName)) {
18068                         return true;
18069                     }
18070                 }
18071             }
18072             return false;
18073         }
18074 
18075         @Override
updateOomAdj()18076         public void updateOomAdj() {
18077             synchronized (ActivityManagerService.this) {
18078                 ActivityManagerService.this.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
18079             }
18080         }
18081 
18082         @Override
updateCpuStats()18083         public void updateCpuStats() {
18084             synchronized (ActivityManagerService.this) {
18085                 ActivityManagerService.this.updateCpuStats();
18086             }
18087         }
18088 
18089         @Override
updateBatteryStats(ComponentName activity, int uid, int userId, boolean resumed)18090         public void updateBatteryStats(ComponentName activity, int uid, int userId,
18091                 boolean resumed) {
18092             synchronized (ActivityManagerService.this) {
18093                 ActivityManagerService.this.updateBatteryStats(activity, uid, userId, resumed);
18094             }
18095         }
18096 
18097         @Override
updateActivityUsageStats(ComponentName activity, int userId, int event, IBinder appToken, ComponentName taskRoot)18098         public void updateActivityUsageStats(ComponentName activity, int userId, int event,
18099                 IBinder appToken, ComponentName taskRoot) {
18100             synchronized (ActivityManagerService.this) {
18101                 ActivityManagerService.this.updateActivityUsageStats(activity, userId, event,
18102                         appToken, taskRoot);
18103             }
18104         }
18105 
18106         @Override
updateForegroundTimeIfOnBattery( String packageName, int uid, long cpuTimeDiff)18107         public void updateForegroundTimeIfOnBattery(
18108                 String packageName, int uid, long cpuTimeDiff) {
18109             synchronized (ActivityManagerService.this) {
18110                 if (!mBatteryStatsService.isOnBattery()) {
18111                     return;
18112                 }
18113                 final BatteryStatsImpl bsi = mBatteryStatsService.getActiveStatistics();
18114                 synchronized (bsi) {
18115                     final BatteryStatsImpl.Uid.Proc ps =
18116                             bsi.getProcessStatsLocked(uid, packageName);
18117                     if (ps != null) {
18118                         ps.addForegroundTimeLocked(cpuTimeDiff);
18119                     }
18120                 }
18121             }
18122         }
18123 
18124         @Override
sendForegroundProfileChanged(int userId)18125         public void sendForegroundProfileChanged(int userId) {
18126             mUserController.sendForegroundProfileChanged(userId);
18127         }
18128 
18129         @Override
shouldConfirmCredentials(int userId)18130         public boolean shouldConfirmCredentials(int userId) {
18131             return mUserController.shouldConfirmCredentials(userId);
18132         }
18133 
18134         @Override
getCurrentProfileIds()18135         public int[] getCurrentProfileIds() {
18136             return mUserController.getCurrentProfileIds();
18137         }
18138 
18139         @Override
getCurrentUser()18140         public UserInfo getCurrentUser() {
18141             return mUserController.getCurrentUser();
18142         }
18143 
18144         @Override
ensureNotSpecialUser(int userId)18145         public void ensureNotSpecialUser(int userId) {
18146             mUserController.ensureNotSpecialUser(userId);
18147         }
18148 
18149         @Override
isCurrentProfile(int userId)18150         public boolean isCurrentProfile(int userId) {
18151             return mUserController.isCurrentProfile(userId);
18152         }
18153 
18154         @Override
hasStartedUserState(int userId)18155         public boolean hasStartedUserState(int userId) {
18156             return mUserController.hasStartedUserState(userId);
18157         }
18158 
18159         @Override
finishUserSwitch(Object uss)18160         public void finishUserSwitch(Object uss) {
18161             mUserController.finishUserSwitch((UserState) uss);
18162         }
18163 
18164         @Override
scheduleAppGcs()18165         public void scheduleAppGcs() {
18166             synchronized (ActivityManagerService.this) {
18167                 ActivityManagerService.this.scheduleAppGcsLocked();
18168             }
18169         }
18170 
18171         @Override
getTaskIdForActivity(IBinder token, boolean onlyRoot)18172         public int getTaskIdForActivity(IBinder token, boolean onlyRoot) {
18173             synchronized (ActivityManagerService.this) {
18174                 return ActivityManagerService.this.getTaskForActivity(token, onlyRoot);
18175             }
18176         }
18177 
18178         @Override
getActivityPresentationInfo(IBinder token)18179         public ActivityPresentationInfo getActivityPresentationInfo(IBinder token) {
18180             int displayId = Display.INVALID_DISPLAY;
18181             try {
18182                 displayId = mActivityTaskManager.getActivityDisplayId(token);
18183             } catch (RemoteException e) {
18184             }
18185 
18186             return new ActivityPresentationInfo(mActivityTaskManager.getTaskForActivity(token,
18187                     /*onlyRoot=*/ false), displayId,
18188                     mActivityTaskManager.getActivityClassForToken(token));
18189         }
18190 
18191         @Override
setBooting(boolean booting)18192         public void setBooting(boolean booting) {
18193             mBooting = booting;
18194         }
18195 
18196         @Override
isBooting()18197         public boolean isBooting() {
18198             return mBooting;
18199         }
18200 
18201         @Override
setBooted(boolean booted)18202         public void setBooted(boolean booted) {
18203             mBooted = booted;
18204         }
18205 
18206         @Override
isBooted()18207         public boolean isBooted() {
18208             return mBooted;
18209         }
18210 
18211         @Override
finishBooting()18212         public void finishBooting() {
18213             ActivityManagerService.this.finishBooting();
18214         }
18215 
18216         @Override
tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid, long duration, String tag)18217         public void tempWhitelistForPendingIntent(int callerPid, int callerUid, int targetUid,
18218                 long duration, String tag) {
18219             synchronized (ActivityManagerService.this) {
18220                 ActivityManagerService.this.tempWhitelistForPendingIntentLocked(
18221                         callerPid, callerUid, targetUid, duration, tag);
18222             }
18223         }
18224 
18225         @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)18226         public int broadcastIntentInPackage(String packageName, int uid, int realCallingUid,
18227                 int realCallingPid, Intent intent, String resolvedType, IIntentReceiver resultTo,
18228                 int resultCode, String resultData, Bundle resultExtras, String requiredPermission,
18229                 Bundle bOptions, boolean serialized, boolean sticky, int userId,
18230                 boolean allowBackgroundActivityStarts) {
18231             synchronized (ActivityManagerService.this) {
18232                 return ActivityManagerService.this.broadcastIntentInPackage(packageName, uid,
18233                         realCallingUid, realCallingPid, intent, resolvedType, resultTo, resultCode,
18234                         resultData, resultExtras, requiredPermission, bOptions, serialized, sticky,
18235                         userId, allowBackgroundActivityStarts);
18236             }
18237         }
18238 
18239         @Override
startServiceInPackage(int uid, Intent service, String resolvedType, boolean fgRequired, String callingPackage, int userId, boolean allowBackgroundActivityStarts)18240         public ComponentName startServiceInPackage(int uid, Intent service, String resolvedType,
18241                 boolean fgRequired, String callingPackage, int userId,
18242                 boolean allowBackgroundActivityStarts) throws TransactionTooLargeException {
18243             synchronized(ActivityManagerService.this) {
18244                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
18245                         "startServiceInPackage: " + service + " type=" + resolvedType);
18246                 final long origId = Binder.clearCallingIdentity();
18247                 ComponentName res;
18248                 try {
18249                     res = mServices.startServiceLocked(null, service,
18250                             resolvedType, -1, uid, fgRequired, callingPackage, userId,
18251                             allowBackgroundActivityStarts);
18252                 } finally {
18253                     Binder.restoreCallingIdentity(origId);
18254                 }
18255                 return res;
18256             }
18257         }
18258 
18259         // The arguments here are untyped because the base ActivityManagerInternal class
18260         // doesn't have compile-time visiblity into ActivityServiceConnectionHolder or
18261         // ConnectionRecord.
18262         @Override
disconnectActivityFromServices(Object connectionHolder, Object conns)18263         public void disconnectActivityFromServices(Object connectionHolder, Object conns) {
18264             // 'connectionHolder' is an untyped ActivityServiceConnectionsHolder
18265             // 'conns' is an untyped HashSet<ConnectionRecord>
18266             final ActivityServiceConnectionsHolder holder =
18267                     (ActivityServiceConnectionsHolder) connectionHolder;
18268             final HashSet<ConnectionRecord> toDisconnect = (HashSet<ConnectionRecord>) conns;
18269             synchronized(ActivityManagerService.this) {
18270                 for (ConnectionRecord cr : toDisconnect) {
18271                     mServices.removeConnectionLocked(cr, null, holder);
18272                 }
18273             }
18274         }
18275 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)18276         public void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
18277             synchronized(ActivityManagerService.this) {
18278                 mServices.cleanUpServices(userId, component, baseIntent);
18279             }
18280         }
18281 
getActivityInfoForUser(ActivityInfo aInfo, int userId)18282         public ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
18283             // Locked intentionally not held as it isn't needed for this case.
18284             return ActivityManagerService.this.getActivityInfoForUser(aInfo, userId);
18285         }
18286 
ensureBootCompleted()18287         public void ensureBootCompleted() {
18288             // Locked intentionally not held as it isn't needed for this case.
18289             ActivityManagerService.this.ensureBootCompleted();
18290         }
18291 
updateOomLevelsForDisplay(int displayId)18292         public void updateOomLevelsForDisplay(int displayId) {
18293             synchronized(ActivityManagerService.this) {
18294                 if (mWindowManager != null) {
18295                     mProcessList.applyDisplaySize(mWindowManager);
18296                 }
18297             }
18298         }
18299 
isActivityStartsLoggingEnabled()18300         public boolean isActivityStartsLoggingEnabled() {
18301             return mConstants.mFlagActivityStartsLoggingEnabled;
18302         }
18303 
isBackgroundActivityStartsEnabled()18304         public boolean isBackgroundActivityStartsEnabled() {
18305             return mConstants.mFlagBackgroundActivityStartsEnabled;
18306         }
18307 
reportCurKeyguardUsageEvent(boolean keyguardShowing)18308         public void reportCurKeyguardUsageEvent(boolean keyguardShowing) {
18309             synchronized(ActivityManagerService.this) {
18310                 ActivityManagerService.this.reportGlobalUsageEventLocked(keyguardShowing
18311                         ? UsageEvents.Event.KEYGUARD_SHOWN
18312                         : UsageEvents.Event.KEYGUARD_HIDDEN);
18313             }
18314         }
18315 
18316         @Override
inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason)18317         public long inputDispatchingTimedOut(int pid, boolean aboveSystem, String reason) {
18318             synchronized (ActivityManagerService.this) {
18319                 return ActivityManagerService.this.inputDispatchingTimedOut(
18320                         pid, aboveSystem, reason);
18321             }
18322         }
18323 
18324         @Override
inputDispatchingTimedOut(Object proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, Object parentProc, boolean aboveSystem, String reason)18325         public boolean inputDispatchingTimedOut(Object proc, String activityShortComponentName,
18326                 ApplicationInfo aInfo, String parentShortComponentName, Object parentProc,
18327                 boolean aboveSystem, String reason) {
18328             return ActivityManagerService.this.inputDispatchingTimedOut((ProcessRecord) proc,
18329                     activityShortComponentName, aInfo, parentShortComponentName,
18330                     (WindowProcessController) parentProc, aboveSystem, reason);
18331 
18332         }
18333 
18334         @Override
broadcastGlobalConfigurationChanged(int changes, boolean initLocale)18335         public void broadcastGlobalConfigurationChanged(int changes, boolean initLocale) {
18336             synchronized (ActivityManagerService.this) {
18337                 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
18338                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18339                         | Intent.FLAG_RECEIVER_REPLACE_PENDING
18340                         | Intent.FLAG_RECEIVER_FOREGROUND
18341                         | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18342                 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
18343                         OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
18344                         Binder.getCallingPid(), UserHandle.USER_ALL);
18345                 if ((changes & ActivityInfo.CONFIG_LOCALE) != 0) {
18346                     intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
18347                     intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
18348                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
18349                             | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
18350                     if (initLocale || !mProcessesReady) {
18351                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
18352                     }
18353                     broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
18354                             OP_NONE, null, false, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
18355                             Binder.getCallingPid(), UserHandle.USER_ALL);
18356                 }
18357 
18358                 // Send a broadcast to PackageInstallers if the configuration change is interesting
18359                 // for the purposes of installing additional splits.
18360                 if (!initLocale && isSplitConfigurationChange(changes)) {
18361                     intent = new Intent(Intent.ACTION_SPLIT_CONFIGURATION_CHANGED);
18362                     intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
18363                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
18364 
18365                     // Typically only app stores will have this permission.
18366                     String[] permissions =
18367                             new String[] { android.Manifest.permission.INSTALL_PACKAGES };
18368                     broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
18369                             permissions, OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
18370                             Binder.getCallingUid(), Binder.getCallingPid(), UserHandle.USER_ALL);
18371                 }
18372             }
18373         }
18374 
18375         /**
18376          * Returns true if this configuration change is interesting enough to send an
18377          * {@link Intent#ACTION_SPLIT_CONFIGURATION_CHANGED} broadcast.
18378          */
isSplitConfigurationChange(int configDiff)18379         private boolean isSplitConfigurationChange(int configDiff) {
18380             return (configDiff & (ActivityInfo.CONFIG_LOCALE | ActivityInfo.CONFIG_DENSITY)) != 0;
18381         }
18382 
18383         @Override
broadcastCloseSystemDialogs(String reason)18384         public void broadcastCloseSystemDialogs(String reason) {
18385             synchronized (ActivityManagerService.this) {
18386                 final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
18387                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
18388                         | Intent.FLAG_RECEIVER_FOREGROUND);
18389                 if (reason != null) {
18390                     intent.putExtra("reason", reason);
18391                 }
18392 
18393                 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null,
18394                         OP_NONE, null, false, false, -1, SYSTEM_UID, Binder.getCallingUid(),
18395                         Binder.getCallingPid(), UserHandle.USER_ALL);
18396             }
18397         }
18398 
18399         @Override
killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState)18400         public void killAllBackgroundProcessesExcept(int minTargetSdk, int maxProcState) {
18401             synchronized (ActivityManagerService.this) {
18402                 ActivityManagerService.this.killAllBackgroundProcessesExcept(
18403                         minTargetSdk, maxProcState);
18404             }
18405         }
18406 
18407         @Override
startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, String hostingType, ComponentName hostingName)18408         public void startProcess(String processName, ApplicationInfo info,
18409                 boolean knownToBeDead, String hostingType, ComponentName hostingName) {
18410             try {
18411                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
18412                     Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
18413                             + processName);
18414                 }
18415                 synchronized (ActivityManagerService.this) {
18416                     startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
18417                             new HostingRecord(hostingType, hostingName),
18418                             false /* allowWhileBooting */, false /* isolated */,
18419                             true /* keepIfLarge */);
18420                 }
18421             } finally {
18422                 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
18423             }
18424         }
18425 
18426         @Override
setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags, ProfilerInfo profilerInfo, Object wmLock)18427         public void setDebugFlagsForStartingActivity(ActivityInfo aInfo, int startFlags,
18428                 ProfilerInfo profilerInfo, Object wmLock) {
18429             synchronized (ActivityManagerService.this) {
18430                 /**
18431                  * This function is called from the window manager context and needs to be executed
18432                  * synchronously.  To avoid deadlock, we pass a message to AMS to execute the
18433                  * function and notify the passed in lock when it has been completed.
18434                  */
18435                 synchronized (wmLock) {
18436                     if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
18437                         setDebugApp(aInfo.processName, true, false);
18438                     }
18439 
18440                     if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
18441                         setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
18442                     }
18443 
18444                     if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
18445                         setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
18446                     }
18447 
18448                     if (profilerInfo != null) {
18449                         setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
18450                     }
18451                     wmLock.notify();
18452                 }
18453             }
18454         }
18455 
18456         @Override
getStorageMountMode(int pid, int uid)18457         public int getStorageMountMode(int pid, int uid) {
18458             if (uid == SHELL_UID || uid == ROOT_UID) {
18459                 return Zygote.MOUNT_EXTERNAL_FULL;
18460             }
18461             synchronized (mPidsSelfLocked) {
18462                 final ProcessRecord pr = mPidsSelfLocked.get(pid);
18463                 return pr == null ? Zygote.MOUNT_EXTERNAL_NONE : pr.mountMode;
18464             }
18465         }
18466 
18467         @Override
isAppForeground(int uid)18468         public boolean isAppForeground(int uid) {
18469             return ActivityManagerService.this.isAppForeground(uid);
18470         }
18471 
18472         @Override
isAppBad(ApplicationInfo info)18473         public boolean isAppBad(ApplicationInfo info) {
18474             return ActivityManagerService.this.isAppBad(info);
18475         }
18476 
18477         @Override
clearPendingBackup(int userId)18478         public void clearPendingBackup(int userId) {
18479             ActivityManagerService.this.clearPendingBackup(userId);
18480         }
18481 
18482         /**
18483          * When power button is very long pressed, call this interface to do some pre-shutdown work
18484          * like persisting database etc.
18485          */
18486         @Override
prepareForPossibleShutdown()18487         public void prepareForPossibleShutdown() {
18488             ActivityManagerService.this.prepareForPossibleShutdown();
18489         }
18490 
18491         @Override
hasRunningForegroundService(int uid, int foregroundServicetype)18492         public boolean hasRunningForegroundService(int uid, int foregroundServicetype) {
18493             synchronized (ActivityManagerService.this) {
18494                 for (int i = 0; i < mProcessList.mLruProcesses.size(); i++) {
18495                     final ProcessRecord pr = mProcessList.mLruProcesses.get(i);
18496                     if (pr.uid != uid) {
18497                         continue;
18498                     }
18499 
18500                     if ((pr.getForegroundServiceTypes() & foregroundServicetype) != 0) {
18501                         return true;
18502                     }
18503                 }
18504             }
18505 
18506             return false;
18507         }
18508 
18509         @Override
registerProcessObserver(IProcessObserver processObserver)18510         public void registerProcessObserver(IProcessObserver processObserver) {
18511             ActivityManagerService.this.registerProcessObserver(processObserver);
18512         }
18513 
18514         @Override
unregisterProcessObserver(IProcessObserver processObserver)18515         public void unregisterProcessObserver(IProcessObserver processObserver) {
18516             ActivityManagerService.this.unregisterProcessObserver(processObserver);
18517         }
18518     }
18519 
inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason)18520     long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
18521         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
18522             throw new SecurityException("Requires permission " + FILTER_EVENTS);
18523         }
18524         ProcessRecord proc;
18525         long timeout;
18526         synchronized (this) {
18527             synchronized (mPidsSelfLocked) {
18528                 proc = mPidsSelfLocked.get(pid);
18529             }
18530             timeout = proc != null ? proc.getInputDispatchingTimeout() : KEY_DISPATCHING_TIMEOUT_MS;
18531         }
18532 
18533         if (inputDispatchingTimedOut(proc, null, null, null, null, aboveSystem, reason)) {
18534             return -1;
18535         }
18536 
18537         return timeout;
18538     }
18539 
18540     /**
18541      * Handle input dispatching timeouts.
18542      * @return whether input dispatching should be aborted or not.
18543      */
inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, WindowProcessController parentProcess, boolean aboveSystem, String reason)18544     boolean inputDispatchingTimedOut(ProcessRecord proc, String activityShortComponentName,
18545             ApplicationInfo aInfo, String parentShortComponentName,
18546             WindowProcessController parentProcess, boolean aboveSystem, String reason) {
18547         if (checkCallingPermission(FILTER_EVENTS) != PackageManager.PERMISSION_GRANTED) {
18548             throw new SecurityException("Requires permission " + FILTER_EVENTS);
18549         }
18550 
18551         final String annotation;
18552         if (reason == null) {
18553             annotation = "Input dispatching timed out";
18554         } else {
18555             annotation = "Input dispatching timed out (" + reason + ")";
18556         }
18557 
18558         if (proc != null) {
18559             synchronized (this) {
18560                 if (proc.isDebugging()) {
18561                     return false;
18562                 }
18563 
18564                 if (proc.getActiveInstrumentation() != null) {
18565                     Bundle info = new Bundle();
18566                     info.putString("shortMsg", "keyDispatchingTimedOut");
18567                     info.putString("longMsg", annotation);
18568                     finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
18569                     return true;
18570                 }
18571             }
18572             proc.appNotResponding(activityShortComponentName, aInfo,
18573                     parentShortComponentName, parentProcess, aboveSystem, annotation);
18574         }
18575 
18576         return true;
18577     }
18578 
18579     /**
18580      * Called by app main thread to wait for the network policy rules to get updated.
18581      *
18582      * @param procStateSeq The sequence number indicating the process state change that the main
18583      *                     thread is interested in.
18584      */
18585     @Override
waitForNetworkStateUpdate(long procStateSeq)18586     public void waitForNetworkStateUpdate(long procStateSeq) {
18587         final int callingUid = Binder.getCallingUid();
18588         if (DEBUG_NETWORK) {
18589             Slog.d(TAG_NETWORK, "Called from " + callingUid + " to wait for seq: " + procStateSeq);
18590         }
18591         UidRecord record;
18592         synchronized (this) {
18593             record = mProcessList.getUidRecordLocked(callingUid);
18594             if (record == null) {
18595                 return;
18596             }
18597         }
18598         synchronized (record.networkStateLock) {
18599             if (record.lastDispatchedProcStateSeq < procStateSeq) {
18600                 if (DEBUG_NETWORK) {
18601                     Slog.d(TAG_NETWORK, "Uid state change for seq no. " + procStateSeq + " is not "
18602                             + "dispatched to NPMS yet, so don't wait. Uid: " + callingUid
18603                             + " lastProcStateSeqDispatchedToObservers: "
18604                             + record.lastDispatchedProcStateSeq);
18605                 }
18606                 return;
18607             }
18608             if (record.curProcStateSeq > procStateSeq) {
18609                 if (DEBUG_NETWORK) {
18610                     Slog.d(TAG_NETWORK, "Ignore the wait requests for older seq numbers. Uid: "
18611                             + callingUid + ", curProcStateSeq: " + record.curProcStateSeq
18612                             + ", procStateSeq: " + procStateSeq);
18613                 }
18614                 return;
18615             }
18616             if (record.lastNetworkUpdatedProcStateSeq >= procStateSeq) {
18617                 if (DEBUG_NETWORK) {
18618                     Slog.d(TAG_NETWORK, "Network rules have been already updated for seq no. "
18619                             + procStateSeq + ", so no need to wait. Uid: "
18620                             + callingUid + ", lastProcStateSeqWithUpdatedNetworkState: "
18621                             + record.lastNetworkUpdatedProcStateSeq);
18622                 }
18623                 return;
18624             }
18625             try {
18626                 if (DEBUG_NETWORK) {
18627                     Slog.d(TAG_NETWORK, "Starting to wait for the network rules update."
18628                         + " Uid: " + callingUid + " procStateSeq: " + procStateSeq);
18629                 }
18630                 final long startTime = SystemClock.uptimeMillis();
18631                 record.waitingForNetwork = true;
18632                 record.networkStateLock.wait(mWaitForNetworkTimeoutMs);
18633                 record.waitingForNetwork = false;
18634                 final long totalTime = SystemClock.uptimeMillis() - startTime;
18635                 if (totalTime >= mWaitForNetworkTimeoutMs || DEBUG_NETWORK) {
18636                     Slog.w(TAG_NETWORK, "Total time waited for network rules to get updated: "
18637                             + totalTime + ". Uid: " + callingUid + " procStateSeq: "
18638                             + procStateSeq + " UidRec: " + record
18639                             + " validateUidRec: " + mValidateUids.get(callingUid));
18640                 }
18641             } catch (InterruptedException e) {
18642                 Thread.currentThread().interrupt();
18643             }
18644         }
18645     }
18646 
waitForBroadcastIdle(PrintWriter pw)18647     public void waitForBroadcastIdle(PrintWriter pw) {
18648         enforceCallingPermission(permission.DUMP, "waitForBroadcastIdle()");
18649         while (true) {
18650             boolean idle = true;
18651             synchronized (this) {
18652                 for (BroadcastQueue queue : mBroadcastQueues) {
18653                     if (!queue.isIdle()) {
18654                         final String msg = "Waiting for queue " + queue + " to become idle...";
18655                         pw.println(msg);
18656                         pw.println(queue.describeState());
18657                         pw.flush();
18658                         Slog.v(TAG, msg);
18659                         queue.cancelDeferrals();
18660                         idle = false;
18661                     }
18662                 }
18663             }
18664 
18665             if (idle) {
18666                 final String msg = "All broadcast queues are idle!";
18667                 pw.println(msg);
18668                 pw.flush();
18669                 Slog.v(TAG, msg);
18670                 return;
18671             } else {
18672                 SystemClock.sleep(1000);
18673             }
18674         }
18675     }
18676 
18677     /**
18678      * Kill processes for the user with id userId and that depend on the package named packageName
18679      */
18680     @Override
killPackageDependents(String packageName, int userId)18681     public void killPackageDependents(String packageName, int userId) {
18682         enforceCallingPermission(android.Manifest.permission.KILL_UID, "killPackageDependents()");
18683         if (packageName == null) {
18684             throw new NullPointerException(
18685                     "Cannot kill the dependents of a package without its name.");
18686         }
18687 
18688         long callingId = Binder.clearCallingIdentity();
18689         IPackageManager pm = AppGlobals.getPackageManager();
18690         int pkgUid = -1;
18691         try {
18692             pkgUid = pm.getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
18693         } catch (RemoteException e) {
18694         }
18695         if (userId != UserHandle.USER_ALL && pkgUid == -1) {
18696             throw new IllegalArgumentException(
18697                     "Cannot kill dependents of non-existing package " + packageName);
18698         }
18699         try {
18700             synchronized(this) {
18701                 mProcessList.killPackageProcessesLocked(packageName, UserHandle.getAppId(pkgUid),
18702                         userId, ProcessList.FOREGROUND_APP_ADJ, "dep: " + packageName);
18703             }
18704         } finally {
18705             Binder.restoreCallingIdentity(callingId);
18706         }
18707     }
18708 
18709     @Override
restartUserInBackground(final int userId)18710     public int restartUserInBackground(final int userId) {
18711         return mUserController.restartUser(userId, /* foreground */ false);
18712     }
18713 
18714     @Override
scheduleApplicationInfoChanged(List<String> packageNames, int userId)18715     public void scheduleApplicationInfoChanged(List<String> packageNames, int userId) {
18716         enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
18717                 "scheduleApplicationInfoChanged()");
18718 
18719         synchronized (this) {
18720             final long origId = Binder.clearCallingIdentity();
18721             try {
18722                 updateApplicationInfoLocked(packageNames, userId);
18723             } finally {
18724                 Binder.restoreCallingIdentity(origId);
18725             }
18726         }
18727     }
18728 
18729     /**
18730      * Synchronously update the system ActivityThread, bypassing any deferred threading so any
18731      * resources and overlaid values are available immediately.
18732      */
updateSystemUiContext()18733     public void updateSystemUiContext() {
18734         PackageManagerInternal packageManagerInternal;
18735         synchronized (this) {
18736             packageManagerInternal = getPackageManagerInternalLocked();
18737         }
18738 
18739         ApplicationInfo ai = packageManagerInternal.getApplicationInfo("android",
18740                 GET_SHARED_LIBRARY_FILES, Binder.getCallingUid(), UserHandle.USER_SYSTEM);
18741         ActivityThread.currentActivityThread().handleSystemApplicationInfoChanged(ai);
18742     }
18743 
updateApplicationInfoLocked(@onNull List<String> packagesToUpdate, int userId)18744     void updateApplicationInfoLocked(@NonNull List<String> packagesToUpdate, int userId) {
18745         final boolean updateFrameworkRes = packagesToUpdate.contains("android");
18746         if (updateFrameworkRes) {
18747             PackageParser.readConfigUseRoundIcon(null);
18748         }
18749         mProcessList.updateApplicationInfoLocked(packagesToUpdate, userId, updateFrameworkRes);
18750 
18751         if (updateFrameworkRes) {
18752             // Update system server components that need to know about changed overlays. Because the
18753             // overlay is applied in ActivityThread, we need to serialize through its thread too.
18754             final Executor executor = ActivityThread.currentActivityThread().getExecutor();
18755             final DisplayManagerInternal display =
18756                     LocalServices.getService(DisplayManagerInternal.class);
18757             if (display != null) {
18758                 executor.execute(display::onOverlayChanged);
18759             }
18760             if (mWindowManager != null) {
18761                 executor.execute(mWindowManager::onOverlayChanged);
18762             }
18763         }
18764     }
18765 
18766     /**
18767      * Attach an agent to the specified process (proces name or PID)
18768      */
attachAgent(String process, String path)18769     public void attachAgent(String process, String path) {
18770         try {
18771             synchronized (this) {
18772                 ProcessRecord proc = findProcessLocked(process, UserHandle.USER_SYSTEM,
18773                         "attachAgent");
18774                 if (proc == null || proc.thread == null) {
18775                     throw new IllegalArgumentException("Unknown process: " + process);
18776                 }
18777 
18778                 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
18779                 if (!isDebuggable) {
18780                     if ((proc.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
18781                         throw new SecurityException("Process not debuggable: " + proc);
18782                     }
18783                 }
18784 
18785                 proc.thread.attachAgent(path);
18786             }
18787         } catch (RemoteException e) {
18788             throw new IllegalStateException("Process disappeared");
18789         }
18790     }
18791 
18792     /**
18793      * When power button is very long pressed, call this interface to do some pre-shutdown work
18794      * like persisting database etc.
18795      */
prepareForPossibleShutdown()18796     public void prepareForPossibleShutdown() {
18797         synchronized (this) {
18798             if (mUsageStatsService != null) {
18799                 mUsageStatsService.prepareForPossibleShutdown();
18800             }
18801         }
18802     }
18803 
18804     @VisibleForTesting
18805     public static class Injector {
18806         private NetworkManagementInternal mNmi;
18807 
getContext()18808         public Context getContext() {
18809             return null;
18810         }
18811 
getAppOpsService(File file, Handler handler)18812         public AppOpsService getAppOpsService(File file, Handler handler) {
18813             return new AppOpsService(file, handler);
18814         }
18815 
getUiHandler(ActivityManagerService service)18816         public Handler getUiHandler(ActivityManagerService service) {
18817             return service.new UiHandler();
18818         }
18819 
isNetworkRestrictedForUid(int uid)18820         public boolean isNetworkRestrictedForUid(int uid) {
18821             if (ensureHasNetworkManagementInternal()) {
18822                 return mNmi.isNetworkRestrictedForUid(uid);
18823             }
18824             return false;
18825         }
18826 
ensureHasNetworkManagementInternal()18827         private boolean ensureHasNetworkManagementInternal() {
18828             if (mNmi == null) {
18829                 mNmi = LocalServices.getService(NetworkManagementInternal.class);
18830             }
18831             return mNmi != null;
18832         }
18833     }
18834 
18835     @Override
startDelegateShellPermissionIdentity(int delegateUid, @Nullable String[] permissions)18836     public void startDelegateShellPermissionIdentity(int delegateUid,
18837             @Nullable String[] permissions) {
18838         if (UserHandle.getCallingAppId() != Process.SHELL_UID
18839                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
18840             throw new SecurityException("Only the shell can delegate its permissions");
18841         }
18842 
18843         // We allow delegation only to one instrumentation started from the shell
18844         synchronized (ActivityManagerService.this) {
18845             // If there is a delegate it should be the same instance for app ops and permissions.
18846             if (mAppOpsService.getAppOpsServiceDelegate()
18847                     != getPackageManagerInternalLocked().getCheckPermissionDelegate()) {
18848                 throw new IllegalStateException("Bad shell delegate state");
18849             }
18850 
18851             // If the delegate is already set up for the target UID, nothing to do.
18852             if (mAppOpsService.getAppOpsServiceDelegate() != null) {
18853                 if (!(mAppOpsService.getAppOpsServiceDelegate() instanceof ShellDelegate)) {
18854                     throw new IllegalStateException("Bad shell delegate state");
18855                 }
18856                 final ShellDelegate delegate = (ShellDelegate) mAppOpsService
18857                         .getAppOpsServiceDelegate();
18858                 if (delegate.getDelegateUid() != delegateUid) {
18859                     throw new SecurityException("Shell can delegate permissions only "
18860                             + "to one instrumentation at a time");
18861                 }
18862                 delegate.setPermissions(permissions);
18863                 return;
18864             }
18865 
18866             final int instrCount = mActiveInstrumentation.size();
18867             for (int i = 0; i < instrCount; i++) {
18868                 final ActiveInstrumentation instr = mActiveInstrumentation.get(i);
18869                 if (instr.mTargetInfo.uid != delegateUid) {
18870                     continue;
18871                 }
18872                 // If instrumentation started from the shell the connection is not null
18873                 if (instr.mUiAutomationConnection == null) {
18874                     throw new SecurityException("Shell can delegate its permissions" +
18875                             " only to an instrumentation started from the shell");
18876                 }
18877 
18878                 // Hook them up...
18879                 final ShellDelegate shellDelegate = new ShellDelegate(
18880                         instr.mTargetInfo.packageName, delegateUid, permissions);
18881                 mAppOpsService.setAppOpsServiceDelegate(shellDelegate);
18882                 getPackageManagerInternalLocked().setCheckPermissionDelegate(shellDelegate);
18883                 return;
18884             }
18885         }
18886     }
18887 
18888     @Override
stopDelegateShellPermissionIdentity()18889     public void stopDelegateShellPermissionIdentity() {
18890         if (UserHandle.getCallingAppId() != Process.SHELL_UID
18891                 && UserHandle.getCallingAppId() != Process.ROOT_UID) {
18892             throw new SecurityException("Only the shell can delegate its permissions");
18893         }
18894         synchronized (ActivityManagerService.this) {
18895             mAppOpsService.setAppOpsServiceDelegate(null);
18896             getPackageManagerInternalLocked().setCheckPermissionDelegate(null);
18897         }
18898     }
18899 
18900     private class ShellDelegate implements CheckOpsDelegate, CheckPermissionDelegate {
18901         private final String mTargetPackageName;
18902         private final int mTargetUid;
18903         private @Nullable String[] mPermissions;
18904 
ShellDelegate(String targetPacakgeName, int targetUid, @Nullable String[] permissions)18905         ShellDelegate(String targetPacakgeName, int targetUid, @Nullable String[] permissions) {
18906             mTargetPackageName = targetPacakgeName;
18907             mTargetUid = targetUid;
18908             mPermissions = permissions;
18909         }
18910 
getDelegateUid()18911         int getDelegateUid() {
18912             return mTargetUid;
18913         }
18914 
setPermissions(@ullable String[] permissions)18915         void setPermissions(@Nullable String[] permissions) {
18916             mPermissions = permissions;
18917         }
18918 
18919         @Override
checkOperation(int code, int uid, String packageName, boolean raw, QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl)18920         public int checkOperation(int code, int uid, String packageName, boolean raw,
18921                 QuadFunction<Integer, Integer, String, Boolean, Integer> superImpl) {
18922             if (uid == mTargetUid && isTargetOp(code)) {
18923                 final long identity = Binder.clearCallingIdentity();
18924                 try {
18925                     return superImpl.apply(code, Process.SHELL_UID,
18926                             "com.android.shell", raw);
18927                 } finally {
18928                     Binder.restoreCallingIdentity(identity);
18929                 }
18930             }
18931             return superImpl.apply(code, uid, packageName, raw);
18932         }
18933 
18934         @Override
checkAudioOperation(int code, int usage, int uid, String packageName, QuadFunction<Integer, Integer, Integer, String, Integer> superImpl)18935         public int checkAudioOperation(int code, int usage, int uid, String packageName,
18936                 QuadFunction<Integer, Integer, Integer, String, Integer> superImpl) {
18937             if (uid == mTargetUid && isTargetOp(code)) {
18938                 final long identity = Binder.clearCallingIdentity();
18939                 try {
18940                     return superImpl.apply(code, usage, Process.SHELL_UID,
18941                             "com.android.shell");
18942                 } finally {
18943                     Binder.restoreCallingIdentity(identity);
18944                 }
18945             }
18946             return superImpl.apply(code, usage, uid, packageName);
18947         }
18948 
18949         @Override
noteOperation(int code, int uid, String packageName, TriFunction<Integer, Integer, String, Integer> superImpl)18950         public int noteOperation(int code, int uid, String packageName,
18951                 TriFunction<Integer, Integer, String, Integer> superImpl) {
18952             if (uid == mTargetUid && isTargetOp(code)) {
18953                 final long identity = Binder.clearCallingIdentity();
18954                 try {
18955                     return mAppOpsService.noteProxyOperation(code, Process.SHELL_UID,
18956                             "com.android.shell", uid, packageName);
18957                 } finally {
18958                     Binder.restoreCallingIdentity(identity);
18959                 }
18960             }
18961             return superImpl.apply(code, uid, packageName);
18962         }
18963 
18964         @Override
checkPermission(String permName, String pkgName, int userId, TriFunction<String, String, Integer, Integer> superImpl)18965         public int checkPermission(String permName, String pkgName, int userId,
18966                 TriFunction<String, String, Integer, Integer> superImpl) {
18967             if (mTargetPackageName.equals(pkgName) && isTargetPermission(permName)) {
18968                 final long identity = Binder.clearCallingIdentity();
18969                 try {
18970                     return superImpl.apply(permName, "com.android.shell", userId);
18971                 } finally {
18972                     Binder.restoreCallingIdentity(identity);
18973                 }
18974             }
18975             return superImpl.apply(permName, pkgName, userId);
18976         }
18977 
18978         @Override
checkUidPermission(String permName, int uid, BiFunction<String, Integer, Integer> superImpl)18979         public int checkUidPermission(String permName, int uid,
18980                 BiFunction<String, Integer, Integer> superImpl) {
18981             if (uid == mTargetUid  && isTargetPermission(permName)) {
18982                 final long identity = Binder.clearCallingIdentity();
18983                 try {
18984                     return superImpl.apply(permName, Process.SHELL_UID);
18985                 } finally {
18986                     Binder.restoreCallingIdentity(identity);
18987                 }
18988             }
18989             return superImpl.apply(permName, uid);
18990         }
18991 
isTargetOp(int code)18992         private boolean isTargetOp(int code) {
18993             // null permissions means all ops are targeted
18994             if (mPermissions == null) {
18995                 return true;
18996             }
18997             // no permission for the op means the op is targeted
18998             final String permission = AppOpsManager.opToPermission(code);
18999             if (permission == null) {
19000                 return true;
19001             }
19002             return isTargetPermission(permission);
19003         }
19004 
isTargetPermission(@onNull String permission)19005         private boolean isTargetPermission(@NonNull String permission) {
19006             // null permissions means all permissions are targeted
19007             return (mPermissions == null || ArrayUtils.contains(mPermissions, permission));
19008         }
19009     }
19010 
19011     /**
19012      * If debug.trigger.watchdog is set to 1, sleep 10 minutes with the AM lock held, which would
19013      * cause a watchdog kill.
19014      */
maybeTriggerWatchdog()19015     void maybeTriggerWatchdog() {
19016         final String key = "debug.trigger.watchdog";
19017         if (Watchdog.DEBUG && SystemProperties.getInt(key, 0) == 1) {
19018             Slog.w(TAG, "!!! TRIGGERING WATCHDOG !!!");
19019 
19020             // Clear the property; otherwise the system would hang again after a watchdog restart.
19021             SystemProperties.set(key, "");
19022             synchronized (ActivityManagerService.this) {
19023                 try {
19024                     // Arbitrary long sleep for watchdog to catch.
19025                     Thread.sleep(60 * 60 * 1000);
19026                 } catch (InterruptedException e) {
19027                 }
19028             }
19029         }
19030     }
19031 
isOnOffloadQueue(int flags)19032     private boolean isOnOffloadQueue(int flags) {
19033         return (mEnableOffloadQueue && ((flags & Intent.FLAG_RECEIVER_OFFLOAD) != 0));
19034     }
19035 
19036     @Override
getLifeMonitor()19037     public ParcelFileDescriptor getLifeMonitor() {
19038         if (!isCallerShell()) {
19039             throw new SecurityException("Only shell can call it");
19040         }
19041         synchronized (this) {
19042             try {
19043                 if (mLifeMonitorFds == null) {
19044                     mLifeMonitorFds = ParcelFileDescriptor.createPipe();
19045                 }
19046                 // The returned FD will be closed, but we want to keep our reader open,
19047                 // so return a dup instead.
19048                 return mLifeMonitorFds[0].dup();
19049             } catch (IOException e) {
19050                 Slog.w(TAG, "Unable to create pipe", e);
19051                 return null;
19052             }
19053         }
19054     }
19055 }
19056