1 /*
2  * Copyright (C) 2012 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.REQUEST_COMPANION_RUN_IN_BACKGROUND;
20 import static android.Manifest.permission.REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND;
21 import static android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND;
22 import static android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND;
23 import static android.app.ActivityManager.PROCESS_CAPABILITY_BFSL;
24 import static android.app.ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
25 import static android.app.ActivityManager.PROCESS_STATE_BOUND_TOP;
26 import static android.app.ActivityManager.PROCESS_STATE_HEAVY_WEIGHT;
27 import static android.app.ActivityManager.PROCESS_STATE_RECEIVER;
28 import static android.app.ActivityManager.PROCESS_STATE_TOP;
29 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_BIND_SERVICE;
30 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_COMPONENT_DISABLED;
31 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_EXECUTING_SERVICE;
32 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_NONE;
33 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_PROCESS_END;
34 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_REMOVE_TASK;
35 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_SHORT_FGS_TIMEOUT;
36 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_START_SERVICE;
37 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_STOP_SERVICE;
38 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_UID_IDLE;
39 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_UNBIND_SERVICE;
40 import static android.app.ForegroundServiceTypePolicy.FGS_TYPE_POLICY_CHECK_DEPRECATED;
41 import static android.app.ForegroundServiceTypePolicy.FGS_TYPE_POLICY_CHECK_DISABLED;
42 import static android.app.ForegroundServiceTypePolicy.FGS_TYPE_POLICY_CHECK_OK;
43 import static android.app.ForegroundServiceTypePolicy.FGS_TYPE_POLICY_CHECK_PERMISSION_DENIED_ENFORCED;
44 import static android.app.ForegroundServiceTypePolicy.FGS_TYPE_POLICY_CHECK_PERMISSION_DENIED_PERMISSIVE;
45 import static android.app.ForegroundServiceTypePolicy.FGS_TYPE_POLICY_CHECK_UNKNOWN;
46 import static android.content.Context.BIND_ALLOW_WHITELIST_MANAGEMENT;
47 import static android.content.pm.PackageManager.PERMISSION_DENIED;
48 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
49 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
50 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
51 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE;
52 import static android.os.PowerExemptionManager.REASON_ACTIVE_DEVICE_ADMIN;
53 import static android.os.PowerExemptionManager.REASON_ACTIVITY_STARTER;
54 import static android.os.PowerExemptionManager.REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD;
55 import static android.os.PowerExemptionManager.REASON_ALARM_MANAGER_ALARM_CLOCK;
56 import static android.os.PowerExemptionManager.REASON_ALLOWLISTED_PACKAGE;
57 import static android.os.PowerExemptionManager.REASON_BACKGROUND_ACTIVITY_PERMISSION;
58 import static android.os.PowerExemptionManager.REASON_BACKGROUND_FGS_PERMISSION;
59 import static android.os.PowerExemptionManager.REASON_CARRIER_PRIVILEGED_APP;
60 import static android.os.PowerExemptionManager.REASON_COMPANION_DEVICE_MANAGER;
61 import static android.os.PowerExemptionManager.REASON_CURRENT_INPUT_METHOD;
62 import static android.os.PowerExemptionManager.REASON_DENIED;
63 import static android.os.PowerExemptionManager.REASON_DEVICE_DEMO_MODE;
64 import static android.os.PowerExemptionManager.REASON_DEVICE_OWNER;
65 import static android.os.PowerExemptionManager.REASON_DISALLOW_APPS_CONTROL;
66 import static android.os.PowerExemptionManager.REASON_DPO_PROTECTED_APP;
67 import static android.os.PowerExemptionManager.REASON_FGS_BINDING;
68 import static android.os.PowerExemptionManager.REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION;
69 import static android.os.PowerExemptionManager.REASON_INSTR_BACKGROUND_FGS_PERMISSION;
70 import static android.os.PowerExemptionManager.REASON_OPT_OUT_REQUESTED;
71 import static android.os.PowerExemptionManager.REASON_OP_ACTIVATE_PLATFORM_VPN;
72 import static android.os.PowerExemptionManager.REASON_OP_ACTIVATE_VPN;
73 import static android.os.PowerExemptionManager.REASON_PACKAGE_INSTALLER;
74 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT;
75 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT_UI;
76 import static android.os.PowerExemptionManager.REASON_PROC_STATE_TOP;
77 import static android.os.PowerExemptionManager.REASON_PROFILE_OWNER;
78 import static android.os.PowerExemptionManager.REASON_ROLE_EMERGENCY;
79 import static android.os.PowerExemptionManager.REASON_SERVICE_LAUNCH;
80 import static android.os.PowerExemptionManager.REASON_START_ACTIVITY_FLAG;
81 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
82 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED;
83 import static android.os.PowerExemptionManager.REASON_SYSTEM_EXEMPT_APP_OP;
84 import static android.os.PowerExemptionManager.REASON_SYSTEM_MODULE;
85 import static android.os.PowerExemptionManager.REASON_SYSTEM_UID;
86 import static android.os.PowerExemptionManager.REASON_TEMP_ALLOWED_WHILE_IN_USE;
87 import static android.os.PowerExemptionManager.REASON_UID_VISIBLE;
88 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
89 import static android.os.PowerExemptionManager.getReasonCodeFromProcState;
90 import static android.os.PowerExemptionManager.reasonCodeToString;
91 import static android.os.Process.INVALID_UID;
92 import static android.os.Process.NFC_UID;
93 import static android.os.Process.ROOT_UID;
94 import static android.os.Process.SHELL_UID;
95 import static android.os.Process.SYSTEM_UID;
96 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
97 import static android.content.flags.Flags.enableBindPackageIsolatedProcess;
98 
99 
100 import static com.android.internal.messages.nano.SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICE_BG_LAUNCH;
101 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_DELEGATE;
102 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA;
103 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NONE;
104 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_START_FOREGROUND_SERVICE;
105 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_START_SERVICE;
106 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED;
107 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER;
108 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT;
109 import static com.android.internal.util.FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT;
110 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED;
111 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL;
112 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED;
113 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD;
114 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_HOT;
115 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM;
116 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__REQUEST_TYPE__BIND;
117 import static com.android.internal.util.FrameworkStatsLog.SERVICE_REQUEST_EVENT_REPORTED__REQUEST_TYPE__START;
118 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
119 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
120 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
121 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
122 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES;
123 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
124 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
125 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
126 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
127 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
128 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
129 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
130 
131 import android.Manifest;
132 import android.annotation.IntDef;
133 import android.annotation.NonNull;
134 import android.annotation.Nullable;
135 import android.annotation.UptimeMillisLong;
136 import android.annotation.UserIdInt;
137 import android.app.ActivityManager;
138 import android.app.ActivityManagerInternal;
139 import android.app.ActivityManagerInternal.OomAdjReason;
140 import android.app.ActivityManagerInternal.ServiceNotificationPolicy;
141 import android.app.ActivityThread;
142 import android.app.AppGlobals;
143 import android.app.AppOpsManager;
144 import android.app.BackgroundStartPrivileges;
145 import android.app.ForegroundServiceDelegationOptions;
146 import android.app.ForegroundServiceStartNotAllowedException;
147 import android.app.ForegroundServiceTypePolicy;
148 import android.app.ForegroundServiceTypePolicy.ForegroundServicePolicyCheckCode;
149 import android.app.ForegroundServiceTypePolicy.ForegroundServiceTypePermission;
150 import android.app.ForegroundServiceTypePolicy.ForegroundServiceTypePolicyInfo;
151 import android.app.IApplicationThread;
152 import android.app.IForegroundServiceObserver;
153 import android.app.IServiceConnection;
154 import android.app.InvalidForegroundServiceTypeException;
155 import android.app.MissingForegroundServiceTypeException;
156 import android.app.Notification;
157 import android.app.NotificationManager;
158 import android.app.PendingIntent;
159 import android.app.RemoteServiceException.ForegroundServiceDidNotStartInTimeException;
160 import android.app.RemoteServiceException.ForegroundServiceDidNotStopInTimeException;
161 import android.app.Service;
162 import android.app.ServiceStartArgs;
163 import android.app.StartForegroundCalledOnStoppedServiceException;
164 import android.app.admin.DevicePolicyEventLogger;
165 import android.app.compat.CompatChanges;
166 import android.app.usage.UsageEvents;
167 import android.appwidget.AppWidgetManagerInternal;
168 import android.compat.annotation.ChangeId;
169 import android.compat.annotation.EnabledAfter;
170 import android.compat.annotation.EnabledSince;
171 import android.compat.annotation.Overridable;
172 import android.content.ComponentName;
173 import android.content.ComponentName.WithComponentName;
174 import android.content.Context;
175 import android.content.IIntentSender;
176 import android.content.Intent;
177 import android.content.IntentSender;
178 import android.content.ServiceConnection;
179 import android.content.pm.ApplicationInfo;
180 import android.content.pm.PackageManager;
181 import android.content.pm.PackageManagerInternal;
182 import android.content.pm.ParceledListSlice;
183 import android.content.pm.ResolveInfo;
184 import android.content.pm.ServiceInfo;
185 import android.content.pm.ServiceInfo.ForegroundServiceType;
186 import android.os.Build;
187 import android.os.Build.VERSION_CODES;
188 import android.os.Bundle;
189 import android.os.DeadObjectException;
190 import android.os.Handler;
191 import android.os.IBinder;
192 import android.os.Looper;
193 import android.os.Message;
194 import android.os.PowerExemptionManager;
195 import android.os.PowerExemptionManager.ReasonCode;
196 import android.os.Process;
197 import android.os.RemoteCallback;
198 import android.os.RemoteCallbackList;
199 import android.os.RemoteException;
200 import android.os.ServiceManager;
201 import android.os.SystemClock;
202 import android.os.SystemProperties;
203 import android.os.Trace;
204 import android.os.TransactionTooLargeException;
205 import android.os.UserHandle;
206 import android.os.UserManager;
207 import android.provider.Settings;
208 import android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService;
209 import android.service.voice.HotwordDetectionService;
210 import android.service.voice.VisualQueryDetectionService;
211 import android.service.wearable.WearableSensingService;
212 import android.stats.devicepolicy.DevicePolicyEnums;
213 import android.text.TextUtils;
214 import android.util.ArrayMap;
215 import android.util.ArraySet;
216 import android.util.EventLog;
217 import android.util.Pair;
218 import android.util.PrintWriterPrinter;
219 import android.util.Slog;
220 import android.util.SparseArray;
221 import android.util.SparseIntArray;
222 import android.util.SparseLongArray;
223 import android.util.TimeUtils;
224 import android.util.proto.ProtoOutputStream;
225 import android.webkit.WebViewZygote;
226 
227 import com.android.internal.R;
228 import com.android.internal.annotations.GuardedBy;
229 import com.android.internal.app.procstats.ServiceState;
230 import com.android.internal.notification.SystemNotificationChannels;
231 import com.android.internal.os.SomeArgs;
232 import com.android.internal.os.TimeoutRecord;
233 import com.android.internal.os.TransferPipe;
234 import com.android.internal.util.ArrayUtils;
235 import com.android.internal.util.DumpUtils;
236 import com.android.internal.util.FastPrintWriter;
237 import com.android.internal.util.FrameworkStatsLog;
238 import com.android.server.AppStateTracker;
239 import com.android.server.LocalServices;
240 import com.android.server.SystemService;
241 import com.android.server.am.ActivityManagerService.ItemMatcher;
242 import com.android.server.am.LowMemDetector.MemFactor;
243 import com.android.server.am.ServiceRecord.ShortFgsInfo;
244 import com.android.server.am.ServiceRecord.TimeLimitedFgsInfo;
245 import com.android.server.pm.KnownPackages;
246 import com.android.server.uri.NeededUriGrants;
247 import com.android.server.utils.AnrTimer;
248 import com.android.server.wm.ActivityServiceConnectionsHolder;
249 
250 import java.io.FileDescriptor;
251 import java.io.IOException;
252 import java.io.PrintWriter;
253 import java.io.StringWriter;
254 import java.lang.annotation.Retention;
255 import java.lang.annotation.RetentionPolicy;
256 import java.text.SimpleDateFormat;
257 import java.util.ArrayList;
258 import java.util.Collections;
259 import java.util.Comparator;
260 import java.util.List;
261 import java.util.Objects;
262 import java.util.Set;
263 import java.util.concurrent.atomic.AtomicReference;
264 import java.util.function.Predicate;
265 
266 public final class ActiveServices {
267     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
268     private static final String TAG_MU = TAG + POSTFIX_MU;
269     static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
270     private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
271 
272     private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
273     private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
274 
275     private static final boolean DEBUG_SHORT_SERVICE = DEBUG_SERVICE;
276 
277     private static final boolean LOG_SERVICE_START_STOP = DEBUG_SERVICE;
278 
279     // Foreground service types that always get immediate notification display,
280     // expressed in the same bitmask format that ServiceRecord.foregroundServiceType
281     // uses.
282     static final int FGS_IMMEDIATE_DISPLAY_MASK =
283             ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
284                     | ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL
285                     | ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
286                     | ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION;
287 
288     // Keep track of number of foreground services and number of apps that have foreground
289     // services in the device. This field is made to be directly accessed without holding AMS lock.
290     static final AtomicReference<Pair<Integer, Integer>> sNumForegroundServices =
291             new AtomicReference(new Pair<>(0, 0));
292 
293     // Foreground service is stopped for unknown reason.
294     static final int FGS_STOP_REASON_UNKNOWN = 0;
295     // Foreground service is stopped by app calling Service.stopForeground().
296     static final int FGS_STOP_REASON_STOP_FOREGROUND = 1;
297     // Foreground service is stopped because service is brought down either by app calling
298     // stopService() or unbindService(), or service process is killed by the system.
299     static final int FGS_STOP_REASON_STOP_SERVICE = 2;
300     /**
301      * The list of FGS stop reasons.
302      */
303     @IntDef(flag = true, prefix = { "FGS_STOP_REASON_" }, value = {
304             FGS_STOP_REASON_UNKNOWN,
305             FGS_STOP_REASON_STOP_FOREGROUND,
306             FGS_STOP_REASON_STOP_SERVICE,
307     })
308     @Retention(RetentionPolicy.SOURCE)
309     @interface FgsStopReason {}
310 
311     /**
312      * The policy to be applied to the service bindings; this one means it follows the legacy
313      * behavior.
314      */
315     static final int SERVICE_BIND_OOMADJ_POLICY_LEGACY = 0;
316 
317     /**
318      * The policy to be applied to the service bindings; this one means we'll skip
319      * updating the target process's oom adj score / process state for its {@link Service#onCreate}.
320      */
321     static final int SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CREATE = 1;
322 
323     /**
324      * The policy to be applied to the service bindings; this one means we'll skip
325      * updating the target process's oom adj score / process state for its {@link Service#onBind}.
326      */
327     static final int SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_BIND = 1 << 1;
328 
329     /**
330      * The policy to be applied to the service bindings; this one means we'll skip
331      * updating the target process's oom adj score / process state on setting up the service
332      * connection between the client and the service host process.
333      */
334     static final int SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT = 1 << 2;
335     /**
336      * The policy to be applied to the service bindings; this one means the caller
337      * will be frozen upon calling the bindService APIs.
338      */
339     static final int SERVICE_BIND_OOMADJ_POLICY_FREEZE_CALLER = 1 << 3;
340 
341     @IntDef(flag = true, prefix = { "SERVICE_BIND_OOMADJ_POLICY_" }, value = {
342             SERVICE_BIND_OOMADJ_POLICY_LEGACY,
343             SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CREATE,
344             SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_BIND,
345             SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT,
346             SERVICE_BIND_OOMADJ_POLICY_FREEZE_CALLER,
347     })
348     @Retention(RetentionPolicy.SOURCE)
349     @interface ServiceBindingOomAdjPolicy {}
350 
351     @ServiceBindingOomAdjPolicy
352     static final int DEFAULT_SERVICE_NO_BUMP_BIND_POLICY_FLAG =
353             SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CREATE
354             | SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_BIND
355             | SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT;
356 
357     @ServiceBindingOomAdjPolicy
358     static final int DEFAULT_SERVICE_CACHED_BIND_POLICY_FLAG =
359             SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CREATE
360             | SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_BIND;
361 
362     /**
363      * Disables foreground service background starts from BOOT_COMPLETED broadcasts for all types
364      * except:
365      * <ul>
366      *     <li>{@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_LOCATION}</li>
367      *     <li>{@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE}</li>
368      *     <li>{@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING}</li>
369      *     <li>{@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_HEALTH}</li>
370      *     <li>{@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED}</li>
371      *     <li>{@link android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_SPECIAL_USE}</li>
372      * </ul>
373      */
374     @ChangeId
375     @EnabledSince(targetSdkVersion = VERSION_CODES.VANILLA_ICE_CREAM)
376     @Overridable
377     public static final long FGS_BOOT_COMPLETED_RESTRICTIONS = 296558535L;
378 
379     /**
380      * Disables foreground service background starts in System Alert Window for all types
381      * unless it already has a System Overlay Window.
382      */
383     @ChangeId
384     @EnabledSince(targetSdkVersion = VERSION_CODES.VANILLA_ICE_CREAM)
385     @Overridable
386     public static final long FGS_SAW_RESTRICTIONS = 319471980L;
387 
388     final ActivityManagerService mAm;
389 
390     // Maximum number of services that we allow to start in the background
391     // at the same time.
392     final int mMaxStartingBackground;
393 
394     /**
395      * Master service bookkeeping, keyed by user number.
396      */
397     final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
398 
399     /**
400      * All currently bound service connections.  Keys are the IBinder of
401      * the client's IServiceConnection.
402      */
403     final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
404 
405     /**
406      * List of services that we have been asked to start,
407      * but haven't yet been able to.  It is used to hold start requests
408      * while waiting for their corresponding application thread to get
409      * going.
410      */
411     final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
412 
413     /**
414      * List of services that are scheduled to restart following a crash.
415      */
416     final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
417 
418     /**
419      * List of services that are in the process of being destroyed.
420      */
421     final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
422 
423     /**
424      * List of services for which display of the FGS notification has been deferred.
425      */
426     final ArrayList<ServiceRecord> mPendingFgsNotifications = new ArrayList<>();
427 
428     /**
429      * Map of ForegroundServiceDelegation to the delegation ServiceRecord. The delegation
430      * ServiceRecord has flag isFgsDelegate set to true.
431      */
432     final ArrayMap<ForegroundServiceDelegation, ServiceRecord> mFgsDelegations = new ArrayMap<>();
433 
434     /**
435      * A global counter for generating sequence numbers to uniquely identify bindService requests.
436      * It is purely for logging purposes.
437      */
438     @GuardedBy("mAm")
439     private long mBindServiceSeqCounter = 0;
440 
441     /**
442      * Whether there is a rate limit that suppresses immediate re-deferral of new FGS
443      * notifications from each app.  On by default, disabled only by shell command for
444      * test-suite purposes.  To disable the behavior more generally, use the usual
445      * DeviceConfig mechanism to set the rate limit interval to zero.
446      */
447     private boolean mFgsDeferralRateLimited = true;
448 
449     /**
450      * Uptime at which a given uid becomes eliglible again for FGS notification deferral
451      */
452     final SparseLongArray mFgsDeferralEligible = new SparseLongArray();
453 
454     /**
455      * Foreground service observers: track what apps have FGSes
456      */
457     final RemoteCallbackList<IForegroundServiceObserver> mFgsObservers =
458             new RemoteCallbackList<>();
459 
460     /**
461      * Map of services that are asked to be brought up (start/binding) but not ready to.
462      */
463     private ArrayMap<ServiceRecord, ArrayList<Runnable>> mPendingBringups = new ArrayMap<>();
464 
465     /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
466     private ArrayList<ServiceRecord> mTmpCollectionResults = null;
467 
468     /** Mapping from uid to their foreground service AppOpCallbacks (if they have one). */
469     @GuardedBy("mAm")
470     private final SparseArray<AppOpCallback> mFgsAppOpCallbacks = new SparseArray<>();
471 
472     /**
473      * The list of packages with the service restart backoff disabled.
474      */
475     @GuardedBy("mAm")
476     private final ArraySet<String> mRestartBackoffDisabledPackages = new ArraySet<>();
477 
478     // Used for logging foreground service API starts and end
479     private final ForegroundServiceTypeLoggerModule mFGSLogger;
480 
481     /**
482      * For keeping ActiveForegroundApps retaining state while the screen is off.
483      */
484     boolean mScreenOn = true;
485 
486     /** Amount of time to allow a last ANR message to exist before freeing the memory. */
487     static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
488 
489     String mLastAnrDump;
490 
491     AppWidgetManagerInternal mAppWidgetManagerInternal;
492 
493     /**
494      * The available ANR timers.
495      */
496     // ActivityManagerConstants.SERVICE_TIMEOUT/ActivityManagerConstants.SERVICE_BACKGROUND_TIMEOUT
497     private final ProcessAnrTimer mActiveServiceAnrTimer;
498     // see ServiceRecord$ShortFgsInfo#getAnrTime()
499     private final ServiceAnrTimer mShortFGSAnrTimer;
500     // ActivityManagerConstants.DEFAULT_SERVICE_START_FOREGROUND_TIMEOUT_MS
501     private final ServiceAnrTimer mServiceFGAnrTimer;
502 
503     /**
504      * Mapping of uid to {fgs_type, fgs_info} for time limited fgs types such as dataSync and
505      * mediaProcessing.
506      */
507     final SparseArray<SparseArray<TimeLimitedFgsInfo>> mTimeLimitedFgsInfo = new SparseArray<>();
508 
509     /**
510      * Foreground services of certain types will now have a time limit. If the foreground service
511      * of the offending type is not stopped within the allocated time limit, it will receive a
512      * callback via {@link Service#onTimeout(int, int)} and it must then be stopped within a few
513      * seconds. If an app fails to do so, it will be declared an ANR.
514      *
515      * @see Service#onTimeout(int, int) onTimeout callback for additional details
516      */
517     @ChangeId
518     @EnabledSince(targetSdkVersion = VERSION_CODES.VANILLA_ICE_CREAM)
519     static final long FGS_INTRODUCE_TIME_LIMITS = 317799821L;
520 
521     // allowlisted packageName.
522     ArraySet<String> mAllowListWhileInUsePermissionInFgs = new ArraySet<>();
523 
524     String mCachedDeviceProvisioningPackage;
525 
526     // TODO: remove this after feature development is done
527     private static final SimpleDateFormat DATE_FORMATTER =
528             new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
529 
530     /**
531      * The BG-launch FGS restriction feature is going to be allowed only for apps targetSdkVersion
532      * is higher than R.
533      */
534     @ChangeId
535     @EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.S)
536     @Overridable
537     static final long FGS_BG_START_RESTRICTION_CHANGE_ID = 170668199L;
538 
539     /**
540      * If a service can not become foreground service due to BG-FGS-launch restriction or other
541      * reasons, throws an IllegalStateException.
542      */
543     @ChangeId
544     @EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.S)
545     static final long FGS_START_EXCEPTION_CHANGE_ID = 174041399L;
546 
547     /**
548      * If enabled, the FGS type check against the manifest FSG type will be enabled for
549      * instant apps too. Before U, this check was only done for non-instant apps.
550      */
551     @ChangeId
552     @EnabledAfter(targetSdkVersion = VERSION_CODES.TIRAMISU)
553     static final long FGS_TYPE_CHECK_FOR_INSTANT_APPS = 261055255L;
554 
555     final Runnable mLastAnrDumpClearer = new Runnable() {
556         @Override public void run() {
557             synchronized (mAm) {
558                 mLastAnrDump = null;
559             }
560         }
561     };
562 
563     /**
564      * Reference to the AppStateTracker service. No lock is needed as we'll assign with the same
565      * instance to it always.
566      */
567     AppStateTracker mAppStateTracker;
568 
569     /**
570      * Watch for apps being put into background restricted, so we can step their fg
571      * services down.
572      */
573     class BackgroundRestrictedListener implements AppStateTracker.BackgroundRestrictedAppListener {
574         @Override
updateBackgroundRestrictedForUidPackage(int uid, String packageName, boolean restricted)575         public void updateBackgroundRestrictedForUidPackage(int uid, String packageName,
576                 boolean restricted) {
577             synchronized (mAm) {
578                 mAm.mProcessList.updateBackgroundRestrictedForUidPackageLocked(
579                         uid, packageName, restricted);
580                 if (!isForegroundServiceAllowedInBackgroundRestricted(uid, packageName)
581                         && !isTempAllowedByAlarmClock(uid)) {
582                     stopAllForegroundServicesLocked(uid, packageName);
583                 }
584             }
585         }
586     }
587 
stopAllForegroundServicesLocked(final int uid, final String packageName)588     void stopAllForegroundServicesLocked(final int uid, final String packageName) {
589         final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
590         final int N = smap.mServicesByInstanceName.size();
591         final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
592         for (int i = 0; i < N; i++) {
593             final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
594             if (uid == r.serviceInfo.applicationInfo.uid
595                     || packageName.equals(r.serviceInfo.packageName)) {
596                 // If the FGS is started by temp allowlist of alarm-clock
597                 // (REASON_ALARM_MANAGER_ALARM_CLOCK), allow it to continue and do not stop it,
598                 // even the app is background-restricted.
599                 if (r.isForeground
600                         && r.mAllowStartForegroundAtEntering != REASON_ALARM_MANAGER_ALARM_CLOCK
601                         && !isDeviceProvisioningPackage(r.packageName)) {
602                     toStop.add(r);
603                 }
604             }
605         }
606 
607         // Now stop them all
608         final int numToStop = toStop.size();
609         if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
610             Slog.i(TAG, "Package " + packageName + "/" + uid
611                     + " in FAS with foreground services");
612         }
613         for (int i = 0; i < numToStop; i++) {
614             final ServiceRecord r = toStop.get(i);
615             if (DEBUG_FOREGROUND_SERVICE) {
616                 Slog.i(TAG, "  Stopping fg for service " + r);
617             }
618             setServiceForegroundInnerLocked(r, 0, null, 0, 0,
619                     0);
620         }
621     }
622 
623     /**
624      * Information about an app that is currently running one or more foreground services.
625      * (This maps directly to the running apps we show in the notification.)
626      */
627     static final class ActiveForegroundApp {
628         String mPackageName;
629         int mUid;
630         CharSequence mLabel;
631         boolean mShownWhileScreenOn;
632         boolean mAppOnTop;
633         boolean mShownWhileTop;
634         long mStartTime;
635         long mStartVisibleTime;
636         long mEndTime;
637         int mNumActive;
638 
639         // Temp output of foregroundAppShownEnoughLocked
640         long mHideTime;
641     }
642 
643     /**
644      * Information about services for a single user.
645      */
646     final class ServiceMap extends Handler {
647         final int mUserId;
648         final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
649         final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
650 
651         final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
652         /* XXX eventually I'd like to have this based on processes instead of services.
653          * That is, if we try to start two services in a row both running in the same
654          * process, this should be one entry in mStartingBackground for that one process
655          * that remains until all services in it are done.
656         final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
657                 = new ArrayMap<ProcessRecord, DelayingProcess>();
658         final ArrayList<DelayingProcess> mStartingProcessList
659                 = new ArrayList<DelayingProcess>();
660         */
661 
662         final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
663 
664         final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
665         final ArrayList<String> mPendingRemoveForegroundApps = new ArrayList<>();
666 
667         boolean mActiveForegroundAppsChanged;
668 
669         static final int MSG_BG_START_TIMEOUT = 1;
670         static final int MSG_UPDATE_FOREGROUND_APPS = 2;
671         static final int MSG_ENSURE_NOT_START_BG = 3;
672 
ServiceMap(Looper looper, int userId)673         ServiceMap(Looper looper, int userId) {
674             super(looper);
675             mUserId = userId;
676         }
677 
678         @Override
handleMessage(Message msg)679         public void handleMessage(Message msg) {
680             switch (msg.what) {
681                 case MSG_BG_START_TIMEOUT: {
682                     synchronized (mAm) {
683                         rescheduleDelayedStartsLocked();
684                     }
685                 } break;
686                 case MSG_UPDATE_FOREGROUND_APPS: {
687                     updateForegroundApps(this);
688                 } break;
689                 case MSG_ENSURE_NOT_START_BG: {
690                     synchronized (mAm) {
691                         rescheduleDelayedStartsLocked();
692                     }
693                 } break;
694             }
695         }
696 
ensureNotStartingBackgroundLocked(ServiceRecord r)697         void ensureNotStartingBackgroundLocked(ServiceRecord r) {
698             if (mStartingBackground.remove(r)) {
699                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
700                         "No longer background starting: " + r);
701                 removeMessages(MSG_ENSURE_NOT_START_BG);
702                 Message msg = obtainMessage(MSG_ENSURE_NOT_START_BG);
703                 sendMessage(msg);
704             }
705             if (mDelayedStartList.remove(r)) {
706                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
707             }
708         }
709 
rescheduleDelayedStartsLocked()710         void rescheduleDelayedStartsLocked() {
711             removeMessages(MSG_BG_START_TIMEOUT);
712             final long now = SystemClock.uptimeMillis();
713             for (int i=0, N=mStartingBackground.size(); i<N; i++) {
714                 ServiceRecord r = mStartingBackground.get(i);
715                 if (r.startingBgTimeout <= now) {
716                     Slog.i(TAG, "Waited long enough for: " + r);
717                     mStartingBackground.remove(i);
718                     N--;
719                     i--;
720                 }
721             }
722             while (mDelayedStartList.size() > 0
723                     && mStartingBackground.size() < mMaxStartingBackground) {
724                 ServiceRecord r = mDelayedStartList.remove(0);
725                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
726                         "REM FR DELAY LIST (exec next): " + r);
727                 if (DEBUG_DELAYED_SERVICE) {
728                     if (mDelayedStartList.size() > 0) {
729                         Slog.v(TAG_SERVICE, "Remaining delayed list:");
730                         for (int i=0; i<mDelayedStartList.size(); i++) {
731                             Slog.v(TAG_SERVICE, "  #" + i + ": " + mDelayedStartList.get(i));
732                         }
733                     }
734                 }
735                 r.delayed = false;
736                 if (r.pendingStarts.size() <= 0) {
737                     Slog.wtf(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
738                             + " delayedStop=" + r.delayedStop);
739                 } else {
740                     try {
741                         final ServiceRecord.StartItem si = r.pendingStarts.get(0);
742                         startServiceInnerLocked(this, si.intent, r, false, true, si.callingId,
743                                 si.mCallingProcessName, si.mCallingProcessState,
744                                 r.startRequested, si.mCallingPackageName);
745                     } catch (TransactionTooLargeException e) {
746                         // Ignore, nobody upstack cares.
747                     }
748                 }
749             }
750             if (mStartingBackground.size() > 0) {
751                 ServiceRecord next = mStartingBackground.get(0);
752                 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
753                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
754                         + ", can delay others up to " + when);
755                 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
756                 sendMessageAtTime(msg, when);
757             }
758             if (mStartingBackground.size() < mMaxStartingBackground) {
759                 mAm.backgroundServicesFinishedLocked(mUserId);
760             }
761         }
762     }
763 
ActiveServices(ActivityManagerService service)764     public ActiveServices(ActivityManagerService service) {
765         mAm = service;
766         int maxBg = 0;
767         try {
768             maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
769         } catch(RuntimeException e) {
770         }
771         mMaxStartingBackground = maxBg > 0
772                 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
773 
774         final IBinder b = ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);
775         this.mFGSLogger = new ForegroundServiceTypeLoggerModule();
776         this.mActiveServiceAnrTimer = new ProcessAnrTimer(service,
777                 ActivityManagerService.SERVICE_TIMEOUT_MSG,
778                 "SERVICE_TIMEOUT",
779                 new AnrTimer.Args().freeze(true));
780         this.mShortFGSAnrTimer = new ServiceAnrTimer(service,
781                 ActivityManagerService.SERVICE_SHORT_FGS_ANR_TIMEOUT_MSG,
782                 "SHORT_FGS_TIMEOUT");
783         this.mServiceFGAnrTimer = new ServiceAnrTimer(service,
784                 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG,
785                 "SERVICE_FOREGROUND_TIMEOUT");
786     }
787 
systemServicesReady()788     void systemServicesReady() {
789         getAppStateTracker().addBackgroundRestrictedAppListener(new BackgroundRestrictedListener());
790         mAppWidgetManagerInternal = LocalServices.getService(AppWidgetManagerInternal.class);
791         setAllowListWhileInUsePermissionInFgs();
792         initSystemExemptedFgsTypePermission();
793         initMediaProjectFgsTypeCustomPermission();
794     }
795 
getAppStateTracker()796     private AppStateTracker getAppStateTracker() {
797         if (mAppStateTracker == null) {
798             mAppStateTracker = LocalServices.getService(AppStateTracker.class);
799         }
800         return mAppStateTracker;
801     }
802 
setAllowListWhileInUsePermissionInFgs()803     private void setAllowListWhileInUsePermissionInFgs() {
804         final String attentionServicePackageName =
805                 mAm.mContext.getPackageManager().getAttentionServicePackageName();
806         if (!TextUtils.isEmpty(attentionServicePackageName)) {
807             mAllowListWhileInUsePermissionInFgs.add(attentionServicePackageName);
808         }
809         final String systemCaptionsServicePackageName =
810                 mAm.mContext.getPackageManager().getSystemCaptionsServicePackageName();
811         if (!TextUtils.isEmpty(systemCaptionsServicePackageName)) {
812             mAllowListWhileInUsePermissionInFgs.add(systemCaptionsServicePackageName);
813         }
814     }
815 
getServiceByNameLocked(ComponentName name, int callingUser)816     ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
817         // TODO: Deal with global services
818         if (DEBUG_MU)
819             Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
820         return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
821     }
822 
hasBackgroundServicesLocked(int callingUser)823     boolean hasBackgroundServicesLocked(int callingUser) {
824         ServiceMap smap = mServiceMap.get(callingUser);
825         return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
826     }
827 
hasForegroundServiceNotificationLocked(String pkg, int userId, String channelId)828     boolean hasForegroundServiceNotificationLocked(String pkg, int userId, String channelId) {
829         final ServiceMap smap = mServiceMap.get(userId);
830         if (smap != null) {
831             for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
832                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
833                 if (sr.appInfo.packageName.equals(pkg) && sr.isForeground) {
834                     if (sr.foregroundNoti != null
835                             && Objects.equals(sr.foregroundNoti.getChannelId(), channelId)) {
836                         if (DEBUG_FOREGROUND_SERVICE) {
837                             Slog.d(TAG_SERVICE, "Channel u" + userId + "/pkg=" + pkg
838                                     + "/channelId=" + channelId
839                                     + " has fg service notification");
840                         }
841                         return true;
842                     }
843                 }
844             }
845         }
846         return false;
847     }
848 
getServiceMapLocked(int callingUser)849     private ServiceMap getServiceMapLocked(int callingUser) {
850         ServiceMap smap = mServiceMap.get(callingUser);
851         if (smap == null) {
852             smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
853             mServiceMap.put(callingUser, smap);
854         }
855         return smap;
856     }
857 
getServicesLocked(int callingUser)858     ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
859         return getServiceMapLocked(callingUser).mServicesByInstanceName;
860     }
861 
appRestrictedAnyInBackground(final int uid, final String packageName)862     private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
863         final AppStateTracker appStateTracker = getAppStateTracker();
864         if (appStateTracker != null) {
865             return appStateTracker.isAppBackgroundRestricted(uid, packageName);
866         }
867         return false;
868     }
869 
updateAppRestrictedAnyInBackgroundLocked(final int uid, final String packageName)870     void updateAppRestrictedAnyInBackgroundLocked(final int uid, final String packageName) {
871         final boolean restricted = appRestrictedAnyInBackground(uid, packageName);
872         final UidRecord uidRec = mAm.mProcessList.getUidRecordLOSP(uid);
873         if (uidRec != null) {
874             final ProcessRecord app = uidRec.getProcessInPackage(packageName);
875             if (app != null) {
876                 app.mState.setBackgroundRestricted(restricted);
877             }
878         }
879     }
880 
getProcessNameForService(ServiceInfo sInfo, ComponentName name, String callingPackage, String instanceName, boolean isSdkSandbox, boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess)881     static String getProcessNameForService(ServiceInfo sInfo, ComponentName name,
882             String callingPackage, String instanceName, boolean isSdkSandbox,
883             boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess) {
884         if (isSdkSandbox) {
885             // For SDK sandbox, the process name is passed in as the instanceName
886             return instanceName;
887         }
888         if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0
889                 || (inPrivateSharedIsolatedProcess && !isDefaultProcessService(sInfo))) {
890             // For regular processes, or private package-shared isolated processes, just the name
891             // in sInfo
892             return sInfo.processName;
893         }
894         // Isolated processes remain.
895         if (inSharedIsolatedProcess) {
896             // Shared isolated processes are scoped to the calling package
897             return callingPackage + ":ishared:" + instanceName;
898         } else {
899             return sInfo.processName + ":" + name.getClassName();
900         }
901     }
902 
isDefaultProcessService(ServiceInfo serviceInfo)903     private static boolean isDefaultProcessService(ServiceInfo serviceInfo) {
904         return serviceInfo.applicationInfo.processName.equals(serviceInfo.processName);
905     }
906 
traceInstant(@onNull String message, @NonNull ServiceRecord service)907     private static void traceInstant(@NonNull String message, @NonNull ServiceRecord service) {
908         if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
909             return;
910         }
911         final String serviceName = (service.getComponentName() != null)
912                 ? service.getComponentName().toShortString() : "(?)";
913         Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER, message + serviceName);
914     }
915 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)916     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
917             int callingPid, int callingUid, boolean fgRequired, String callingPackage,
918             @Nullable String callingFeatureId, final int userId, boolean isSdkSandboxService,
919             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)
920             throws TransactionTooLargeException {
921         return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
922                 callingPackage, callingFeatureId, userId, BackgroundStartPrivileges.NONE,
923                 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
924                 instanceName);
925     }
926 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId, BackgroundStartPrivileges backgroundStartPrivileges)927     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
928             int callingPid, int callingUid, boolean fgRequired,
929             String callingPackage, @Nullable String callingFeatureId, final int userId,
930             BackgroundStartPrivileges backgroundStartPrivileges)
931             throws TransactionTooLargeException {
932         return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
933                 callingPackage, callingFeatureId, userId, backgroundStartPrivileges,
934                 false /* isSdkSandboxService */, INVALID_UID, null, null);
935     }
936 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId, BackgroundStartPrivileges backgroundStartPrivileges, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)937     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
938             int callingPid, int callingUid, boolean fgRequired,
939             String callingPackage, @Nullable String callingFeatureId, final int userId,
940             BackgroundStartPrivileges backgroundStartPrivileges, boolean isSdkSandboxService,
941             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)
942             throws TransactionTooLargeException {
943         if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
944                 + " type=" + resolvedType + " args=" + service.getExtras());
945 
946         final boolean callerFg;
947         if (caller != null) {
948             final ProcessRecord callerApp = mAm.getRecordForAppLOSP(caller);
949             if (callerApp == null) {
950                 throw new SecurityException(
951                         "Unable to find app for caller " + caller
952                         + " (pid=" + callingPid
953                         + ") when starting service " + service);
954             }
955             callerFg = callerApp.mState.getSetSchedGroup() != ProcessList.SCHED_GROUP_BACKGROUND;
956         } else {
957             callerFg = true;
958         }
959 
960         ServiceLookupResult res = retrieveServiceLocked(service, instanceName, isSdkSandboxService,
961                 sdkSandboxClientAppUid, sdkSandboxClientAppPackage, resolvedType, callingPackage,
962                 callingPid, callingUid, userId, true, callerFg, false, false, null, false, false);
963         if (res == null) {
964             return null;
965         }
966         if (res.record == null) {
967             return new ComponentName("!", res.permission != null
968                     ? res.permission : "private to package");
969         }
970 
971         ServiceRecord r = res.record;
972 
973         traceInstant("startService(): ", r);
974 
975         // Note, when startService() or startForegroundService() is called on an already
976         // running SHORT_SERVICE FGS, the call will succeed (i.e. we won't throw
977         // ForegroundServiceStartNotAllowedException), even when the service is already timed
978         // out. This is because these APIs will essentially only change the "started" state
979         // of the service, and it won't affect "the foreground-ness" of the service, or the type
980         // of the FGS.
981         // However, this call will still _not_ extend the SHORT_SERVICE timeout either.
982         // Also, if the app tries to change the type of the FGS later (using
983         // Service.startForeground()), at that point we will consult the BFSL check and the timeout
984         // and make the necessary decisions.
985         setFgsRestrictionLocked(callingPackage, callingPid, callingUid, service, r, userId,
986                 backgroundStartPrivileges, false /* isBindService */);
987 
988         if (!mAm.mUserController.exists(r.userId)) {
989             Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
990             return null;
991         }
992 
993         // For the SDK sandbox, we start the service on behalf of the client app.
994         final int appUid = isSdkSandboxService ? sdkSandboxClientAppUid : r.appInfo.uid;
995         final String appPackageName =
996                 isSdkSandboxService ? sdkSandboxClientAppPackage : r.packageName;
997         int appTargetSdkVersion = r.appInfo.targetSdkVersion;
998         if (isSdkSandboxService) {
999             try {
1000                 appTargetSdkVersion = AppGlobals.getPackageManager().getApplicationInfo(
1001                         appPackageName, ActivityManagerService.STOCK_PM_FLAGS,
1002                         userId).targetSdkVersion;
1003             } catch (RemoteException ignored) {
1004             }
1005         }
1006 
1007         // If we're starting indirectly (e.g. from PendingIntent), figure out whether
1008         // we're launching into an app in a background state.  This keys off of the same
1009         // idleness state tracking as e.g. O+ background service start policy.
1010         final boolean bgLaunch = !mAm.isUidActiveLOSP(appUid);
1011 
1012         // If the app has strict background restrictions, we treat any bg service
1013         // start analogously to the legacy-app forced-restrictions case, regardless
1014         // of its target SDK version.
1015         boolean forcedStandby = false;
1016         if (bgLaunch
1017                 && appRestrictedAnyInBackground(appUid, appPackageName)
1018                 && !isTempAllowedByAlarmClock(appUid)
1019                 && !isDeviceProvisioningPackage(appPackageName)) {
1020             if (DEBUG_FOREGROUND_SERVICE) {
1021                 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
1022                         + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
1023             }
1024             forcedStandby = true;
1025         }
1026 
1027         if (fgRequired) {
1028             logFgsBackgroundStart(r);
1029             if (!r.isFgsAllowedStart() && isBgFgsRestrictionEnabled(r, callingUid)) {
1030                 String msg = "startForegroundService() not allowed due to "
1031                         + "mAllowStartForeground false: service "
1032                         + r.shortInstanceName;
1033                 Slog.w(TAG, msg);
1034                 showFgsBgRestrictedNotificationLocked(r);
1035                 logFGSStateChangeLocked(r,
1036                         FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED,
1037                         0, FGS_STOP_REASON_UNKNOWN, FGS_TYPE_POLICY_CHECK_UNKNOWN,
1038                         FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
1039                         false /* fgsRestrictionRecalculated */
1040                 );
1041                 if (CompatChanges.isChangeEnabled(FGS_START_EXCEPTION_CHANGE_ID, callingUid)) {
1042                     throw new ForegroundServiceStartNotAllowedException(msg);
1043                 }
1044                 return null;
1045             }
1046         }
1047 
1048         // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
1049         boolean forceSilentAbort = false;
1050         if (fgRequired) {
1051             final int mode = mAm.getAppOpsManager().checkOpNoThrow(
1052                     AppOpsManager.OP_START_FOREGROUND, appUid, appPackageName);
1053             switch (mode) {
1054                 case AppOpsManager.MODE_ALLOWED:
1055                 case AppOpsManager.MODE_DEFAULT:
1056                     // All okay.
1057                     break;
1058                 case AppOpsManager.MODE_IGNORED:
1059                     // Not allowed, fall back to normal start service, failing siliently
1060                     // if background check restricts that.
1061                     Slog.w(TAG, "startForegroundService not allowed due to app op: service "
1062                             + service + " to " + r.shortInstanceName
1063                             + " from pid=" + callingPid + " uid=" + callingUid
1064                             + " pkg=" + callingPackage);
1065                     fgRequired = false;
1066                     forceSilentAbort = true;
1067                     break;
1068                 default:
1069                     return new ComponentName("!!", "foreground not allowed as per app op");
1070             }
1071         }
1072 
1073         // If this isn't a direct-to-foreground start, check our ability to kick off an
1074         // arbitrary service.
1075         if (forcedStandby || (!r.startRequested && !fgRequired)) {
1076             // Before going further -- if this app is not allowed to start services in the
1077             // background, then at this point we aren't going to let it period.
1078             final int allowed = mAm.getAppStartModeLOSP(appUid, appPackageName, appTargetSdkVersion,
1079                     callingPid, false, false, forcedStandby);
1080             if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
1081                 Slog.w(TAG, "Background start not allowed: service "
1082                         + service + " to " + r.shortInstanceName
1083                         + " from pid=" + callingPid + " uid=" + callingUid
1084                         + " pkg=" + callingPackage + " startFg?=" + fgRequired);
1085                 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
1086                     // In this case we are silently disabling the app, to disrupt as
1087                     // little as possible existing apps.
1088                     return null;
1089                 }
1090                 if (forcedStandby) {
1091                     // This is an O+ app, but we might be here because the user has placed
1092                     // it under strict background restrictions.  Don't punish the app if it's
1093                     // trying to do the right thing but we're denying it for that reason.
1094                     if (fgRequired) {
1095                         if (DEBUG_BACKGROUND_CHECK) {
1096                             Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
1097                         }
1098                         return null;
1099                     }
1100                 }
1101                 // This app knows it is in the new model where this operation is not
1102                 // allowed, so tell it what has happened.
1103                 UidRecord uidRec = mAm.mProcessList.getUidRecordLOSP(appUid);
1104                 return new ComponentName("?", "app is in background uid " + uidRec);
1105             }
1106         }
1107 
1108         // At this point we've applied allowed-to-start policy based on whether this was
1109         // an ordinary startService() or a startForegroundService().  Now, only require that
1110         // the app follow through on the startForegroundService() -> startForeground()
1111         // contract if it actually targets O+.
1112         if (appTargetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
1113             if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
1114                 Slog.i(TAG, "startForegroundService() but host targets "
1115                         + appTargetSdkVersion + " - not requiring startForeground()");
1116             }
1117             fgRequired = false;
1118         }
1119 
1120         final ProcessRecord callingApp;
1121         synchronized (mAm.mPidsSelfLocked) {
1122             callingApp = mAm.mPidsSelfLocked.get(callingPid);
1123         }
1124         final String callingProcessName = callingApp != null
1125                 ? callingApp.processName : callingPackage;
1126         final int callingProcessState =
1127                 callingApp != null && callingApp.getThread() != null && !callingApp.isKilled()
1128                 ? callingApp.mState.getCurProcState() : ActivityManager.PROCESS_STATE_UNKNOWN;
1129         r.updateProcessStateOnRequest();
1130 
1131         // The package could be frozen (meaning it's doing surgery), defer the actual
1132         // start until the package is unfrozen.
1133         if (deferServiceBringupIfFrozenLocked(r, service, callingPackage, callingFeatureId,
1134                 callingUid, callingPid, callingProcessName,
1135                 callingProcessState, fgRequired, callerFg, userId,
1136                 backgroundStartPrivileges, false, null)) {
1137             return null;
1138         }
1139 
1140         // If permissions need a review before any of the app components can run,
1141         // we do not start the service and launch a review activity if the calling app
1142         // is in the foreground passing it a pending intent to start the service when
1143         // review is completed.
1144 
1145         // XXX This is not dealing with fgRequired!
1146         if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage, callingFeatureId,
1147                 callingUid, service, callerFg, userId, false, null)) {
1148             return null;
1149         }
1150 
1151         // If what the client try to start/connect was an alias, then we need to return the
1152         // alias component name to the client, not the "target" component name, which is
1153         // what realResult contains.
1154         final ComponentName realResult =
1155                 startServiceInnerLocked(r, service, callingUid, callingPid,
1156                         callingProcessName, callingProcessState,
1157                         fgRequired, callerFg,
1158                         backgroundStartPrivileges, callingPackage);
1159         if (res.aliasComponent != null
1160                 && !realResult.getPackageName().startsWith("!")
1161                 && !realResult.getPackageName().startsWith("?")) {
1162             return res.aliasComponent;
1163         } else {
1164             return realResult;
1165         }
1166     }
1167 
shouldAllowBootCompletedStart(ServiceRecord r, int foregroundServiceType)1168     private boolean shouldAllowBootCompletedStart(ServiceRecord r, int foregroundServiceType) {
1169         @PowerExemptionManager.ReasonCode final int fgsStartReasonCode = r.getFgsAllowStart();
1170         if (Flags.fgsBootCompleted()
1171                 && CompatChanges.isChangeEnabled(FGS_BOOT_COMPLETED_RESTRICTIONS, r.appInfo.uid)
1172                 && fgsStartReasonCode == PowerExemptionManager.REASON_BOOT_COMPLETED) {
1173             // Filter through types
1174             return ((foregroundServiceType & mAm.mConstants.FGS_BOOT_COMPLETED_ALLOWLIST) != 0);
1175         }
1176         // Not BOOT_COMPLETED
1177         return true;
1178     }
1179 
startServiceInnerLocked(ServiceRecord r, Intent service, int callingUid, int callingPid, String callingProcessName, int callingProcessState, boolean fgRequired, boolean callerFg, BackgroundStartPrivileges backgroundStartPrivileges, String callingPackage)1180     private ComponentName startServiceInnerLocked(ServiceRecord r, Intent service,
1181             int callingUid, int callingPid, String callingProcessName,
1182             int callingProcessState, boolean fgRequired, boolean callerFg,
1183             BackgroundStartPrivileges backgroundStartPrivileges, String callingPackage)
1184             throws TransactionTooLargeException {
1185         NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
1186                 service, callingUid, r.packageName, r.userId);
1187         if (unscheduleServiceRestartLocked(r, callingUid, false)) {
1188             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
1189         }
1190         final boolean wasStartRequested = r.startRequested;
1191         r.lastActivity = SystemClock.uptimeMillis();
1192         r.startRequested = true;
1193         r.delayedStop = false;
1194         r.fgRequired = fgRequired;
1195         r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
1196                 service, neededGrants, callingUid, callingProcessName, callingPackage,
1197                 callingProcessState));
1198 
1199         // We want to allow scheduling user-initiated jobs when the app is running a
1200         // foreground service that was started in the same conditions that allows for scheduling
1201         // UI jobs. More explicitly, we want to allow scheduling UI jobs when the app is running
1202         // an FGS that started when the app was in the TOP or a BAL-approved state.
1203         final boolean isFgs = r.isForeground || r.fgRequired;
1204         if (isFgs) {
1205             // As of Android UDC, the conditions required for the while-in-use permissions
1206             // are the same conditions that we want, so we piggyback on that logic.
1207             // Use that as a shortcut if possible to avoid having to recheck all the conditions.
1208             final boolean whileInUseAllowsUiJobScheduling =
1209                     ActivityManagerService.doesReasonCodeAllowSchedulingUserInitiatedJobs(
1210                             r.getFgsAllowWiu_forStart(), callingUid);
1211             r.updateAllowUiJobScheduling(whileInUseAllowsUiJobScheduling
1212                     || mAm.canScheduleUserInitiatedJobs(callingUid, callingPid, callingPackage));
1213         } else {
1214             r.updateAllowUiJobScheduling(false);
1215         }
1216 
1217         if (fgRequired) {
1218             // We are now effectively running a foreground service.
1219             synchronized (mAm.mProcessStats.mLock) {
1220                 final ServiceState stracker = r.getTracker();
1221                 if (stracker != null) {
1222                     stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
1223                             SystemClock.uptimeMillis()); // Use current time, not lastActivity.
1224                 }
1225             }
1226             mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
1227                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null,
1228                     true, false, null, false, AppOpsManager.ATTRIBUTION_FLAGS_NONE,
1229                     AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE);
1230         }
1231 
1232         final ServiceMap smap = getServiceMapLocked(r.userId);
1233         boolean addToStarting = false;
1234         if (!callerFg && !fgRequired && r.app == null
1235                 && mAm.mUserController.hasStartedUserState(r.userId)) {
1236             ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid);
1237             if (proc == null || proc.mState.getCurProcState() > PROCESS_STATE_RECEIVER) {
1238                 // If this is not coming from a foreground caller, then we may want
1239                 // to delay the start if there are already other background services
1240                 // that are starting.  This is to avoid process start spam when lots
1241                 // of applications are all handling things like connectivity broadcasts.
1242                 // We only do this for cached processes, because otherwise an application
1243                 // can have assumptions about calling startService() for a service to run
1244                 // in its own process, and for that process to not be killed before the
1245                 // service is started.  This is especially the case for receivers, which
1246                 // may start a service in onReceive() to do some additional work and have
1247                 // initialized some global state as part of that.
1248                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
1249                         + r + " in " + proc);
1250                 if (r.delayed) {
1251                     // This service is already scheduled for a delayed start; just leave
1252                     // it still waiting.
1253                     if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
1254                     return r.name;
1255                 }
1256                 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
1257                     // Something else is starting, delay!
1258                     Slog.i(TAG_SERVICE, "Delaying start of: " + r);
1259                     smap.mDelayedStartList.add(r);
1260                     r.delayed = true;
1261                     return r.name;
1262                 }
1263                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
1264                 addToStarting = true;
1265             } else if (proc.mState.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
1266                 // We slightly loosen when we will enqueue this new service as a background
1267                 // starting service we are waiting for, to also include processes that are
1268                 // currently running other services or receivers.
1269                 addToStarting = true;
1270                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1271                         "Not delaying, but counting as bg: " + r);
1272             } else if (DEBUG_DELAYED_STARTS) {
1273                 StringBuilder sb = new StringBuilder(128);
1274                 sb.append("Not potential delay (state=").append(proc.mState.getCurProcState())
1275                         .append(' ').append(proc.mState.getAdjType());
1276                 String reason = proc.mState.makeAdjReason();
1277                 if (reason != null) {
1278                     sb.append(' ');
1279                     sb.append(reason);
1280                 }
1281                 sb.append("): ");
1282                 sb.append(r.toString());
1283                 Slog.v(TAG_SERVICE, sb.toString());
1284             }
1285         } else if (DEBUG_DELAYED_STARTS) {
1286             if (callerFg || fgRequired) {
1287                 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
1288                         + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
1289             } else if (r.app != null) {
1290                 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
1291             } else {
1292                 Slog.v(TAG_SERVICE,
1293                         "Not potential delay (user " + r.userId + " not started): " + r);
1294             }
1295         }
1296         if (backgroundStartPrivileges.allowsAny()) {
1297             r.allowBgActivityStartsOnServiceStart(backgroundStartPrivileges);
1298         }
1299         ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting,
1300                 callingUid, callingProcessName, callingProcessState,
1301                 wasStartRequested, callingPackage);
1302         return cmp;
1303     }
1304 
requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r, String callingPackage, @Nullable String callingFeatureId, int callingUid, Intent service, boolean callerFg, final int userId, final boolean isBinding, final IServiceConnection connection)1305     private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
1306             String callingPackage, @Nullable String callingFeatureId, int callingUid,
1307             Intent service, boolean callerFg, final int userId,
1308             final boolean isBinding, final IServiceConnection connection) {
1309         if (mAm.getPackageManagerInternal().isPermissionsReviewRequired(
1310                 r.packageName, r.userId)) {
1311 
1312             // Show a permission review UI only for starting/binding from a foreground app
1313             if (!callerFg) {
1314                 Slog.w(TAG, "u" + r.userId
1315                         + (isBinding ? " Binding" : " Starting") + " a service in package"
1316                         + r.packageName + " requires a permissions review");
1317                 return false;
1318             }
1319 
1320             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1321             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1322                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
1323                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1324             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
1325 
1326             if (isBinding) {
1327                 RemoteCallback callback = new RemoteCallback(
1328                         new RemoteCallback.OnResultListener() {
1329                             @Override
1330                             public void onResult(Bundle result) {
1331                                 synchronized (mAm) {
1332                                     final long identity = mAm.mInjector.clearCallingIdentity();
1333                                     try {
1334                                         if (!mPendingServices.contains(r)) {
1335                                             return;
1336                                         }
1337                                         // If there is still a pending record, then the service
1338                                         // binding request is still valid, so hook them up. We
1339                                         // proceed only if the caller cleared the review requirement
1340                                         // otherwise we unbind because the user didn't approve.
1341                                         if (!mAm.getPackageManagerInternal()
1342                                                 .isPermissionsReviewRequired(r.packageName,
1343                                                     r.userId)) {
1344                                             try {
1345                                                 bringUpServiceLocked(r,
1346                                                         service.getFlags(),
1347                                                         callerFg,
1348                                                         false /* whileRestarting */,
1349                                                         false /* permissionsReviewRequired */,
1350                                                         false /* packageFrozen */,
1351                                                         true /* enqueueOomAdj */,
1352                                                         SERVICE_BIND_OOMADJ_POLICY_LEGACY);
1353                                             } catch (RemoteException e) {
1354                                                 /* ignore - local call */
1355                                             } finally {
1356                                                 /* Will be a no-op if nothing pending */
1357                                                 mAm.updateOomAdjPendingTargetsLocked(
1358                                                         OOM_ADJ_REASON_START_SERVICE);
1359                                             }
1360                                         } else {
1361                                             unbindServiceLocked(connection);
1362                                         }
1363                                     } finally {
1364                                         mAm.mInjector.restoreCallingIdentity(identity);
1365                                     }
1366                                 }
1367                             }
1368                         });
1369                 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1370             } else { // Starting a service
1371                 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
1372                         ActivityManager.INTENT_SENDER_SERVICE, callingPackage, callingFeatureId,
1373                         callingUid, userId, null, null, 0, new Intent[]{service},
1374                         new String[]{service.resolveType(mAm.mContext.getContentResolver())},
1375                         PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
1376                         | PendingIntent.FLAG_IMMUTABLE, null);
1377                 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
1378             }
1379 
1380             if (DEBUG_PERMISSIONS_REVIEW) {
1381                 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
1382                         + r.packageName);
1383             }
1384 
1385             mAm.mHandler.post(new Runnable() {
1386                 @Override
1387                 public void run() {
1388                     mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1389                 }
1390             });
1391 
1392             return false;
1393         }
1394 
1395         return  true;
1396     }
1397 
1398     /**
1399      * Defer the service starting/binding until the package is unfrozen, if it's currently frozen.
1400      *
1401      * @return {@code true} if the binding is deferred because it's frozen.
1402      */
1403     @GuardedBy("mAm")
deferServiceBringupIfFrozenLocked(ServiceRecord s, Intent serviceIntent, String callingPackage, @Nullable String callingFeatureId, int callingUid, int callingPid, String callingProcessName, int callingProcessState, boolean fgRequired, boolean callerFg, int userId, BackgroundStartPrivileges backgroundStartPrivileges, boolean isBinding, IServiceConnection connection)1404     private boolean deferServiceBringupIfFrozenLocked(ServiceRecord s, Intent serviceIntent,
1405             String callingPackage, @Nullable String callingFeatureId,
1406             int callingUid, int callingPid, String callingProcessName,
1407             int callingProcessState, boolean fgRequired, boolean callerFg, int userId,
1408             BackgroundStartPrivileges backgroundStartPrivileges,
1409             boolean isBinding, IServiceConnection connection) {
1410         final PackageManagerInternal pm = mAm.getPackageManagerInternal();
1411         final boolean frozen = pm.isPackageFrozen(s.packageName, callingUid, s.userId);
1412         if (!frozen) {
1413             // Not frozen, it's okay to go
1414             return false;
1415         }
1416         ArrayList<Runnable> curPendingBringups = mPendingBringups.get(s);
1417         if (curPendingBringups == null) {
1418             curPendingBringups = new ArrayList<>();
1419             mPendingBringups.put(s, curPendingBringups);
1420         }
1421         curPendingBringups.add(new Runnable() {
1422             @Override
1423             public void run() {
1424                 synchronized (mAm) {
1425                     if (!mPendingBringups.containsKey(s)) {
1426                         return;
1427                     }
1428                     // binding request is still valid, so hook them up.
1429                     // Before doing so, check if it requires a permission review.
1430                     if (!requestStartTargetPermissionsReviewIfNeededLocked(s,
1431                                 callingPackage, callingFeatureId, callingUid,
1432                                 serviceIntent, callerFg, userId, isBinding, connection)) {
1433                         // Let's wait for the user approval.
1434                         return;
1435                     }
1436                     if (isBinding) {
1437                         try {
1438                             bringUpServiceLocked(s, serviceIntent.getFlags(), callerFg,
1439                                     false /* whileRestarting */,
1440                                     false /* permissionsReviewRequired */,
1441                                     false /* packageFrozen */,
1442                                     true /* enqueueOomAdj */,
1443                                     SERVICE_BIND_OOMADJ_POLICY_LEGACY);
1444                         } catch (TransactionTooLargeException e) {
1445                             /* ignore - local call */
1446                         } finally {
1447                             /* Will be a no-op if nothing pending */
1448                             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
1449                         }
1450                     } else { // Starting a service
1451                         try {
1452                             startServiceInnerLocked(s, serviceIntent, callingUid, callingPid,
1453                                     callingProcessName, callingProcessState, fgRequired, callerFg,
1454                                     backgroundStartPrivileges, callingPackage);
1455                         } catch (TransactionTooLargeException e) {
1456                             /* ignore - local call */
1457                         }
1458                     }
1459                 }
1460             }
1461         });
1462         return true;
1463     }
1464 
1465     @GuardedBy("mAm")
schedulePendingServiceStartLocked(String packageName, int userId)1466     void schedulePendingServiceStartLocked(String packageName, int userId) {
1467         int totalPendings = mPendingBringups.size();
1468         for (int i = totalPendings - 1; i >= 0 && totalPendings > 0;) {
1469             final ServiceRecord r = mPendingBringups.keyAt(i);
1470             if (r.userId != userId || !TextUtils.equals(r.packageName, packageName)) {
1471                 i--;
1472                 continue;
1473             }
1474             final ArrayList<Runnable> curPendingBringups = mPendingBringups.valueAt(i);
1475             if (curPendingBringups != null) {
1476                 for (int j = curPendingBringups.size() - 1; j >= 0; j--) {
1477                     curPendingBringups.get(j).run();
1478                 }
1479                 curPendingBringups.clear();
1480             }
1481             // Now, how many remaining ones we have after calling into above runnables
1482             final int curTotalPendings = mPendingBringups.size();
1483             // Don't call removeAt() here, as it could have been removed already by above runnables
1484             mPendingBringups.remove(r);
1485             if (totalPendings != curTotalPendings) {
1486                 // Okay, within the above Runnable.run(), the mPendingBringups is altered.
1487                 // Restart the loop, it won't call into those finished runnables
1488                 // since we've cleared the curPendingBringups above.
1489                 totalPendings = mPendingBringups.size();
1490                 i = totalPendings - 1;
1491             } else {
1492                 totalPendings = mPendingBringups.size();
1493                 i--;
1494             }
1495         }
1496     }
1497 
startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting, int callingUid, String callingProcessName, int callingProcessState, boolean wasStartRequested, String callingPackage)1498     ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
1499             boolean callerFg, boolean addToStarting, int callingUid, String callingProcessName,
1500             int callingProcessState, boolean wasStartRequested, String callingPackage)
1501             throws TransactionTooLargeException {
1502         synchronized (mAm.mProcessStats.mLock) {
1503             final ServiceState stracker = r.getTracker();
1504             if (stracker != null) {
1505                 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(),
1506                         SystemClock.uptimeMillis()); // Use current time, not lastActivity.
1507             }
1508         }
1509         r.callStart = false;
1510 
1511         final int uid = r.appInfo.uid;
1512         final String packageName = r.name.getPackageName();
1513         final String serviceName = r.name.getClassName();
1514         FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, uid, packageName,
1515                 serviceName, FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__START);
1516         mAm.mBatteryStatsService.noteServiceStartRunning(uid, packageName, serviceName);
1517         final ProcessRecord hostApp = r.app;
1518         final boolean wasStopped = hostApp == null ? wasStopped(r) : false;
1519         final boolean firstLaunch =
1520                 hostApp == null ? !mAm.wasPackageEverLaunched(r.packageName, r.userId) : false;
1521 
1522         String error = bringUpServiceLocked(r, service.getFlags(), callerFg,
1523                 false /* whileRestarting */,
1524                 false /* permissionsReviewRequired */,
1525                 false /* packageFrozen */,
1526                 true /* enqueueOomAdj */,
1527                 SERVICE_BIND_OOMADJ_POLICY_LEGACY);
1528         /* Will be a no-op if nothing pending */
1529         mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
1530         if (error != null) {
1531             return new ComponentName("!!", error);
1532         }
1533 
1534         final int packageState = wasStopped
1535                 ? SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED
1536                 : SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL;
1537         if (DEBUG_PROCESSES) {
1538             Slog.d(TAG, "Logging startService for " + packageName + ", stopped="
1539                     + wasStopped + ", firstLaunch=" + firstLaunch + ", intent=" + service
1540                     + ", r.app=" + r.app);
1541         }
1542         FrameworkStatsLog.write(SERVICE_REQUEST_EVENT_REPORTED, uid, callingUid,
1543                 service.getAction(),
1544                 SERVICE_REQUEST_EVENT_REPORTED__REQUEST_TYPE__START, false,
1545                 r.app == null || r.app.getThread() == null
1546                 ? SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD
1547                 : (wasStartRequested || !r.getConnections().isEmpty()
1548                 ? SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_HOT
1549                 : SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM),
1550                 getShortProcessNameForStats(callingUid, callingProcessName),
1551                 getShortServiceNameForStats(r),
1552                 packageState,
1553                 packageName,
1554                 callingPackage,
1555                 callingProcessState,
1556                 r.mProcessStateOnRequest,
1557                 firstLaunch,
1558                 0L /* TODO: stoppedDuration */);
1559 
1560         if (r.startRequested && addToStarting) {
1561             boolean first = smap.mStartingBackground.size() == 0;
1562             smap.mStartingBackground.add(r);
1563             r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
1564             if (DEBUG_DELAYED_SERVICE) {
1565                 RuntimeException here = new RuntimeException("here");
1566                 here.fillInStackTrace();
1567                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
1568             } else if (DEBUG_DELAYED_STARTS) {
1569                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
1570             }
1571             if (first) {
1572                 smap.rescheduleDelayedStartsLocked();
1573             }
1574         } else if (callerFg || r.fgRequired) {
1575             smap.ensureNotStartingBackgroundLocked(r);
1576         }
1577 
1578         return r.name;
1579     }
1580 
getShortProcessNameForStats(int uid, String processName)1581     private @Nullable String getShortProcessNameForStats(int uid, String processName) {
1582         final String[] packages = mAm.mContext.getPackageManager().getPackagesForUid(uid);
1583         if (packages != null && packages.length == 1) {
1584             // Not the shared UID case, let's see if the package name equals to the process name.
1585             if (TextUtils.equals(packages[0], processName)) {
1586                 // same name, just return null here.
1587                 return null;
1588             } else if (processName != null && processName.startsWith(packages[0])) {
1589                 // return the suffix of the process name
1590                 return processName.substring(packages[0].length());
1591             }
1592         }
1593         // return the full process name.
1594         return processName;
1595     }
1596 
getShortServiceNameForStats(@onNull ServiceRecord r)1597     private @Nullable String getShortServiceNameForStats(@NonNull ServiceRecord r) {
1598         final ComponentName cn = r.getComponentName();
1599         return cn != null ? cn.getShortClassName() : null;
1600     }
1601 
stopServiceLocked(ServiceRecord service, boolean enqueueOomAdj)1602     private void stopServiceLocked(ServiceRecord service, boolean enqueueOomAdj) {
1603         traceInstant("stopService(): ", service);
1604         try {
1605             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "stopServiceLocked()");
1606             if (service.delayed) {
1607                 // If service isn't actually running, but is being held in the
1608                 // delayed list, then we need to keep it started but note that it
1609                 // should be stopped once no longer delayed.
1610                 if (DEBUG_DELAYED_STARTS) {
1611                     Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
1612                 }
1613                 service.delayedStop = true;
1614                 return;
1615             }
1616 
1617             maybeStopShortFgsTimeoutLocked(service);
1618             maybeStopFgsTimeoutLocked(service);
1619 
1620             final int uid = service.appInfo.uid;
1621             final String packageName = service.name.getPackageName();
1622             final String serviceName = service.name.getClassName();
1623             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, uid, packageName,
1624                     serviceName, FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
1625             mAm.mBatteryStatsService.noteServiceStopRunning(uid, packageName, serviceName);
1626             service.startRequested = false;
1627             if (service.tracker != null) {
1628                 synchronized (mAm.mProcessStats.mLock) {
1629                     service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
1630                             SystemClock.uptimeMillis());
1631                 }
1632             }
1633             service.callStart = false;
1634 
1635             bringDownServiceIfNeededLocked(service, false, false, enqueueOomAdj,
1636                     "stopService");
1637         } finally {
1638             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1639         }
1640 
1641     }
1642 
stopServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int userId, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName)1643     int stopServiceLocked(IApplicationThread caller, Intent service,
1644             String resolvedType, int userId, boolean isSdkSandboxService,
1645             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String instanceName) {
1646         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
1647                 + " type=" + resolvedType);
1648 
1649         final ProcessRecord callerApp = mAm.getRecordForAppLOSP(caller);
1650         if (caller != null && callerApp == null) {
1651             throw new SecurityException(
1652                     "Unable to find app for caller " + caller
1653                     + " (pid=" + mAm.mInjector.getCallingPid()
1654                     + ") when stopping service " + service);
1655         }
1656 
1657         // If this service is active, make sure it is stopped.
1658         ServiceLookupResult r = retrieveServiceLocked(service, instanceName, isSdkSandboxService,
1659                 sdkSandboxClientAppUid, sdkSandboxClientAppPackage, resolvedType, null,
1660                 mAm.mInjector.getCallingPid(), mAm.mInjector.getCallingUid(),
1661                 userId, false, false, false, false, null, false, false);
1662         if (r != null) {
1663             if (r.record != null) {
1664                 final long origId = mAm.mInjector.clearCallingIdentity();
1665                 try {
1666                     stopServiceLocked(r.record, false);
1667                 } finally {
1668                     mAm.mInjector.restoreCallingIdentity(origId);
1669                 }
1670                 return 1;
1671             }
1672             return -1;
1673         }
1674 
1675         return 0;
1676     }
1677 
stopInBackgroundLocked(int uid)1678     void stopInBackgroundLocked(int uid) {
1679         // Stop all services associated with this uid due to it going to the background
1680         // stopped state.
1681         ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
1682         ArrayList<ServiceRecord> stopping = null;
1683         if (services != null) {
1684             for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1685                 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
1686                 if (service.appInfo.uid == uid && service.startRequested) {
1687                     if (mAm.getAppStartModeLOSP(service.appInfo.uid, service.packageName,
1688                             service.appInfo.targetSdkVersion, -1, false, false, false)
1689                             != ActivityManager.APP_START_MODE_NORMAL) {
1690                         if (stopping == null) {
1691                             stopping = new ArrayList<>();
1692                         }
1693                         String compName = service.shortInstanceName;
1694                         EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
1695                         StringBuilder sb = new StringBuilder(64);
1696                         sb.append("Stopping service due to app idle: ");
1697                         UserHandle.formatUid(sb, service.appInfo.uid);
1698                         sb.append(" ");
1699                         TimeUtils.formatDuration(service.createRealTime
1700                                 - SystemClock.elapsedRealtime(), sb);
1701                         sb.append(" ");
1702                         sb.append(compName);
1703                         Slog.w(TAG, sb.toString());
1704                         stopping.add(service);
1705 
1706                         // If the app is under bg restrictions, also make sure that
1707                         // any notification is dismissed
1708                         if (appRestrictedAnyInBackground(
1709                                 service.appInfo.uid, service.packageName)) {
1710                             cancelForegroundNotificationLocked(service);
1711                         }
1712                     }
1713                 }
1714             }
1715             if (stopping != null) {
1716                 final int size = stopping.size();
1717                 for (int i = size - 1; i >= 0; i--) {
1718                     ServiceRecord service = stopping.get(i);
1719                     service.delayed = false;
1720                     services.ensureNotStartingBackgroundLocked(service);
1721                     stopServiceLocked(service, true);
1722                 }
1723                 if (size > 0) {
1724                     mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_UID_IDLE);
1725                 }
1726             }
1727         }
1728     }
1729 
killMisbehavingService(ServiceRecord r, int appUid, int appPid, String localPackageName, int exceptionTypeId)1730     void killMisbehavingService(ServiceRecord r,
1731             int appUid, int appPid, String localPackageName, int exceptionTypeId) {
1732         synchronized (mAm) {
1733             if (!r.destroying) {
1734                 // This service is still alive, stop it.
1735                 stopServiceLocked(r, false);
1736             } else {
1737                 // Check if there is another instance of it being started in parallel,
1738                 // if so, stop that too to avoid spamming the system.
1739                 final ServiceMap smap = getServiceMapLocked(r.userId);
1740                 final ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
1741                 if (found != null) {
1742                     stopServiceLocked(found, false);
1743                 }
1744             }
1745             mAm.crashApplicationWithType(appUid, appPid, localPackageName, -1,
1746                     "Bad notification for startForeground", true /*force*/, exceptionTypeId);
1747         }
1748     }
1749 
peekServiceLocked(Intent service, String resolvedType, String callingPackage)1750     IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
1751         ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
1752                 mAm.mInjector.getCallingPid(), mAm.mInjector.getCallingUid(),
1753                 UserHandle.getCallingUserId(), false, false, false, false, false, false);
1754 
1755         IBinder ret = null;
1756         if (r != null) {
1757             // r.record is null if findServiceLocked() failed the caller permission check
1758             if (r.record == null) {
1759                 throw new SecurityException(
1760                         "Permission Denial: Accessing service"
1761                         + " from pid=" + mAm.mInjector.getCallingPid()
1762                         + ", uid=" + mAm.mInjector.getCallingUid()
1763                         + " requires " + r.permission);
1764             }
1765             IntentBindRecord ib = r.record.bindings.get(r.record.intent);
1766             if (ib != null) {
1767                 ret = ib.binder;
1768             }
1769         }
1770 
1771         return ret;
1772     }
1773 
stopServiceTokenLocked(ComponentName className, IBinder token, int startId)1774     boolean stopServiceTokenLocked(ComponentName className, IBinder token,
1775             int startId) {
1776         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
1777                 + " " + token + " startId=" + startId);
1778         ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
1779         if (r != null) {
1780             if (startId >= 0) {
1781                 // Asked to only stop if done with all work.  Note that
1782                 // to avoid leaks, we will take this as dropping all
1783                 // start items up to and including this one.
1784                 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
1785                 if (si != null) {
1786                     while (r.deliveredStarts.size() > 0) {
1787                         ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
1788                         cur.removeUriPermissionsLocked();
1789                         if (cur == si) {
1790                             break;
1791                         }
1792                     }
1793                 }
1794 
1795                 if (r.getLastStartId() != startId) {
1796                     return false;
1797                 }
1798 
1799                 if (r.deliveredStarts.size() > 0) {
1800                     Slog.w(TAG, "stopServiceToken startId " + startId
1801                             + " is last, but have " + r.deliveredStarts.size()
1802                             + " remaining args");
1803                 }
1804             }
1805 
1806             maybeStopShortFgsTimeoutLocked(r);
1807             maybeStopFgsTimeoutLocked(r);
1808 
1809             final int uid = r.appInfo.uid;
1810             final String packageName = r.name.getPackageName();
1811             final String serviceName = r.name.getClassName();
1812             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, uid, packageName,
1813                     serviceName, FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
1814             mAm.mBatteryStatsService.noteServiceStopRunning(uid, packageName, serviceName);
1815             r.startRequested = false;
1816             if (r.tracker != null) {
1817                 synchronized (mAm.mProcessStats.mLock) {
1818                     r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
1819                             SystemClock.uptimeMillis());
1820                 }
1821             }
1822             r.callStart = false;
1823             final long origId = mAm.mInjector.clearCallingIdentity();
1824             bringDownServiceIfNeededLocked(r, false, false, false, "stopServiceToken");
1825             mAm.mInjector.restoreCallingIdentity(origId);
1826             return true;
1827         }
1828         return false;
1829     }
1830 
1831     /**
1832      * Put the named service into the foreground mode
1833      */
1834     @GuardedBy("mAm")
setServiceForegroundLocked(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)1835     public void setServiceForegroundLocked(ComponentName className, IBinder token,
1836             int id, Notification notification, int flags, int foregroundServiceType) {
1837         final int userId = UserHandle.getCallingUserId();
1838         final int callingUid = mAm.mInjector.getCallingUid();
1839         final long origId = mAm.mInjector.clearCallingIdentity();
1840         try {
1841             ServiceRecord r = findServiceLocked(className, token, userId);
1842             if (r != null) {
1843                 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType,
1844                         callingUid);
1845             }
1846         } finally {
1847             mAm.mInjector.restoreCallingIdentity(origId);
1848         }
1849     }
1850 
1851     /**
1852      * Return the current foregroundServiceType of the ServiceRecord.
1853      * @param className ComponentName of the Service class.
1854      * @param token IBinder token.
1855      * @return current foreground service type.
1856      */
getForegroundServiceTypeLocked(ComponentName className, IBinder token)1857     public int getForegroundServiceTypeLocked(ComponentName className, IBinder token) {
1858         final int userId = UserHandle.getCallingUserId();
1859         final long origId = mAm.mInjector.clearCallingIdentity();
1860         int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
1861         try {
1862             ServiceRecord r = findServiceLocked(className, token, userId);
1863             if (r != null) {
1864                 ret = r.foregroundServiceType;
1865             }
1866         } finally {
1867             mAm.mInjector.restoreCallingIdentity(origId);
1868         }
1869         return ret;
1870     }
1871 
foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed)1872     boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
1873         if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
1874                 + aa.mUid);
1875         boolean canRemove = false;
1876         aa.mHideTime = Long.MAX_VALUE;
1877         if (aa.mShownWhileTop) {
1878             // If the app was ever at the top of the screen while the foreground
1879             // service was running, then we can always just immediately remove it.
1880             canRemove = true;
1881             if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
1882         } else if (mScreenOn || aa.mShownWhileScreenOn) {
1883             final long minTime = aa.mStartVisibleTime
1884                     + (aa.mStartTime != aa.mStartVisibleTime
1885                             ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
1886                             : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
1887             if (nowElapsed >= minTime) {
1888                 // If shown while the screen is on, and it has been shown for
1889                 // at least the minimum show time, then we can now remove it.
1890                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
1891                 canRemove = true;
1892             } else {
1893                 // This is when we will be okay to stop telling the user.
1894                 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
1895                 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
1896                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
1897                         + " with screen on");
1898             }
1899         } else {
1900             final long minTime = aa.mEndTime
1901                     + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
1902             if (nowElapsed >= minTime) {
1903                 // If the foreground service has only run while the screen is
1904                 // off, but it has been gone now for long enough that we won't
1905                 // care to tell the user about it when the screen comes back on,
1906                 // then we can remove it now.
1907                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
1908                 canRemove = true;
1909             } else {
1910                 // This is when we won't care about this old fg service.
1911                 aa.mHideTime = minTime;
1912                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
1913                         + " with screen off");
1914             }
1915         }
1916         return canRemove;
1917     }
1918 
1919     /**
1920      * Stop FGSs owned by non-top, BG-restricted apps.
1921      */
updateForegroundApps(ServiceMap smap)1922     void updateForegroundApps(ServiceMap smap) {
1923         // This is called from the handler without the lock held.
1924         synchronized (mAm) {
1925             final long now = SystemClock.elapsedRealtime();
1926             long nextUpdateTime = Long.MAX_VALUE;
1927             if (smap != null) {
1928                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
1929                         + smap.mUserId);
1930                 smap.mPendingRemoveForegroundApps.clear();
1931                 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
1932                     ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
1933                     if (aa.mEndTime != 0) {
1934                         boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
1935                         if (canRemove) {
1936                             // This was up for longer than the timeout, so just remove immediately.
1937                             smap.mPendingRemoveForegroundApps.add(smap.mActiveForegroundApps.keyAt(i));
1938                             smap.mActiveForegroundAppsChanged = true;
1939                             continue;
1940                         }
1941                         if (aa.mHideTime < nextUpdateTime) {
1942                             nextUpdateTime = aa.mHideTime;
1943                         }
1944                     }
1945                     if (!aa.mAppOnTop) {
1946                         // Transitioning a fg-service host app out of top: if it's bg restricted,
1947                         // it loses the fg service state now.
1948                         if (isForegroundServiceAllowedInBackgroundRestricted(
1949                                 aa.mUid, aa.mPackageName)) {
1950                             if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1951                                     + aa.mPackageName + ", uid=" + aa.mUid);
1952                         } else {
1953                             if (DEBUG_FOREGROUND_SERVICE) {
1954                                 Slog.d(TAG, "bg-restricted app "
1955                                         + aa.mPackageName + "/" + aa.mUid
1956                                         + " exiting top; demoting fg services ");
1957                             }
1958                             stopAllForegroundServicesLocked(aa.mUid, aa.mPackageName);
1959                         }
1960                     }
1961                 }
1962                 for(int i = smap.mPendingRemoveForegroundApps.size() - 1; i >= 0; i--) {
1963                     smap.mActiveForegroundApps.remove(smap.mPendingRemoveForegroundApps.get(i));
1964                 }
1965                 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1966                 if (nextUpdateTime < Long.MAX_VALUE) {
1967                     if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1968                             + (nextUpdateTime-now));
1969                     Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1970                     smap.sendMessageAtTime(msg, nextUpdateTime
1971                             + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
1972                 }
1973             }
1974             smap.mActiveForegroundAppsChanged = false;
1975         }
1976     }
1977 
requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed)1978     private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
1979         Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1980         if (timeElapsed != 0) {
1981             smap.sendMessageAtTime(msg,
1982                     timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
1983         } else {
1984             smap.mActiveForegroundAppsChanged = true;
1985             smap.sendMessage(msg);
1986         }
1987     }
1988 
decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r)1989     private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1990         ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1991         if (active != null) {
1992             active.mNumActive--;
1993             if (active.mNumActive <= 0) {
1994                 active.mEndTime = SystemClock.elapsedRealtime();
1995                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1996                 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
1997                     // Have been active for long enough that we will remove it immediately.
1998                     smap.mActiveForegroundApps.remove(r.packageName);
1999                     smap.mActiveForegroundAppsChanged = true;
2000                     requestUpdateActiveForegroundAppsLocked(smap, 0);
2001                 } else if (active.mHideTime < Long.MAX_VALUE){
2002                     requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
2003                 }
2004             }
2005         }
2006     }
2007 
updateScreenStateLocked(boolean screenOn)2008     void updateScreenStateLocked(boolean screenOn) {
2009         if (mScreenOn != screenOn) {
2010             mScreenOn = screenOn;
2011 
2012             // If screen is turning on, then we now reset the start time of any foreground
2013             // services that were started while the screen was off.
2014             if (screenOn) {
2015                 final long nowElapsed = SystemClock.elapsedRealtime();
2016                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
2017                 for (int i = mServiceMap.size()-1; i >= 0; i--) {
2018                     ServiceMap smap = mServiceMap.valueAt(i);
2019                     long nextUpdateTime = Long.MAX_VALUE;
2020                     boolean changed = false;
2021                     for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
2022                         ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
2023                         if (active.mEndTime == 0) {
2024                             if (!active.mShownWhileScreenOn) {
2025                                 active.mShownWhileScreenOn = true;
2026                                 active.mStartVisibleTime = nowElapsed;
2027                             }
2028                         } else {
2029                             if (!active.mShownWhileScreenOn
2030                                     && active.mStartVisibleTime == active.mStartTime) {
2031                                 // If this was never shown while the screen was on, then we will
2032                                 // count the time it started being visible as now, to tell the user
2033                                 // about it now that they have a screen to look at.
2034                                 active.mEndTime = active.mStartVisibleTime = nowElapsed;
2035                             }
2036                             if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
2037                                 // Have been active for long enough that we will remove it
2038                                 // immediately.
2039                                 smap.mActiveForegroundApps.remove(active.mPackageName);
2040                                 smap.mActiveForegroundAppsChanged = true;
2041                                 changed = true;
2042                             } else {
2043                                 if (active.mHideTime < nextUpdateTime) {
2044                                     nextUpdateTime = active.mHideTime;
2045                                 }
2046                             }
2047                         }
2048                     }
2049                     if (changed) {
2050                         // Need to immediately update.
2051                         requestUpdateActiveForegroundAppsLocked(smap, 0);
2052                     } else if (nextUpdateTime < Long.MAX_VALUE) {
2053                         requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
2054                     }
2055                 }
2056             }
2057         }
2058     }
2059 
foregroundServiceProcStateChangedLocked(UidRecord uidRec)2060     void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
2061         ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.getUid()));
2062         if (smap != null) {
2063             boolean changed = false;
2064             for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
2065                 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
2066                 if (active.mUid == uidRec.getUid()) {
2067                     if (uidRec.getCurProcState() <= PROCESS_STATE_TOP) {
2068                         if (!active.mAppOnTop) {
2069                             active.mAppOnTop = true;
2070                             changed = true;
2071                         }
2072                         active.mShownWhileTop = true;
2073                     } else if (active.mAppOnTop) {
2074                         active.mAppOnTop = false;
2075                         changed = true;
2076                     }
2077                 }
2078             }
2079             if (changed) {
2080                 requestUpdateActiveForegroundAppsLocked(smap, 0);
2081             }
2082         }
2083     }
2084 
2085     /**
2086      * Check if the given app is allowed to have FGS running even if it's background restricted.
2087      *
2088      * <p>
2089      * Currently it needs to be in Top/Bound Top/FGS state. An uid could be in the FGS state if:
2090      * a) Bound by another process in the FGS state;
2091      * b) There is an active FGS running (ServiceRecord.isForeground is true);
2092      * c) The startForegroundService() has been called but the startForeground() hasn't - in this
2093      *    case, it must have passed the background FGS start check so we're safe here.
2094      * </p>
2095      */
isForegroundServiceAllowedInBackgroundRestricted(ProcessRecord app)2096     private boolean isForegroundServiceAllowedInBackgroundRestricted(ProcessRecord app) {
2097         final ProcessStateRecord state = app.mState;
2098         if (isDeviceProvisioningPackage(app.info.packageName)) {
2099             return true;
2100         }
2101         if (!state.isBackgroundRestricted()
2102                 || state.getSetProcState() <= ActivityManager.PROCESS_STATE_BOUND_TOP) {
2103             return true;
2104         }
2105         if (state.getSetProcState() == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2106                 && state.isSetBoundByNonBgRestrictedApp()) {
2107             return true;
2108         }
2109         return false;
2110     }
2111 
2112     /**
2113      * Check if the given uid/pkg is allowed to have FGS running even if it's background restricted.
2114      */
isForegroundServiceAllowedInBackgroundRestricted(int uid, String packageName)2115     private boolean isForegroundServiceAllowedInBackgroundRestricted(int uid, String packageName) {
2116         final UidRecord uidRec = mAm.mProcessList.getUidRecordLOSP(uid);
2117         ProcessRecord app = null;
2118         return uidRec != null && ((app = uidRec.getProcessInPackage(packageName)) != null)
2119                 && isForegroundServiceAllowedInBackgroundRestricted(app);
2120     }
2121 
2122     /*
2123      * If the FGS start is temp allowlisted by alarm-clock(REASON_ALARM_MANAGER_ALARM_CLOCK), it is
2124      * allowed even the app is background-restricted.
2125      */
isTempAllowedByAlarmClock(int uid)2126     private boolean isTempAllowedByAlarmClock(int uid) {
2127         final ActivityManagerService.FgsTempAllowListItem item =
2128                 mAm.isAllowlistedForFgsStartLOSP(uid);
2129         if (item != null) {
2130             return item.mReasonCode == REASON_ALARM_MANAGER_ALARM_CLOCK;
2131         } else {
2132             return false;
2133         }
2134     }
2135 
logFgsApiBeginLocked(int uid, int pid, int apiType)2136     void logFgsApiBeginLocked(int uid, int pid, int apiType) {
2137         synchronized (mFGSLogger) {
2138             mFGSLogger.logForegroundServiceApiEventBegin(uid, pid, apiType, "");
2139         }
2140     }
2141 
logFgsApiEndLocked(int uid, int pid, int apiType)2142     void logFgsApiEndLocked(int uid, int pid, int apiType) {
2143         synchronized (mFGSLogger) {
2144             mFGSLogger.logForegroundServiceApiEventEnd(uid, pid, apiType);
2145         }
2146     }
2147 
logFgsApiStateChangedLocked(int uid, int pid, int apiType, int state)2148     void logFgsApiStateChangedLocked(int uid, int pid, int apiType, int state) {
2149         synchronized (mFGSLogger) {
2150             mFGSLogger.logForegroundServiceApiStateChanged(uid, pid, apiType, state);
2151         }
2152     }
2153 
2154     /**
2155      * @param id Notification ID.  Zero === exit foreground state for the given service.
2156      */
2157     @GuardedBy("mAm")
setServiceForegroundInnerLocked(final ServiceRecord r, int id, Notification notification, int flags, int foregroundServiceType, int callingUidIfStart)2158     private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
2159             Notification notification, int flags, int foregroundServiceType,
2160             int callingUidIfStart) {
2161         if (id != 0) {
2162             if (notification == null) {
2163                 throw new IllegalArgumentException("null notification");
2164             }
2165             traceInstant("startForeground(): ", r);
2166             final int foregroundServiceStartType = foregroundServiceType;
2167             // Instant apps need permission to create foreground services.
2168             if (r.appInfo.isInstantApp()) {
2169                 final int mode = mAm.getAppOpsManager().checkOpNoThrow(
2170                         AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
2171                         r.appInfo.uid,
2172                         r.appInfo.packageName);
2173                 switch (mode) {
2174                     case AppOpsManager.MODE_ALLOWED:
2175                         break;
2176                     case AppOpsManager.MODE_IGNORED:
2177                         Slog.w(TAG, "Instant app " + r.appInfo.packageName
2178                                 + " does not have permission to create foreground services"
2179                                 + ", ignoring.");
2180                         return;
2181                     case AppOpsManager.MODE_ERRORED:
2182                         throw new SecurityException("Instant app " + r.appInfo.packageName
2183                                 + " does not have permission to create foreground services");
2184                     default:
2185                         mAm.enforcePermission(
2186                                 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
2187                                 r.app.getPid(), r.appInfo.uid, "startForeground");
2188                 }
2189             } else {
2190                 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
2191                     mAm.enforcePermission(
2192                             android.Manifest.permission.FOREGROUND_SERVICE,
2193                             r.app.getPid(), r.appInfo.uid, "startForeground");
2194                 }
2195             }
2196             final int manifestType = r.serviceInfo.getForegroundServiceType();
2197             // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
2198             // consider it is the same as manifest foreground service type.
2199             if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
2200                 foregroundServiceType = manifestType;
2201             }
2202 
2203             // Check the passed in foreground service type flags is a subset of manifest
2204             // foreground service type flags.
2205             final String prop = "debug.skip_fgs_manifest_type_check";
2206             if (((foregroundServiceType & manifestType) != foregroundServiceType)
2207                     // When building a test app on Studio, the SDK may not have all the
2208                     // FGS types yet. This debug flag will allow using FGS types that are
2209                     // not set in the manifest.
2210                     && !SystemProperties.getBoolean(prop, false)) {
2211                 final String message = "foregroundServiceType "
2212                         + String.format("0x%08X", foregroundServiceType)
2213                         + " is not a subset of foregroundServiceType attribute "
2214                         + String.format("0x%08X", manifestType)
2215                         + " in service element of manifest file";
2216                 if (!r.appInfo.isInstantApp()
2217                         || CompatChanges.isChangeEnabled(FGS_TYPE_CHECK_FOR_INSTANT_APPS,
2218                         r.appInfo.uid)) {
2219                     throw new IllegalArgumentException(message);
2220                 } else {
2221                     Slog.w(TAG, message + "\n"
2222                             + "This will be an exception once the target SDK level is UDC");
2223                 }
2224             }
2225             if ((foregroundServiceType & FOREGROUND_SERVICE_TYPE_SHORT_SERVICE) != 0
2226                     && foregroundServiceType != FOREGROUND_SERVICE_TYPE_SHORT_SERVICE) {
2227                 Slog.w(TAG_SERVICE, "startForeground(): FOREGROUND_SERVICE_TYPE_SHORT_SERVICE"
2228                         + " is combined with other types. SHORT_SERVICE will be ignored.");
2229                 // In this case, the service will be handled as a non-short, regular FGS
2230                 // anyway, so we just remove the SHORT_SERVICE type.
2231                 foregroundServiceType &= ~FOREGROUND_SERVICE_TYPE_SHORT_SERVICE;
2232             }
2233 
2234             boolean alreadyStartedOp = false;
2235             boolean stopProcStatsOp = false;
2236             final boolean origFgRequired = r.fgRequired;
2237             if (r.fgRequired) {
2238                 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
2239                     Slog.i(TAG, "Service called startForeground() as required: " + r);
2240                 }
2241                 r.fgRequired = false;
2242                 r.fgWaiting = false;
2243                 alreadyStartedOp = stopProcStatsOp = true;
2244                 mServiceFGAnrTimer.cancel(r);
2245             }
2246 
2247             if (!shouldAllowBootCompletedStart(r, foregroundServiceType)) {
2248                 throw new ForegroundServiceStartNotAllowedException("FGS type "
2249                         + ServiceInfo.foregroundServiceTypeToLabel(foregroundServiceType)
2250                         + " not allowed to start from BOOT_COMPLETED!");
2251             }
2252 
2253             final ProcessServiceRecord psr = r.app.mServices;
2254             try {
2255                 boolean ignoreForeground = false;
2256                 final int mode = mAm.getAppOpsManager().checkOpNoThrow(
2257                         AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
2258                 switch (mode) {
2259                     case AppOpsManager.MODE_ALLOWED:
2260                     case AppOpsManager.MODE_DEFAULT:
2261                         // All okay.
2262                         break;
2263                     case AppOpsManager.MODE_IGNORED:
2264                         // Whoops, silently ignore this.
2265                         Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
2266                                 + r.shortInstanceName);
2267                         ignoreForeground = true;
2268                         break;
2269                     default:
2270                         throw new SecurityException("Foreground not allowed as per app op");
2271                 }
2272 
2273                 // Apps that are TOP or effectively similar may call startForeground() on
2274                 // their services even if they are restricted from doing that while in bg.
2275                 if (!ignoreForeground
2276                         && !isForegroundServiceAllowedInBackgroundRestricted(r.app)
2277                         && !isTempAllowedByAlarmClock(r.app.uid)) {
2278                     Slog.w(TAG,
2279                             "Service.startForeground() not allowed due to bg restriction: service "
2280                                     + r.shortInstanceName);
2281                     // Back off of any foreground expectations around this service, since we've
2282                     // just turned down its fg request.
2283                     updateServiceForegroundLocked(psr, false);
2284                     ignoreForeground = true;
2285                 }
2286 
2287                 // Whether FGS-BG-start restriction is enabled for this service.
2288                 final boolean isBgFgsRestrictionEnabledForService = isBgFgsRestrictionEnabled(r,
2289                         callingUidIfStart);
2290 
2291                 // Whether to extend the SHORT_SERVICE time out.
2292                 boolean extendShortServiceTimeout = false;
2293 
2294                 // Whether setFgsRestrictionLocked() is called in here. Only used for logging.
2295                 boolean fgsRestrictionRecalculated = false;
2296 
2297                 final int previousFgsType = r.foregroundServiceType;
2298 
2299                 int fgsTypeCheckCode = FGS_TYPE_POLICY_CHECK_UNKNOWN;
2300                 if (!ignoreForeground) {
2301                     if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
2302                             && !r.startRequested) {
2303                         // There's a long standing bug that allows a bound service to become
2304                         // a foreground service *even when it's not started*.
2305                         // Unfortunately, there are apps relying on this behavior, so we can't just
2306                         // suddenly disallow it.
2307                         // However, this would be very problematic if used with a short-FGS, so we
2308                         // explicitly disallow this combination.
2309                         throw new StartForegroundCalledOnStoppedServiceException(
2310                                 "startForeground(SHORT_SERVICE) called on a service that's not"
2311                                 + " started.");
2312                     }
2313 
2314                     // Side note: If a valid short-service (which has to be "started"), happens to
2315                     // also be bound, then we still _will_ apply a timeout, because it still has
2316                     // to be stopped.
2317 
2318                     // Calling startForeground on a SHORT_SERVICE will require some additional
2319                     // checks.
2320                     // A) SHORT_SERVICE -> another type.
2321                     //    - This should be allowed only when the app could start another FGS.
2322                     //    - When succeed, the timeout should stop.
2323                     // B) SHORT_SERVICE -> SHORT_SERVICE
2324                     //    - If the app could start an FGS, then this would extend the timeout.
2325                     //    - Otherwise, it's basically a no-op.
2326                     //    - If it's already timed out, we also throw.
2327                     // Also,
2328                     // C) another type -> SHORT_SERVICE
2329                     //    - This will always be allowed.
2330                     //    - Timeout will start.
2331 
2332                     final boolean isOldTypeShortFgs = r.isShortFgs();
2333                     final boolean isNewTypeShortFgs =
2334                             foregroundServiceType == FOREGROUND_SERVICE_TYPE_SHORT_SERVICE;
2335                     final long nowUptime = SystemClock.uptimeMillis();
2336                     final boolean isOldTypeShortFgsAndTimedOut =
2337                             r.shouldTriggerShortFgsTimeout(nowUptime);
2338 
2339                     // If true, we skip the BFSL check.
2340                     boolean bypassBfslCheck = false;
2341 
2342                     if (r.isForeground && (isOldTypeShortFgs || isNewTypeShortFgs)) {
2343                         if (DEBUG_SHORT_SERVICE) {
2344                             Slog.i(TAG_SERVICE, String.format(
2345                                     "FGS type changing from %x%s to %x: %s",
2346                                     r.foregroundServiceType,
2347                                     (isOldTypeShortFgsAndTimedOut ? "(timed out short FGS)" : ""),
2348                                     foregroundServiceStartType,
2349                                     r.toString()));
2350                         }
2351                     }
2352 
2353                     if (r.isForeground && isOldTypeShortFgs) {
2354 
2355                         // If we get here, that means startForeground(SHORT_SERVICE) is called again
2356                         // on a SHORT_SERVICE FGS.
2357 
2358                         // See if the app could start an FGS or not.
2359                         r.clearFgsAllowStart();
2360                         setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
2361                                 r.appInfo.uid, r.intent.getIntent(), r, r.userId,
2362                                 BackgroundStartPrivileges.NONE,
2363                                 false /* isBindService */);
2364                         fgsRestrictionRecalculated = true;
2365                         if (!r.isFgsAllowedStart()) {
2366                             Slog.w(TAG_SERVICE, "FGS type change to/from SHORT_SERVICE: "
2367                                     + " BFSL DENIED.");
2368                         } else {
2369                             if (DEBUG_SHORT_SERVICE) {
2370                                 Slog.w(TAG_SERVICE, "FGS type change to/from SHORT_SERVICE: "
2371                                         + " BFSL Allowed: "
2372                                         + PowerExemptionManager.reasonCodeToString(
2373                                                 r.getFgsAllowStart()));
2374                             }
2375                         }
2376 
2377                         final boolean fgsStartAllowed =
2378                                 !isBgFgsRestrictionEnabledForService
2379                                         || r.isFgsAllowedStart();
2380 
2381                         if (fgsStartAllowed) {
2382                             if (isNewTypeShortFgs) {
2383                                 // Only in this case, we extend the SHORT_SERVICE time out.
2384                                 extendShortServiceTimeout = true;
2385                             } else {
2386                                 // FGS type is changing from SHORT_SERVICE to another type when
2387                                 // an app is allowed to start FGS, so this will succeed.
2388                                 // The timeout will stop later, in
2389                                 // maybeUpdateShortFgsTrackingLocked().
2390                             }
2391                         } else {
2392                             if (isNewTypeShortFgs) {
2393                                 // startForeground(SHORT_SERVICE) is called on an already running
2394                                 // SHORT_SERVICE FGS, when BFSL is not allowed.
2395                                 // In this case, the call should succeed
2396                                 // (== ForegroundServiceStartNotAllowedException shouldn't be
2397                                 // thrown), but the short service timeout shouldn't extend
2398                                 // (== extendShortServiceTimeout should be false).
2399                                 // We still do everything else -- e.g. we still need to update
2400                                 // the notification.
2401                                 bypassBfslCheck = true;
2402                             } else {
2403                                 // We catch this case later, in the
2404                                 // "if (r.mAllowStartForeground == REASON_DENIED...)" block below.
2405                             }
2406                         }
2407                     } else if (CompatChanges.isChangeEnabled(
2408                                     FGS_INTRODUCE_TIME_LIMITS, r.appInfo.uid)
2409                                 && android.app.Flags.introduceNewServiceOntimeoutCallback()
2410                                 && getTimeLimitedFgsType(foregroundServiceType)
2411                                         != ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE) {
2412                         // Calling startForeground on a FGS type which has a time limit will only be
2413                         // allowed if the app is in a state where it can normally start another FGS
2414                         // and it hasn't hit its time limit in the past 24hrs, or it has been in the
2415                         // foreground after it hit its time limit, or it is currently in the
2416                         // TOP (or better) proc state.
2417 
2418                         // See if the app could start an FGS or not.
2419                         r.clearFgsAllowStart();
2420                         setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
2421                                 r.appInfo.uid, r.intent.getIntent(), r, r.userId,
2422                                 BackgroundStartPrivileges.NONE, false /* isBindService */);
2423                         fgsRestrictionRecalculated = true;
2424 
2425                         final boolean fgsStartAllowed = !isBgFgsRestrictionEnabledForService
2426                                                             || r.isFgsAllowedStart();
2427                         if (fgsStartAllowed) {
2428                             SparseArray<TimeLimitedFgsInfo> fgsInfo =
2429                                     mTimeLimitedFgsInfo.get(r.appInfo.uid);
2430                             if (fgsInfo == null) {
2431                                 fgsInfo = new SparseArray<>();
2432                                 mTimeLimitedFgsInfo.put(r.appInfo.uid, fgsInfo);
2433                             }
2434                             final int timeLimitedFgsType =
2435                                     getTimeLimitedFgsType(foregroundServiceType);
2436                             final TimeLimitedFgsInfo fgsTypeInfo = fgsInfo.get(timeLimitedFgsType);
2437                             if (fgsTypeInfo != null) {
2438                                 final long before24Hr = Math.max(0,
2439                                             SystemClock.elapsedRealtime() - (24 * 60 * 60 * 1000));
2440                                 final long lastTimeOutAt = fgsTypeInfo.getTimeLimitExceededAt();
2441                                 if (fgsTypeInfo.getFirstFgsStartRealtime() < before24Hr
2442                                         || r.app.mState.getCurProcState() <= PROCESS_STATE_TOP
2443                                         || (lastTimeOutAt != Long.MIN_VALUE
2444                                             && r.app.mState.getLastTopTime() > lastTimeOutAt)) {
2445                                     // Reset the time limit info for this fgs type if it has been
2446                                     // more than 24hrs since the first fgs start or if the app is
2447                                     // currently in the TOP state or was in the TOP state after
2448                                     // the time limit was exhausted previously.
2449                                     fgsTypeInfo.reset();
2450                                 } else if (lastTimeOutAt > 0) {
2451                                     // Time limit was exhausted within the past 24 hours and the app
2452                                     // has not been in the TOP state since then, throw an exception.
2453                                     final String exceptionMsg = "Time limit already exhausted for"
2454                                             + " foreground service type "
2455                                             + ServiceInfo.foregroundServiceTypeToLabel(
2456                                                     foregroundServiceType);
2457                                     // Only throw an exception if the new crashing logic gate
2458                                     // is enabled; otherwise, reset the limit temporarily.
2459                                     if (android.app.Flags.enableFgsTimeoutCrashBehavior()) {
2460                                         throw new ForegroundServiceStartNotAllowedException(
2461                                                     exceptionMsg);
2462                                     } else {
2463                                         Slog.wtf(TAG, exceptionMsg);
2464                                         fgsTypeInfo.reset();
2465                                     }
2466                                 }
2467                             }
2468                         } else {
2469                             // This case will be handled in the BFSL check below.
2470                         }
2471                     } else if (r.mStartForegroundCount == 0) {
2472                         /*
2473                         If the service was started with startService(), not
2474                         startForegroundService(), and if startForeground() isn't called within
2475                         mFgsStartForegroundTimeoutMs, then we check the state of the app
2476                         (who owns the service, which is the app that called startForeground())
2477                         again. If the app is in the foreground, or in any other cases where
2478                         FGS-starts are allowed, then we still allow the FGS to be started.
2479                         Otherwise, startForeground() would fail.
2480 
2481                         If the service was started with startForegroundService(), then the service
2482                         must call startForeground() within a timeout anyway, so we don't need this
2483                         check.
2484                         */
2485                         if (!r.fgRequired) {
2486                             final long delayMs = SystemClock.elapsedRealtime() - r.createRealTime;
2487                             if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) {
2488                                 resetFgsRestrictionLocked(r);
2489                                 setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
2490                                         r.appInfo.uid, r.intent.getIntent(), r, r.userId,
2491                                         BackgroundStartPrivileges.NONE,
2492                                         false /* isBindService */);
2493                                 fgsRestrictionRecalculated = true;
2494                                 final String temp = "startForegroundDelayMs:" + delayMs;
2495                                 if (r.mInfoAllowStartForeground != null) {
2496                                     r.mInfoAllowStartForeground += "; " + temp;
2497                                 } else {
2498                                     r.mInfoAllowStartForeground = temp;
2499                                 }
2500                                 r.mLoggedInfoAllowStartForeground = false;
2501                             }
2502                         }
2503                     } else if (r.mStartForegroundCount >= 1) {
2504                         // We get here if startForeground() is called multiple times
2505                         // on the same service after it's created, regardless of whether
2506                         // stopForeground() has been called or not.
2507 
2508                         // The second or later time startForeground() is called after service is
2509                         // started. Check for app state again.
2510                         setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
2511                                 r.appInfo.uid, r.intent.getIntent(), r, r.userId,
2512                                 BackgroundStartPrivileges.NONE,
2513                                 false /* isBindService */);
2514                         fgsRestrictionRecalculated = true;
2515                     }
2516 
2517                     // When startForeground() is called on a bound service, without having
2518                     // it started (i.e. no Context.startService() or startForegroundService() was
2519                     // called.)
2520                     // called on it, then we probably didn't call setFgsRestrictionLocked()
2521                     // in startService(). If fgsRestrictionRecalculated is false, then we
2522                     // didn't call setFgsRestrictionLocked() here either.
2523                     //
2524                     // In this situation, we call setFgsRestrictionLocked() with
2525                     // forBoundFgs = false, so we'd set the FGS allowed reason to the
2526                     // by-bindings fields, so we can put it in the log, without affecting the
2527                     // logic.
2528                     if (!fgsRestrictionRecalculated && !r.startRequested) {
2529                         setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
2530                                 r.appInfo.uid, r.intent.getIntent(), r, r.userId,
2531                                 BackgroundStartPrivileges.NONE,
2532                                 false /* isBindService */, true /* forBoundFgs */);
2533                     }
2534 
2535                     // If the foreground service is not started from TOP process, do not allow it to
2536                     // have while-in-use location/camera/microphone access.
2537                     if (!r.isFgsAllowedWiu_forCapabilities()) {
2538                         Slog.w(TAG,
2539                                 "Foreground service started from background can not have "
2540                                         + "location/camera/microphone access: service "
2541                                         + r.shortInstanceName);
2542                     }
2543                     r.maybeLogFgsLogicChange();
2544                     if (!bypassBfslCheck) {
2545                         logFgsBackgroundStart(r);
2546                         if (!r.isFgsAllowedStart()
2547                                 && isBgFgsRestrictionEnabledForService) {
2548                             final String msg = "Service.startForeground() not allowed due to "
2549                                     + "mAllowStartForeground false: service "
2550                                     + r.shortInstanceName
2551                                     + (isOldTypeShortFgs ? " (Called on SHORT_SERVICE)" : "");
2552                             Slog.w(TAG, msg);
2553                             showFgsBgRestrictedNotificationLocked(r);
2554                             updateServiceForegroundLocked(psr, true);
2555                             ignoreForeground = true;
2556                             logFGSStateChangeLocked(r,
2557                                     FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED,
2558                                     0, FGS_STOP_REASON_UNKNOWN, FGS_TYPE_POLICY_CHECK_UNKNOWN,
2559                                     FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
2560                                     false /* fgsRestrictionRecalculated */
2561                             );
2562                             if (CompatChanges.isChangeEnabled(FGS_START_EXCEPTION_CHANGE_ID,
2563                                     r.appInfo.uid)) {
2564                                 throw new ForegroundServiceStartNotAllowedException(msg);
2565                             }
2566                         }
2567                     }
2568 
2569                     if (!ignoreForeground) {
2570                         Pair<Integer, RuntimeException> fgsTypeResult = null;
2571                         if (foregroundServiceType == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE) {
2572                             fgsTypeResult = validateForegroundServiceType(r,
2573                                     foregroundServiceType,
2574                                     ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE,
2575                                     foregroundServiceStartType);
2576                         } else {
2577                             int fgsTypes = foregroundServiceType;
2578                             // If the service has declared some unknown types which might be coming
2579                             // from future releases, and if it also comes with the "specialUse",
2580                             // then it'll be deemed as the "specialUse" and we ignore this
2581                             // unknown type. Otherwise, it'll be treated as an invalid type.
2582                             int defaultFgsTypes = (foregroundServiceType
2583                                     & ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) != 0
2584                                     ? ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
2585                                     : ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
2586                             for (int serviceType = Integer.highestOneBit(fgsTypes);
2587                                     serviceType != 0;
2588                                     serviceType = Integer.highestOneBit(fgsTypes)) {
2589                                 fgsTypeResult = validateForegroundServiceType(r,
2590                                         serviceType, defaultFgsTypes, foregroundServiceStartType);
2591                                 fgsTypes &= ~serviceType;
2592                                 if (fgsTypeResult.first != FGS_TYPE_POLICY_CHECK_OK) {
2593                                     break;
2594                                 }
2595                             }
2596                         }
2597                         fgsTypeCheckCode = fgsTypeResult.first;
2598                         if (fgsTypeResult.second != null) {
2599                             logFGSStateChangeLocked(r,
2600                                     FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED,
2601                                     0, FGS_STOP_REASON_UNKNOWN, fgsTypeResult.first,
2602                                     FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
2603                                     false /* fgsRestrictionRecalculated */
2604                             );
2605                             throw fgsTypeResult.second;
2606                         }
2607                     }
2608                 }
2609 
2610                 // Apps under strict background restrictions simply don't get to have foreground
2611                 // services, so now that we've enforced the startForegroundService() contract
2612                 // we only do the machinery of making the service foreground when the app
2613                 // is not restricted.
2614                 if (!ignoreForeground) {
2615                     if (r.foregroundId != id) {
2616                         cancelForegroundNotificationLocked(r);
2617                         r.foregroundId = id;
2618                     }
2619                     notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
2620                     r.foregroundNoti = notification;
2621                     r.foregroundServiceType = foregroundServiceType;
2622                     if (!r.isForeground) {
2623                         final ServiceMap smap = getServiceMapLocked(r.userId);
2624                         if (smap != null) {
2625                             ActiveForegroundApp active = smap.mActiveForegroundApps
2626                                     .get(r.packageName);
2627                             if (active == null) {
2628                                 active = new ActiveForegroundApp();
2629                                 active.mPackageName = r.packageName;
2630                                 active.mUid = r.appInfo.uid;
2631                                 active.mShownWhileScreenOn = mScreenOn;
2632                                 if (r.app != null) {
2633                                     final UidRecord uidRec = r.app.getUidRecord();
2634                                     if (uidRec != null) {
2635                                         active.mAppOnTop = active.mShownWhileTop =
2636                                                 uidRec.getCurProcState() <= PROCESS_STATE_TOP;
2637                                     }
2638                                 }
2639                                 active.mStartTime = active.mStartVisibleTime
2640                                         = SystemClock.elapsedRealtime();
2641                                 smap.mActiveForegroundApps.put(r.packageName, active);
2642                                 requestUpdateActiveForegroundAppsLocked(smap, 0);
2643                             }
2644                             active.mNumActive++;
2645                         }
2646                         r.isForeground = true;
2647 
2648                         // The logging of FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER event could
2649                         // be deferred, make a copy of mAllowStartForeground and
2650                         // mAllowWhileInUsePermissionInFgs.
2651                         r.mAllowStartForegroundAtEntering = r.getFgsAllowStart();
2652                         r.mAllowWhileInUsePermissionInFgsAtEntering =
2653                                 r.isFgsAllowedWiu_forCapabilities();
2654                         r.mStartForegroundCount++;
2655                         r.mFgsEnterTime = SystemClock.uptimeMillis();
2656                         if (!stopProcStatsOp) {
2657                             synchronized (mAm.mProcessStats.mLock) {
2658                                 final ServiceState stracker = r.getTracker();
2659                                 if (stracker != null) {
2660                                     stracker.setForeground(true,
2661                                             mAm.mProcessStats.getMemFactorLocked(),
2662                                             SystemClock.uptimeMillis());
2663                                 }
2664                             }
2665                         } else {
2666                             stopProcStatsOp = false;
2667                         }
2668 
2669                         mAm.mAppOpsService.startOperation(
2670                                 AppOpsManager.getToken(mAm.mAppOpsService),
2671                                 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
2672                                 null, true, false, "", false, AppOpsManager.ATTRIBUTION_FLAGS_NONE,
2673                                 AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE);
2674                         registerAppOpCallbackLocked(r);
2675                         mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
2676 
2677                         int fgsStartApi = FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NONE;
2678                         if (r.startRequested) {
2679                             if (origFgRequired) {
2680                                 fgsStartApi =
2681                                         FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_START_FOREGROUND_SERVICE;
2682                             } else {
2683                                 fgsStartApi =
2684                                         FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_START_SERVICE;
2685                             }
2686                         }
2687 
2688                         logFGSStateChangeLocked(r,
2689                                 FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER,
2690                                 0, FGS_STOP_REASON_UNKNOWN, fgsTypeCheckCode,
2691                                 fgsStartApi,
2692                                 fgsRestrictionRecalculated
2693                         );
2694                         synchronized (mFGSLogger) {
2695                             mFGSLogger.logForegroundServiceStart(r.appInfo.uid, 0, r);
2696                         }
2697                         updateNumForegroundServicesLocked();
2698                     }
2699 
2700                     maybeUpdateShortFgsTrackingLocked(r,
2701                             extendShortServiceTimeout);
2702                     // Even if the service is already a FGS, we need to update the notification,
2703                     // so we need to call it again.
2704                     signalForegroundServiceObserversLocked(r);
2705                     r.postNotification(true);
2706                     if (r.app != null) {
2707                         updateServiceForegroundLocked(psr, true);
2708                     }
2709                     getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
2710                     mAm.notifyPackageUse(r.serviceInfo.packageName,
2711                             PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
2712 
2713                     if (CompatChanges.isChangeEnabled(FGS_INTRODUCE_TIME_LIMITS, r.appInfo.uid)
2714                             && android.app.Flags.introduceNewServiceOntimeoutCallback()) {
2715                         maybeUpdateFgsTrackingLocked(r, previousFgsType);
2716                     }
2717                 } else {
2718                     if (DEBUG_FOREGROUND_SERVICE) {
2719                         Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
2720                     }
2721                 }
2722             } finally {
2723                 if (stopProcStatsOp) {
2724                     // We got through to this point with it actively being started foreground,
2725                     // and never decided we wanted to keep it like that, so drop it.
2726                     synchronized (mAm.mProcessStats.mLock) {
2727                         final ServiceState stracker = r.getTracker();
2728                         if (stracker != null) {
2729                             stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2730                                     SystemClock.uptimeMillis());
2731                         }
2732                     }
2733                 }
2734                 if (alreadyStartedOp) {
2735                     // If we had previously done a start op for direct foreground start,
2736                     // we have cleared the flag so can now drop it.
2737                     mAm.mAppOpsService.finishOperation(
2738                             AppOpsManager.getToken(mAm.mAppOpsService),
2739                             AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
2740                             null);
2741                 }
2742             }
2743         } else {
2744             if (r.isForeground) {
2745                 traceInstant("stopForeground(): ", r);
2746                 final ServiceMap smap = getServiceMapLocked(r.userId);
2747                 if (smap != null) {
2748                     decActiveForegroundAppLocked(smap, r);
2749                 }
2750 
2751                 maybeStopShortFgsTimeoutLocked(r);
2752                 maybeStopFgsTimeoutLocked(r);
2753 
2754                 // Adjust notification handling before setting isForeground to false, because
2755                 // that state is relevant to the notification policy side.
2756                 // Leave the time-to-display as already set: re-entering foreground mode will
2757                 // only resume the previous quiet timeout, or will display immediately if the
2758                 // deferral period had already passed.
2759                 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
2760                     cancelForegroundNotificationLocked(r);
2761                     r.foregroundId = 0;
2762                     r.foregroundNoti = null;
2763                 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
2764                     // if it's been deferred, force to visibility
2765                     if (!r.mFgsNotificationShown) {
2766                         r.postNotification(false);
2767                     }
2768                     dropFgsNotificationStateLocked(r);
2769                     if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
2770                         r.foregroundId = 0;
2771                         r.foregroundNoti = null;
2772                     }
2773                 }
2774 
2775                 r.isForeground = false;
2776                 r.mFgsExitTime = SystemClock.uptimeMillis();
2777                 synchronized (mAm.mProcessStats.mLock) {
2778                     final ServiceState stracker = r.getTracker();
2779                     if (stracker != null) {
2780                         stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
2781                                 SystemClock.uptimeMillis());
2782                     }
2783                 }
2784                 mAm.mAppOpsService.finishOperation(
2785                         AppOpsManager.getToken(mAm.mAppOpsService),
2786                         AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
2787                 unregisterAppOpCallbackLocked(r);
2788                 logFGSStateChangeLocked(r,
2789                         FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT,
2790                         r.mFgsExitTime > r.mFgsEnterTime
2791                                 ? (int) (r.mFgsExitTime - r.mFgsEnterTime) : 0,
2792                         FGS_STOP_REASON_STOP_FOREGROUND,
2793                         FGS_TYPE_POLICY_CHECK_UNKNOWN,
2794                         FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
2795                         false /* fgsRestrictionRecalculated */
2796                 );
2797 
2798                 synchronized (mFGSLogger) {
2799                     mFGSLogger.logForegroundServiceStop(r.appInfo.uid, r);
2800                 }
2801                 // foregroundServiceType is used in logFGSStateChangeLocked(), so we can't clear it
2802                 // earlier.
2803                 r.foregroundServiceType = 0;
2804                 r.mFgsNotificationWasDeferred = false;
2805                 signalForegroundServiceObserversLocked(r);
2806                 resetFgsRestrictionLocked(r);
2807                 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
2808                 if (r.app != null) {
2809                     mAm.updateLruProcessLocked(r.app, false, null);
2810                     updateServiceForegroundLocked(r.app.mServices, true);
2811                 }
2812                 updateNumForegroundServicesLocked();
2813             }
2814         }
2815     }
2816 
withinFgsDeferRateLimit(ServiceRecord sr, final long now)2817     private boolean withinFgsDeferRateLimit(ServiceRecord sr, final long now) {
2818         // If we're still within the service's deferral period, then by definition
2819         // deferral is not rate limited.
2820         if (now < sr.fgDisplayTime) {
2821             if (DEBUG_FOREGROUND_SERVICE) {
2822                 Slog.d(TAG_SERVICE, "FGS transition for " + sr
2823                         + " within deferral period, no rate limit applied");
2824             }
2825             return false;
2826         }
2827 
2828         final int uid = sr.appInfo.uid;
2829         final long eligible = mFgsDeferralEligible.get(uid, 0L);
2830         if (DEBUG_FOREGROUND_SERVICE) {
2831             if (now < eligible) {
2832                 Slog.d(TAG_SERVICE, "FGS transition for uid " + uid
2833                         + " within rate limit, showing immediately");
2834             }
2835         }
2836         return now < eligible;
2837     }
2838 
2839     /**
2840      * Validate if the given service can start a foreground service with given type.
2841      *
2842      * @return A pair, where the first parameter is the result code and second is the exception
2843      *         object if it fails to start a foreground service with given type.
2844      */
2845     @NonNull
validateForegroundServiceType(ServiceRecord r, @ForegroundServiceType int type, @ForegroundServiceType int defaultToType, @ForegroundServiceType int startType)2846     private Pair<Integer, RuntimeException> validateForegroundServiceType(ServiceRecord r,
2847             @ForegroundServiceType int type,
2848             @ForegroundServiceType int defaultToType,
2849             @ForegroundServiceType int startType) {
2850         final ForegroundServiceTypePolicy policy = ForegroundServiceTypePolicy.getDefaultPolicy();
2851         final ForegroundServiceTypePolicyInfo policyInfo =
2852                 policy.getForegroundServiceTypePolicyInfo(type, defaultToType);
2853         final @ForegroundServicePolicyCheckCode int code = policy.checkForegroundServiceTypePolicy(
2854                 mAm.mContext, r.packageName, r.app.uid, r.app.getPid(),
2855                 r.isFgsAllowedWiu_forStart(), policyInfo);
2856         RuntimeException exception = null;
2857         switch (code) {
2858             case FGS_TYPE_POLICY_CHECK_DEPRECATED: {
2859                 final String msg = "Starting FGS with type "
2860                         + ServiceInfo.foregroundServiceTypeToLabel(type)
2861                         + " code=" + code
2862                         + " callerApp=" + r.app
2863                         + " targetSDK=" + r.app.info.targetSdkVersion;
2864                 Slog.wtfQuiet(TAG, msg);
2865                 Slog.w(TAG, msg);
2866             } break;
2867             case FGS_TYPE_POLICY_CHECK_DISABLED: {
2868                 if (startType == FOREGROUND_SERVICE_TYPE_MANIFEST
2869                         && type == FOREGROUND_SERVICE_TYPE_NONE) {
2870                     exception = new MissingForegroundServiceTypeException(
2871                             "Starting FGS without a type "
2872                             + " callerApp=" + r.app
2873                             + " targetSDK=" + r.app.info.targetSdkVersion);
2874                 } else {
2875                     exception = new InvalidForegroundServiceTypeException(
2876                             "Starting FGS with type "
2877                             + ServiceInfo.foregroundServiceTypeToLabel(type)
2878                             + " callerApp=" + r.app
2879                             + " targetSDK=" + r.app.info.targetSdkVersion
2880                             + " has been prohibited");
2881                 }
2882             } break;
2883             case FGS_TYPE_POLICY_CHECK_PERMISSION_DENIED_PERMISSIVE: {
2884                 final String msg = "Starting FGS with type "
2885                         + ServiceInfo.foregroundServiceTypeToLabel(type)
2886                         + " code=" + code
2887                         + " callerApp=" + r.app
2888                         + " targetSDK=" + r.app.info.targetSdkVersion
2889                         + " requiredPermissions=" + policyInfo.toPermissionString()
2890                         + (policyInfo.hasForegroundOnlyPermission()
2891                         ? " and the app must be in the eligible state/exemptions"
2892                         + " to access the foreground only permission" : "");
2893                 Slog.wtfQuiet(TAG, msg);
2894                 Slog.w(TAG, msg);
2895             } break;
2896             case FGS_TYPE_POLICY_CHECK_PERMISSION_DENIED_ENFORCED: {
2897                 exception = new SecurityException("Starting FGS with type "
2898                         + ServiceInfo.foregroundServiceTypeToLabel(type)
2899                         + " callerApp=" + r.app
2900                         + " targetSDK=" + r.app.info.targetSdkVersion
2901                         + " requires permissions: "
2902                         + policyInfo.toPermissionString()
2903                         + (policyInfo.hasForegroundOnlyPermission()
2904                         ? " and the app must be in the eligible state/exemptions"
2905                         + " to access the foreground only permission" : ""));
2906             } break;
2907             case FGS_TYPE_POLICY_CHECK_OK:
2908             default:
2909                 break;
2910         }
2911         return Pair.create(code, exception);
2912     }
2913 
2914     private class SystemExemptedFgsTypePermission extends ForegroundServiceTypePermission {
SystemExemptedFgsTypePermission()2915         SystemExemptedFgsTypePermission() {
2916             super("System exempted");
2917         }
2918 
2919         @Override
checkPermission(@onNull Context context, int callerUid, int callerPid, @NonNull String packageName, boolean allowWhileInUse)2920         public int checkPermission(@NonNull Context context, int callerUid, int callerPid,
2921                 @NonNull String packageName, boolean allowWhileInUse) {
2922             final AppRestrictionController appRestrictionController = mAm.mAppRestrictionController;
2923             @ReasonCode int reason = appRestrictionController
2924                     .getPotentialSystemExemptionReason(callerUid);
2925             if (reason == REASON_DENIED) {
2926                 reason = appRestrictionController
2927                         .getPotentialSystemExemptionReason(callerUid, packageName);
2928                 if (reason == REASON_DENIED) {
2929                     reason = appRestrictionController
2930                             .getPotentialUserAllowedExemptionReason(callerUid, packageName);
2931                 }
2932             }
2933             if (reason == REASON_DENIED) {
2934                 if (ArrayUtils.contains(mAm.getPackageManagerInternal().getKnownPackageNames(
2935                         KnownPackages.PACKAGE_INSTALLER, UserHandle.USER_SYSTEM), packageName)) {
2936                     reason = REASON_PACKAGE_INSTALLER;
2937                 }
2938             }
2939 
2940             switch (reason) {
2941                 case REASON_SYSTEM_UID:
2942                 case REASON_SYSTEM_ALLOW_LISTED:
2943                 case REASON_DEVICE_DEMO_MODE:
2944                 case REASON_DISALLOW_APPS_CONTROL:
2945                 case REASON_DEVICE_OWNER:
2946                 case REASON_PROFILE_OWNER:
2947                 case REASON_PROC_STATE_PERSISTENT:
2948                 case REASON_PROC_STATE_PERSISTENT_UI:
2949                 case REASON_SYSTEM_MODULE:
2950                 case REASON_CARRIER_PRIVILEGED_APP:
2951                 case REASON_DPO_PROTECTED_APP:
2952                 case REASON_ACTIVE_DEVICE_ADMIN:
2953                 case REASON_ROLE_EMERGENCY:
2954                 case REASON_ALLOWLISTED_PACKAGE:
2955                 case REASON_PACKAGE_INSTALLER:
2956                 case REASON_SYSTEM_EXEMPT_APP_OP:
2957                     return PERMISSION_GRANTED;
2958                 default:
2959                     return PERMISSION_DENIED;
2960             }
2961         }
2962     }
2963 
initSystemExemptedFgsTypePermission()2964     private void initSystemExemptedFgsTypePermission() {
2965         final ForegroundServiceTypePolicy policy = ForegroundServiceTypePolicy.getDefaultPolicy();
2966         final ForegroundServiceTypePolicyInfo policyInfo =
2967                 policy.getForegroundServiceTypePolicyInfo(
2968                        ServiceInfo.FOREGROUND_SERVICE_TYPE_SYSTEM_EXEMPTED,
2969                        ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE);
2970         if (policyInfo != null) {
2971             policyInfo.setCustomPermission(new SystemExemptedFgsTypePermission());
2972         }
2973     }
2974 
2975     /**
2976      * A custom permission checker for the "mediaProjection" FGS type:
2977      * if the app has been granted the permission to start a media projection via
2978      * the {@link android.media.project.MediaProjectionManager#createScreenCaptureIntent()},
2979      * it'll get the permission to start a foreground service with type "mediaProjection".
2980      */
2981     private class MediaProjectionFgsTypeCustomPermission extends ForegroundServiceTypePermission {
MediaProjectionFgsTypeCustomPermission()2982         MediaProjectionFgsTypeCustomPermission() {
2983             super("Media projection screen capture permission");
2984         }
2985 
2986         @Override
checkPermission(@onNull Context context, int callerUid, int callerPid, @NonNull String packageName, boolean allowWhileInUse)2987         public int checkPermission(@NonNull Context context, int callerUid, int callerPid,
2988                 @NonNull String packageName, boolean allowWhileInUse) {
2989             return mAm.isAllowedMediaProjectionNoOpCheck(callerUid)
2990                     ? PERMISSION_GRANTED : PERMISSION_DENIED;
2991         }
2992     }
2993 
2994     /**
2995      * Set a custom permission checker for the "mediaProjection" FGS type.
2996      */
initMediaProjectFgsTypeCustomPermission()2997     private void initMediaProjectFgsTypeCustomPermission() {
2998         final ForegroundServiceTypePolicy policy = ForegroundServiceTypePolicy.getDefaultPolicy();
2999         final ForegroundServiceTypePolicyInfo policyInfo =
3000                 policy.getForegroundServiceTypePolicyInfo(
3001                        ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION,
3002                        ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE);
3003         if (policyInfo != null) {
3004             policyInfo.setCustomPermission(new MediaProjectionFgsTypeCustomPermission());
3005         }
3006     }
3007 
applyForegroundServiceNotificationLocked(Notification notification, final String tag, final int id, final String pkg, final int userId)3008     ServiceNotificationPolicy applyForegroundServiceNotificationLocked(Notification notification,
3009             final String tag, final int id, final String pkg, final int userId) {
3010         // By nature of the FGS API, all FGS notifications have a null tag
3011         if (tag != null) {
3012             return ServiceNotificationPolicy.NOT_FOREGROUND_SERVICE;
3013         }
3014 
3015         if (DEBUG_FOREGROUND_SERVICE) {
3016             Slog.d(TAG_SERVICE, "Evaluating FGS policy for id=" + id
3017                     + " pkg=" + pkg + " not=" + notification);
3018         }
3019 
3020         // Is there an FGS using this notification?
3021         final ServiceMap smap = mServiceMap.get(userId);
3022         if (smap == null) {
3023             // No services in this user at all
3024             return ServiceNotificationPolicy.NOT_FOREGROUND_SERVICE;
3025         }
3026 
3027         for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
3028             final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
3029             if (!sr.isForeground
3030                     || id != sr.foregroundId
3031                     || !pkg.equals(sr.appInfo.packageName)) {
3032                 // Not this one; keep looking
3033                 continue;
3034             }
3035 
3036             // Found; it is associated with an FGS.  Make sure that it's flagged:
3037             // it may have entered the bookkeeping outside of Service-related
3038             // APIs.  We also make sure to take this latest Notification as
3039             // the content to be shown (immediately or eventually).
3040             if (DEBUG_FOREGROUND_SERVICE) {
3041                 Slog.d(TAG_SERVICE, "   FOUND: notification is for " + sr);
3042             }
3043             notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
3044             sr.foregroundNoti = notification;
3045 
3046             // ...and determine immediate vs deferred display policy for it
3047             final boolean showNow = shouldShowFgsNotificationLocked(sr);
3048             if (showNow) {
3049                 if (DEBUG_FOREGROUND_SERVICE) {
3050                     Slog.d(TAG_SERVICE, "   Showing immediately due to policy");
3051                 }
3052                 sr.mFgsNotificationDeferred = false;
3053                 return ServiceNotificationPolicy.SHOW_IMMEDIATELY;
3054             }
3055 
3056             // Deferring - kick off the timer if necessary, and tell the caller
3057             // that it's to be shown only if it's an update to already-
3058             // visible content (e.g. if it's an FGS adopting a
3059             // previously-posted Notification).
3060             if (DEBUG_FOREGROUND_SERVICE) {
3061                 Slog.d(TAG_SERVICE, "   Deferring / update-only");
3062             }
3063             startFgsDeferralTimerLocked(sr);
3064             return ServiceNotificationPolicy.UPDATE_ONLY;
3065         }
3066 
3067         // None of the services in this user are FGSs
3068         return ServiceNotificationPolicy.NOT_FOREGROUND_SERVICE;
3069     }
3070 
3071     // No legacy-app behavior skew intended but there's a runtime E-stop if a need
3072     // arises, so note that
3073     @SuppressWarnings("AndroidFrameworkCompatChange")
shouldShowFgsNotificationLocked(ServiceRecord r)3074     private boolean shouldShowFgsNotificationLocked(ServiceRecord r) {
3075         final long now = SystemClock.uptimeMillis();
3076 
3077         // Is the behavior enabled at all?
3078         if (!mAm.mConstants.mFlagFgsNotificationDeferralEnabled) {
3079             return true;
3080         }
3081 
3082         // Has this service's deferral timer expired?
3083         if (r.mFgsNotificationDeferred && now >= r.fgDisplayTime) {
3084             if (DEBUG_FOREGROUND_SERVICE) {
3085                 Slog.d(TAG, "FGS reached end of deferral period: " + r);
3086             }
3087             return true;
3088         }
3089 
3090         // Did the app have another FGS notification deferred recently?
3091         if (withinFgsDeferRateLimit(r, now)) {
3092             return true;
3093         }
3094 
3095         if (mAm.mConstants.mFlagFgsNotificationDeferralApiGated) {
3096             // Legacy apps' FGS notifications are also deferred unless the relevant
3097             // DeviceConfig element has been set
3098             final boolean isLegacyApp = (r.appInfo.targetSdkVersion < Build.VERSION_CODES.S);
3099             if (isLegacyApp) {
3100                 return true;
3101             }
3102         }
3103 
3104         // did we already show it?
3105         if (r.mFgsNotificationShown) {
3106             return true;
3107         }
3108 
3109         // has the app forced deferral?
3110         if (!r.foregroundNoti.isForegroundDisplayForceDeferred()) {
3111             // is the notification such that it should show right away?
3112             if (r.foregroundNoti.shouldShowForegroundImmediately()) {
3113                 if (DEBUG_FOREGROUND_SERVICE) {
3114                     Slog.d(TAG_SERVICE, "FGS " + r
3115                             + " notification policy says show immediately");
3116                 }
3117                 return true;
3118             }
3119 
3120             // or is this an type of FGS that always shows immediately?
3121             if ((r.foregroundServiceType & FGS_IMMEDIATE_DISPLAY_MASK) != 0) {
3122                 if (DEBUG_FOREGROUND_SERVICE) {
3123                     Slog.d(TAG_SERVICE, "FGS " + r
3124                             + " type gets immediate display");
3125                 }
3126                 return true;
3127             }
3128 
3129             // fall through to return false: no policy dictates immediate display
3130         } else {
3131             if (DEBUG_FOREGROUND_SERVICE) {
3132                 Slog.d(TAG_SERVICE, "FGS " + r + " notification is app deferred");
3133             }
3134             // fall through to return false
3135         }
3136 
3137         return false;
3138     }
3139 
3140     // Target SDK consultation here is strictly for logging purposes, not
3141     // behavioral variation.
3142     @SuppressWarnings("AndroidFrameworkCompatChange")
startFgsDeferralTimerLocked(ServiceRecord r)3143     private void startFgsDeferralTimerLocked(ServiceRecord r) {
3144         final long now = SystemClock.uptimeMillis();
3145         final int uid = r.appInfo.uid;
3146 
3147         // schedule the actual notification post
3148         long when = now
3149                 + (r.isShortFgs() ? mAm.mConstants.mFgsNotificationDeferralIntervalForShort
3150                 : mAm.mConstants.mFgsNotificationDeferralInterval);
3151         // If there are already deferred FGS notifications for this app,
3152         // inherit that deferred-show timestamp
3153         for (int i = 0; i < mPendingFgsNotifications.size(); i++) {
3154             final ServiceRecord pending = mPendingFgsNotifications.get(i);
3155             if (pending == r) {
3156                 // Already pending; no need to reschedule
3157                 if (DEBUG_FOREGROUND_SERVICE) {
3158                     Slog.d(TAG_SERVICE, "FGS " + r
3159                             + " already pending notification display");
3160                 }
3161                 return;
3162             }
3163             if (uid == pending.appInfo.uid) {
3164                 when = Math.min(when, pending.fgDisplayTime);
3165             }
3166         }
3167 
3168         if (mFgsDeferralRateLimited) {
3169             final long nextEligible = when
3170                     + (r.isShortFgs() ? mAm.mConstants.mFgsNotificationDeferralExclusionTimeForShort
3171                     : mAm.mConstants.mFgsNotificationDeferralExclusionTime);
3172             mFgsDeferralEligible.put(uid, nextEligible);
3173         }
3174         r.fgDisplayTime = when;
3175         r.mFgsNotificationDeferred = true;
3176         r.mFgsNotificationWasDeferred = true;
3177         r.mFgsNotificationShown = false;
3178         mPendingFgsNotifications.add(r);
3179         if (DEBUG_FOREGROUND_SERVICE) {
3180             Slog.d(TAG_SERVICE, "FGS " + r
3181                     + " notification in " + (when - now) + " ms");
3182         }
3183         final boolean isLegacyApp = (r.appInfo.targetSdkVersion < Build.VERSION_CODES.S);
3184         if (isLegacyApp) {
3185             Slog.i(TAG_SERVICE, "Deferring FGS notification in legacy app "
3186                     + r.appInfo.packageName + "/" + UserHandle.formatUid(r.appInfo.uid)
3187                     + " : " + r.foregroundNoti);
3188         }
3189         mAm.mHandler.postAtTime(mPostDeferredFGSNotifications, when);
3190     }
3191 
3192     private final Runnable mPostDeferredFGSNotifications = new Runnable() {
3193         @Override
3194         public void run() {
3195             if (DEBUG_FOREGROUND_SERVICE) {
3196                 Slog.d(TAG_SERVICE, "+++ evaluating deferred FGS notifications +++");
3197             }
3198             final long now = SystemClock.uptimeMillis();
3199             synchronized (mAm) {
3200                 // post all notifications whose time has come
3201                 for (int i = mPendingFgsNotifications.size() - 1; i >= 0; i--) {
3202                     final ServiceRecord r = mPendingFgsNotifications.get(i);
3203                     if (r.fgDisplayTime <= now) {
3204                         if (DEBUG_FOREGROUND_SERVICE) {
3205                             Slog.d(TAG_SERVICE, "FGS " + r
3206                                     + " handling deferred notification now");
3207                         }
3208                         mPendingFgsNotifications.remove(i);
3209                         // The service might have been stopped or exited foreground state
3210                         // in the interval, so we lazy check whether we still need to show
3211                         // the notification.
3212                         if (r.isForeground && r.app != null) {
3213                             r.postNotification(true);
3214                             r.mFgsNotificationShown = true;
3215                         } else {
3216                             if (DEBUG_FOREGROUND_SERVICE) {
3217                                 Slog.d(TAG_SERVICE, "  - service no longer running/fg, ignoring");
3218                             }
3219                         }
3220                     }
3221                 }
3222                 if (DEBUG_FOREGROUND_SERVICE) {
3223                     Slog.d(TAG_SERVICE, "Done evaluating deferred FGS notifications; "
3224                             + mPendingFgsNotifications.size() + " remaining");
3225                 }
3226             }
3227         }
3228     };
3229 
3230     /**
3231      * Suppress or reenable the rate limit on foreground service notification deferral.
3232      * Invoked from the activity manager shell command.
3233      *
3234      * @param enable false to suppress rate-limit policy; true to reenable it.
3235      */
enableFgsNotificationRateLimitLocked(final boolean enable)3236     boolean enableFgsNotificationRateLimitLocked(final boolean enable) {
3237         if (enable != mFgsDeferralRateLimited) {
3238             mFgsDeferralRateLimited = enable;
3239             if (!enable) {
3240                 // make sure to reset any active rate limiting
3241                 mFgsDeferralEligible.clear();
3242             }
3243         }
3244         return enable;
3245     }
3246 
removeServiceNotificationDeferralsLocked(String packageName, final @UserIdInt int userId)3247     private void removeServiceNotificationDeferralsLocked(String packageName,
3248             final @UserIdInt int userId) {
3249         for (int i = mPendingFgsNotifications.size() - 1; i >= 0; i--) {
3250             final ServiceRecord r = mPendingFgsNotifications.get(i);
3251             if (userId == r.userId
3252                     && r.appInfo.packageName.equals(packageName)) {
3253                 mPendingFgsNotifications.remove(i);
3254                 if (DEBUG_FOREGROUND_SERVICE) {
3255                     Slog.d(TAG_SERVICE, "Removing notification deferral for "
3256                             + r);
3257                 }
3258             }
3259         }
3260     }
3261 
3262     /**
3263      * Callback from NotificationManagerService whenever it posts a notification
3264      * associated with a foreground service.  This is the unified handling point
3265      * for the disjoint code flows that affect an FGS's notifiation content and
3266      * visibility, starting with both Service.startForeground() and
3267      * NotificationManager.notify().
3268      */
onForegroundServiceNotificationUpdateLocked(boolean shown, Notification notification, final int id, final String pkg, @UserIdInt final int userId)3269     public void onForegroundServiceNotificationUpdateLocked(boolean shown,
3270             Notification notification, final int id, final String pkg,
3271             @UserIdInt final int userId) {
3272         // If this happens to be a Notification for an FGS still in its deferral period,
3273         // drop the deferral and make sure our content bookkeeping is up to date.
3274         for (int i = mPendingFgsNotifications.size() - 1; i >= 0; i--) {
3275             final ServiceRecord sr = mPendingFgsNotifications.get(i);
3276             if (userId == sr.userId
3277                     && id == sr.foregroundId
3278                     && sr.appInfo.packageName.equals(pkg)) {
3279                 // Found it.  If 'shown' is false, it means that the notification
3280                 // subsystem will not be displaying it yet.
3281                 if (shown) {
3282                     if (DEBUG_FOREGROUND_SERVICE) {
3283                         Slog.d(TAG_SERVICE, "Notification shown; canceling deferral of "
3284                                 + sr);
3285                     }
3286                     sr.mFgsNotificationShown = true;
3287                     sr.mFgsNotificationDeferred = false;
3288                     mPendingFgsNotifications.remove(i);
3289                 } else {
3290                     if (DEBUG_FOREGROUND_SERVICE) {
3291                         Slog.d(TAG_SERVICE, "FGS notification deferred for " + sr);
3292                     }
3293                 }
3294             }
3295         }
3296         // In all cases, make sure to retain the latest notification content for the FGS
3297         ServiceMap smap = mServiceMap.get(userId);
3298         if (smap != null) {
3299             for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
3300                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
3301                 if (sr.isForeground
3302                         && id == sr.foregroundId
3303                         && sr.appInfo.packageName.equals(pkg)) {
3304                     if (DEBUG_FOREGROUND_SERVICE) {
3305                         Slog.d(TAG_SERVICE, "Recording shown notification for "
3306                                 + sr);
3307                     }
3308                     sr.foregroundNoti = notification;
3309                 }
3310             }
3311         }
3312     }
3313 
3314     /** Registers an AppOpCallback for monitoring special AppOps for this foreground service. */
registerAppOpCallbackLocked(@onNull ServiceRecord r)3315     private void registerAppOpCallbackLocked(@NonNull ServiceRecord r) {
3316         if (r.app == null) {
3317             return;
3318         }
3319         final int uid = r.appInfo.uid;
3320         AppOpCallback callback = mFgsAppOpCallbacks.get(uid);
3321         if (callback == null) {
3322             callback = new AppOpCallback(r.app, mAm.getAppOpsManager());
3323             mFgsAppOpCallbacks.put(uid, callback);
3324         }
3325         callback.registerLocked();
3326     }
3327 
3328     /** Unregisters a foreground service's AppOpCallback. */
unregisterAppOpCallbackLocked(@onNull ServiceRecord r)3329     private void unregisterAppOpCallbackLocked(@NonNull ServiceRecord r) {
3330         final int uid = r.appInfo.uid;
3331         final AppOpCallback callback = mFgsAppOpCallbacks.get(uid);
3332         if (callback != null) {
3333             callback.unregisterLocked();
3334             if (callback.isObsoleteLocked()) {
3335                 mFgsAppOpCallbacks.remove(uid);
3336             }
3337         }
3338     }
3339 
3340     /**
3341      * For monitoring when {@link #LOGGED_AP_OPS} AppOps occur by an app while it is holding
3342      * at least one foreground service and is not also in the TOP state.
3343      * Once the uid no longer holds any foreground services, this callback becomes stale
3344      * (marked by {@link #isObsoleteLocked()}) and must no longer be used.
3345      *
3346      * Methods that end in Locked should only be called while the mAm lock is held.
3347      */
3348     private static final class AppOpCallback {
3349         /** AppOps that should be logged if they occur during a foreground service. */
3350         private static final int[] LOGGED_AP_OPS = new int[] {
3351                 AppOpsManager.OP_COARSE_LOCATION,
3352                 AppOpsManager.OP_FINE_LOCATION,
3353                 AppOpsManager.OP_RECORD_AUDIO,
3354                 AppOpsManager.OP_CAMERA
3355         };
3356 
3357         private final ProcessRecord mProcessRecord;
3358 
3359         /** Count of acceptances per appop (for LOGGED_AP_OPS) during this fgs session. */
3360         @GuardedBy("mCounterLock")
3361         private final SparseIntArray mAcceptedOps = new SparseIntArray();
3362         /** Count of rejections per appop (for LOGGED_AP_OPS) during this fgs session. */
3363         @GuardedBy("mCounterLock")
3364         private final SparseIntArray mRejectedOps = new SparseIntArray();
3365 
3366         /** Lock for the purposes of mAcceptedOps and mRejectedOps. */
3367         private final Object mCounterLock = new Object();
3368 
3369         /**
3370          * AppOp Mode (e.g. {@link AppOpsManager#MODE_ALLOWED} per op.
3371          * This currently cannot change without the process being killed, so they are constants.
3372          */
3373         private final SparseIntArray mAppOpModes = new SparseIntArray();
3374 
3375         /**
3376          * Number of foreground services currently associated with this AppOpCallback (i.e.
3377          * currently held for this uid).
3378          */
3379         @GuardedBy("mAm")
3380         private int mNumFgs = 0;
3381 
3382         /**
3383          * Indicates that this Object is stale and must not be used.
3384          * Specifically, when mNumFgs decreases down to 0, the callbacks will be unregistered and
3385          * this AppOpCallback is unusable.
3386          */
3387         @GuardedBy("mAm")
3388         private boolean mDestroyed = false;
3389 
3390         private final AppOpsManager mAppOpsManager;
3391 
AppOpCallback(@onNull ProcessRecord r, @NonNull AppOpsManager appOpsManager)3392         AppOpCallback(@NonNull ProcessRecord r, @NonNull AppOpsManager appOpsManager) {
3393             mProcessRecord = r;
3394             mAppOpsManager = appOpsManager;
3395             for (int op : LOGGED_AP_OPS) {
3396                 int mode = appOpsManager.unsafeCheckOpRawNoThrow(op, r.uid, r.info.packageName);
3397                 mAppOpModes.put(op, mode);
3398             }
3399         }
3400 
3401         private final AppOpsManager.OnOpNotedInternalListener mOpNotedCallback =
3402                 new AppOpsManager.OnOpNotedInternalListener() {
3403                     @Override
3404                     public void onOpNoted(int op, int uid, String pkgName,
3405                             String attributionTag, int flags, int result) {
3406                         incrementOpCountIfNeeded(op, uid, result);
3407                     }
3408         };
3409 
3410         private final AppOpsManager.OnOpStartedListener mOpStartedCallback =
3411                 new AppOpsManager.OnOpStartedListener() {
3412                     @Override
3413                     public void onOpStarted(int op, int uid, String pkgName,
3414                             String attributionTag, int flags,
3415                             int result) {
3416                         incrementOpCountIfNeeded(op, uid, result);
3417                     }
3418         };
3419 
incrementOpCountIfNeeded(int op, int uid, @AppOpsManager.Mode int result)3420         private void incrementOpCountIfNeeded(int op, int uid, @AppOpsManager.Mode int result) {
3421             if (uid == mProcessRecord.uid && isNotTop()) {
3422                 incrementOpCount(op, result == AppOpsManager.MODE_ALLOWED);
3423             }
3424         }
3425 
isNotTop()3426         private boolean isNotTop() {
3427             return mProcessRecord.mState.getCurProcState() != PROCESS_STATE_TOP;
3428         }
3429 
incrementOpCount(int op, boolean allowed)3430         private void incrementOpCount(int op, boolean allowed) {
3431             synchronized (mCounterLock) {
3432                 final SparseIntArray counter = allowed ? mAcceptedOps : mRejectedOps;
3433                 final int index = counter.indexOfKey(op);
3434                 if (index < 0) {
3435                     counter.put(op, 1);
3436                 } else {
3437                     counter.setValueAt(index, counter.valueAt(index) + 1);
3438                 }
3439             }
3440         }
3441 
registerLocked()3442         void registerLocked() {
3443             if (isObsoleteLocked()) {
3444                 Slog.wtf(TAG, "Trying to register on a stale AppOpCallback.");
3445                 return;
3446             }
3447             mNumFgs++;
3448             if (mNumFgs == 1) {
3449                 mAppOpsManager.startWatchingNoted(LOGGED_AP_OPS, mOpNotedCallback);
3450                 mAppOpsManager.startWatchingStarted(LOGGED_AP_OPS, mOpStartedCallback);
3451             }
3452         }
3453 
unregisterLocked()3454         void unregisterLocked() {
3455             mNumFgs--;
3456             if (mNumFgs <= 0) {
3457                 mDestroyed = true;
3458                 logFinalValues();
3459                 mAppOpsManager.stopWatchingNoted(mOpNotedCallback);
3460                 mAppOpsManager.stopWatchingStarted(mOpStartedCallback);
3461             }
3462         }
3463 
3464         /**
3465          * Indicates that all foreground services for this uid are now over and the callback is
3466          * stale and must never be used again.
3467          */
isObsoleteLocked()3468         boolean isObsoleteLocked() {
3469             return mDestroyed;
3470         }
3471 
logFinalValues()3472         private void logFinalValues() {
3473             synchronized (mCounterLock) {
3474                 for (int op : LOGGED_AP_OPS) {
3475                     final int acceptances = mAcceptedOps.get(op);
3476                     final int rejections = mRejectedOps.get(op);
3477                     if (acceptances > 0 ||  rejections > 0) {
3478                         FrameworkStatsLog.write(
3479                                 FrameworkStatsLog.FOREGROUND_SERVICE_APP_OP_SESSION_ENDED,
3480                                 mProcessRecord.uid, op,
3481                                 modeToEnum(mAppOpModes.get(op)),
3482                                 acceptances, rejections
3483                         );
3484                     }
3485                 }
3486             }
3487         }
3488 
3489         /** Maps AppOp mode to atoms.proto enum. */
modeToEnum(int mode)3490         private static int modeToEnum(int mode) {
3491             switch (mode) {
3492                 case AppOpsManager.MODE_ALLOWED: return FrameworkStatsLog
3493                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_ALLOWED;
3494                 case AppOpsManager.MODE_IGNORED: return FrameworkStatsLog
3495                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_IGNORED;
3496                 case AppOpsManager.MODE_FOREGROUND: return FrameworkStatsLog
3497                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_FOREGROUND;
3498                 default: return FrameworkStatsLog
3499                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_UNKNOWN;
3500             }
3501         }
3502     }
3503 
cancelForegroundNotificationLocked(ServiceRecord r)3504     private void cancelForegroundNotificationLocked(ServiceRecord r) {
3505         if (r.foregroundNoti != null) {
3506             // First check to see if this app has any other active foreground services
3507             // with the same notification ID.  If so, we shouldn't actually cancel it,
3508             // because that would wipe away the notification that still needs to be shown
3509             // due the other service.
3510             ServiceMap sm = getServiceMapLocked(r.userId);
3511             if (sm != null) {
3512                 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
3513                     ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
3514                     if (other != r
3515                             && other.isForeground
3516                             && other.foregroundId == r.foregroundId
3517                             && other.packageName.equals(r.packageName)) {
3518                         if (DEBUG_FOREGROUND_SERVICE) {
3519                             Slog.i(TAG_SERVICE, "FGS notification for " + r
3520                                     + " shared by " + other
3521                                     + " (isForeground=" + other.isForeground + ")"
3522                                     + " - NOT cancelling");
3523                         }
3524                         return;
3525                     }
3526                 }
3527             }
3528             r.cancelNotification();
3529         }
3530     }
3531 
updateServiceForegroundLocked(ProcessServiceRecord psr, boolean oomAdj)3532     private void updateServiceForegroundLocked(ProcessServiceRecord psr, boolean oomAdj) {
3533         boolean anyForeground = false;
3534         int fgServiceTypes = 0;
3535         boolean hasTypeNone = false;
3536         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
3537             ServiceRecord sr = psr.getRunningServiceAt(i);
3538             if (sr.isForeground || sr.fgRequired) {
3539                 anyForeground = true;
3540                 fgServiceTypes |= sr.foregroundServiceType;
3541                 if (sr.foregroundServiceType == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE) {
3542                     hasTypeNone = true;
3543                 }
3544             }
3545         }
3546         mAm.updateProcessForegroundLocked(psr.mApp, anyForeground,
3547                 fgServiceTypes, hasTypeNone, oomAdj);
3548         psr.setHasReportedForegroundServices(anyForeground);
3549     }
3550 
unscheduleShortFgsTimeoutLocked(ServiceRecord sr)3551     void unscheduleShortFgsTimeoutLocked(ServiceRecord sr) {
3552         mShortFGSAnrTimer.cancel(sr);
3553         mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG,
3554                 sr);
3555         mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_SHORT_FGS_TIMEOUT_MSG, sr);
3556     }
3557 
3558     /**
3559      * Update a {@link ServiceRecord}'s {@link ShortFgsInfo} as needed, and also start
3560      * a timeout as needed.
3561      *
3562      * If the {@link ServiceRecord} is not a short-FGS, then we'll stop the timeout and clear
3563      * the {@link ShortFgsInfo}.
3564      */
maybeUpdateShortFgsTrackingLocked(ServiceRecord sr, boolean extendTimeout)3565     private void maybeUpdateShortFgsTrackingLocked(ServiceRecord sr,
3566             boolean extendTimeout) {
3567         if (!sr.isShortFgs()) {
3568             sr.clearShortFgsInfo(); // Just in case we have it.
3569             unscheduleShortFgsTimeoutLocked(sr);
3570             return;
3571         }
3572 
3573         final boolean isAlreadyShortFgs = sr.hasShortFgsInfo();
3574 
3575         if (extendTimeout || !isAlreadyShortFgs) {
3576             if (DEBUG_SHORT_SERVICE) {
3577                 if (isAlreadyShortFgs) {
3578                     Slog.i(TAG_SERVICE, "Extending SHORT_SERVICE time out: " + sr);
3579                 } else {
3580                     Slog.i(TAG_SERVICE, "Short FGS started: " + sr);
3581                 }
3582             }
3583             traceInstant("short FGS start/extend: ", sr);
3584             sr.setShortFgsInfo(SystemClock.uptimeMillis());
3585 
3586             // We'll restart the timeout.
3587             unscheduleShortFgsTimeoutLocked(sr);
3588 
3589             final Message msg = mAm.mHandler.obtainMessage(
3590                     ActivityManagerService.SERVICE_SHORT_FGS_TIMEOUT_MSG, sr);
3591             mAm.mHandler.sendMessageAtTime(msg, sr.getShortFgsInfo().getTimeoutTime());
3592         } else {
3593             if (DEBUG_SHORT_SERVICE) {
3594                 Slog.w(TAG_SERVICE, "NOT extending SHORT_SERVICE time out: " + sr);
3595             }
3596 
3597             // We only (potentially) update the start command, start count, but not the timeout
3598             // time.
3599             // In this case, we keep the existing timeout running.
3600             sr.getShortFgsInfo().update();
3601         }
3602     }
3603 
3604     /**
3605      * Stop the timeout for a ServiceRecord, if it's of a short-FGS.
3606      */
maybeStopShortFgsTimeoutLocked(ServiceRecord sr)3607     private void maybeStopShortFgsTimeoutLocked(ServiceRecord sr) {
3608         sr.clearShortFgsInfo(); // Always clear, just in case.
3609         if (!sr.isShortFgs()) {
3610             return;
3611         }
3612         if (DEBUG_SHORT_SERVICE) {
3613             Slog.i(TAG_SERVICE, "Stop short FGS timeout: " + sr);
3614         }
3615         unscheduleShortFgsTimeoutLocked(sr);
3616     }
3617 
onShortFgsTimeout(ServiceRecord sr)3618     void onShortFgsTimeout(ServiceRecord sr) {
3619         synchronized (mAm) {
3620             final long nowUptime = SystemClock.uptimeMillis();
3621             if (!sr.shouldTriggerShortFgsTimeout(nowUptime)) {
3622                 if (DEBUG_SHORT_SERVICE) {
3623                     Slog.d(TAG_SERVICE, "[STALE] Short FGS timed out: " + sr
3624                             + " " + sr.getShortFgsTimedEventDescription(nowUptime));
3625                 }
3626                 return;
3627             }
3628             Slog.e(TAG_SERVICE, "Short FGS timed out: " + sr);
3629             traceInstant("short FGS timeout: ", sr);
3630 
3631             logFGSStateChangeLocked(sr,
3632                     FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT,
3633                     nowUptime > sr.mFgsEnterTime ? (int) (nowUptime - sr.mFgsEnterTime) : 0,
3634                     FGS_STOP_REASON_UNKNOWN,
3635                     FGS_TYPE_POLICY_CHECK_UNKNOWN,
3636                     FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
3637                     false /* fgsRestrictionRecalculated */
3638             );
3639             try {
3640                 sr.app.getThread().scheduleTimeoutService(sr, sr.getShortFgsInfo().getStartId());
3641             } catch (RemoteException e) {
3642                 Slog.w(TAG_SERVICE, "Exception from scheduleTimeoutService: " + e.toString());
3643             }
3644             // Schedule the procstate demotion timeout and ANR timeout.
3645             {
3646                 final Message msg = mAm.mHandler.obtainMessage(
3647                         ActivityManagerService.SERVICE_SHORT_FGS_PROCSTATE_TIMEOUT_MSG, sr);
3648                 mAm.mHandler.sendMessageAtTime(
3649                         msg, sr.getShortFgsInfo().getProcStateDemoteTime());
3650             }
3651 
3652             // ServiceRecord.getAnrTime() is an absolute time with a reference that is not "now".
3653             // Compute the time from "now" when starting the anr timer.
3654             mShortFGSAnrTimer.start(sr,
3655                     sr.getShortFgsInfo().getAnrTime() - SystemClock.uptimeMillis());
3656         }
3657     }
3658 
shouldServiceTimeOutLocked(ComponentName className, IBinder token)3659     boolean shouldServiceTimeOutLocked(ComponentName className, IBinder token) {
3660         final int userId = UserHandle.getCallingUserId();
3661         final long ident = mAm.mInjector.clearCallingIdentity();
3662         try {
3663             ServiceRecord sr = findServiceLocked(className, token, userId);
3664             if (sr == null) {
3665                 return false;
3666             }
3667             final long nowUptime = SystemClock.uptimeMillis();
3668             return sr.shouldTriggerShortFgsTimeout(nowUptime);
3669         } finally {
3670             mAm.mInjector.restoreCallingIdentity(ident);
3671         }
3672     }
3673 
onShortFgsProcstateTimeout(ServiceRecord sr)3674     void onShortFgsProcstateTimeout(ServiceRecord sr) {
3675         synchronized (mAm) {
3676             final long nowUptime = SystemClock.uptimeMillis();
3677             if (!sr.shouldDemoteShortFgsProcState(nowUptime)) {
3678                 if (DEBUG_SHORT_SERVICE) {
3679                     Slog.d(TAG_SERVICE, "[STALE] Short FGS procstate demotion: " + sr
3680                             + " " + sr.getShortFgsTimedEventDescription(nowUptime));
3681                 }
3682                 return;
3683             }
3684 
3685             Slog.e(TAG_SERVICE, "Short FGS procstate demoted: " + sr);
3686             traceInstant("short FGS demote: ", sr);
3687 
3688             mAm.updateOomAdjLocked(sr.app, OOM_ADJ_REASON_SHORT_FGS_TIMEOUT);
3689         }
3690     }
3691 
onShortFgsAnrTimeout(ServiceRecord sr)3692     void onShortFgsAnrTimeout(ServiceRecord sr) {
3693         final String reason = "A foreground service of FOREGROUND_SERVICE_TYPE_SHORT_SERVICE"
3694                 + " did not stop within a timeout: " + sr.getComponentName();
3695 
3696         final TimeoutRecord tr = TimeoutRecord.forShortFgsTimeout(reason);
3697 
3698         tr.mLatencyTracker.waitingOnAMSLockStarted();
3699         synchronized (mAm) {
3700             tr.mLatencyTracker.waitingOnAMSLockEnded();
3701 
3702             final long nowUptime = SystemClock.uptimeMillis();
3703             if (!sr.shouldTriggerShortFgsAnr(nowUptime)) {
3704                 if (DEBUG_SHORT_SERVICE) {
3705                     Slog.d(TAG_SERVICE, "[STALE] Short FGS ANR'ed: " + sr
3706                             + " " + sr.getShortFgsTimedEventDescription(nowUptime));
3707                 }
3708                 mShortFGSAnrTimer.discard(sr);
3709                 return;
3710             }
3711             mShortFGSAnrTimer.accept(sr);
3712 
3713             final String message = "Short FGS ANR'ed: " + sr;
3714             if (DEBUG_SHORT_SERVICE) {
3715                 Slog.wtf(TAG_SERVICE, message);
3716             } else {
3717                 Slog.e(TAG_SERVICE, message);
3718             }
3719 
3720             traceInstant("short FGS ANR: ", sr);
3721 
3722             mAm.appNotResponding(sr.app, tr);
3723 
3724             // TODO: Can we close the ANR dialog here, if it's still shown? Currently, the ANR
3725             // dialog really doesn't remember the "cause" (especially if there have been multiple
3726             // ANRs), so it's not doable.
3727         }
3728     }
3729 
3730     /**
3731      * @return the fgs type for this service which has the most lenient time limit; if none of the
3732      * types are time-restricted, return {@link ServiceInfo#FOREGROUND_SERVICE_TYPE_NONE}.
3733      */
getTimeLimitedFgsType(int foregroundServiceType)3734     @ServiceInfo.ForegroundServiceType int getTimeLimitedFgsType(int foregroundServiceType) {
3735         int fgsType = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
3736         long timeout = 0;
3737         if ((foregroundServiceType & ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING)
3738                 == ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING) {
3739             fgsType = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING;
3740             timeout = mAm.mConstants.mMediaProcessingFgsTimeoutDuration;
3741         }
3742         if ((foregroundServiceType & ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
3743                 == ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) {
3744             // update the timeout and type if this type has a more lenient time limit
3745             if (timeout == 0 || mAm.mConstants.mDataSyncFgsTimeoutDuration > timeout) {
3746                 fgsType = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC;
3747                 timeout = mAm.mConstants.mDataSyncFgsTimeoutDuration;
3748             }
3749         }
3750         // Add logic for time limits introduced in the future for other fgs types above.
3751         return fgsType;
3752     }
3753 
3754     /**
3755      * @return the constant time limit defined for the given foreground service type.
3756      */
getTimeLimitForFgsType(int foregroundServiceType)3757     private long getTimeLimitForFgsType(int foregroundServiceType) {
3758         return switch (foregroundServiceType) {
3759             case ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING ->
3760                     mAm.mConstants.mMediaProcessingFgsTimeoutDuration;
3761             case ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC ->
3762                     mAm.mConstants.mDataSyncFgsTimeoutDuration;
3763             // Add logic for time limits introduced in the future for other fgs types above.
3764             default -> Long.MAX_VALUE;
3765         };
3766     }
3767 
3768     /**
3769      * @return the next stop time for the given type, based on how long it has already ran for.
3770      * The total runtime is automatically reset 24hrs after the first fgs start of this type
3771      * or if the app has recently been in the TOP state when the app calls startForeground().
3772      */
getNextFgsStopTime(int fgsType, TimeLimitedFgsInfo fgsInfo)3773     private long getNextFgsStopTime(int fgsType, TimeLimitedFgsInfo fgsInfo) {
3774         final long timeLimit = getTimeLimitForFgsType(fgsType);
3775         if (timeLimit == Long.MAX_VALUE) {
3776             return Long.MAX_VALUE;
3777         }
3778         return fgsInfo.getLastFgsStartTime() + Math.max(0, timeLimit - fgsInfo.getTotalRuntime());
3779     }
3780 
getFgsTimeLimitedInfo(int uid, int fgsType)3781     private TimeLimitedFgsInfo getFgsTimeLimitedInfo(int uid, int fgsType) {
3782         final SparseArray<TimeLimitedFgsInfo> fgsInfo = mTimeLimitedFgsInfo.get(uid);
3783         if (fgsInfo != null) {
3784             return fgsInfo.get(fgsType);
3785         }
3786         return null;
3787     }
3788 
maybeUpdateFgsTrackingLocked(ServiceRecord sr, int previousFgsType)3789     private void maybeUpdateFgsTrackingLocked(ServiceRecord sr, int previousFgsType) {
3790         final int previouslyTimeLimitedType = getTimeLimitedFgsType(previousFgsType);
3791         if (previouslyTimeLimitedType == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE
3792                 && !sr.isFgsTimeLimited()) {
3793             // FGS was not previously time-limited and new type isn't either.
3794             return;
3795         }
3796 
3797         if (previouslyTimeLimitedType != ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE) {
3798             // FGS is switching types and the previous type was time-limited so update the runtime.
3799             final TimeLimitedFgsInfo fgsTypeInfo = getFgsTimeLimitedInfo(
3800                                                     sr.appInfo.uid, previouslyTimeLimitedType);
3801             if (fgsTypeInfo != null) {
3802                 // Update the total runtime for the previous time-limited fgs type.
3803                 fgsTypeInfo.updateTotalRuntime(SystemClock.uptimeMillis());
3804                 fgsTypeInfo.decNumParallelServices();
3805             }
3806 
3807             if (!sr.isFgsTimeLimited()) {
3808                 // Reset timers since new type does not have a timeout.
3809                 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
3810                 mAm.mHandler.removeMessages(
3811                                 ActivityManagerService.SERVICE_FGS_CRASH_TIMEOUT_MSG, sr);
3812                 return;
3813             }
3814         }
3815 
3816         traceInstant("FGS start: ", sr);
3817         final long nowUptime = SystemClock.uptimeMillis();
3818 
3819         // Fetch/create/update the fgs info for the time-limited type.
3820         SparseArray<TimeLimitedFgsInfo> fgsInfo = mTimeLimitedFgsInfo.get(sr.appInfo.uid);
3821         if (fgsInfo == null) {
3822             fgsInfo = new SparseArray<>();
3823             mTimeLimitedFgsInfo.put(sr.appInfo.uid, fgsInfo);
3824         }
3825         final int timeLimitedFgsType = getTimeLimitedFgsType(sr.foregroundServiceType);
3826         TimeLimitedFgsInfo fgsTypeInfo = fgsInfo.get(timeLimitedFgsType);
3827         if (fgsTypeInfo == null) {
3828             fgsTypeInfo = sr.createTimeLimitedFgsInfo();
3829             fgsInfo.put(timeLimitedFgsType, fgsTypeInfo);
3830         }
3831         fgsTypeInfo.noteFgsFgsStart(nowUptime);
3832 
3833         // We'll cancel the timeout and crash messages and post a fresh one below.
3834         mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
3835         mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_CRASH_TIMEOUT_MSG, sr);
3836 
3837         final Message msg = mAm.mHandler.obtainMessage(
3838                 ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
3839         final long timeoutCallbackTime = getNextFgsStopTime(timeLimitedFgsType, fgsTypeInfo);
3840         if (timeoutCallbackTime == Long.MAX_VALUE) {
3841             // This should never happen since we only get to this point if the service record's
3842             // foregroundServiceType attribute contains a type that can be timed-out.
3843             Slog.wtf(TAG, "Couldn't calculate timeout for time-limited fgs: " + sr);
3844             return;
3845         }
3846         mAm.mHandler.sendMessageAtTime(msg, timeoutCallbackTime);
3847     }
3848 
maybeStopFgsTimeoutLocked(ServiceRecord sr)3849     private void maybeStopFgsTimeoutLocked(ServiceRecord sr) {
3850         final int timeLimitedType = getTimeLimitedFgsType(sr.foregroundServiceType);
3851         if (timeLimitedType == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE) {
3852             return; // if the current fgs type is not time-limited, return.
3853         }
3854 
3855         final TimeLimitedFgsInfo fgsTypeInfo = getFgsTimeLimitedInfo(
3856                                                 sr.appInfo.uid, timeLimitedType);
3857         if (fgsTypeInfo != null) {
3858             // Update the total runtime for the previous time-limited fgs type.
3859             fgsTypeInfo.updateTotalRuntime(SystemClock.uptimeMillis());
3860             fgsTypeInfo.decNumParallelServices();
3861         }
3862         Slog.d(TAG_SERVICE, "Stop FGS timeout: " + sr);
3863         mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
3864         mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_CRASH_TIMEOUT_MSG, sr);
3865     }
3866 
onUidRemovedLocked(int uid)3867     void onUidRemovedLocked(int uid) {
3868         // Remove all time-limited fgs tracking info stored for this uid.
3869         mTimeLimitedFgsInfo.delete(uid);
3870     }
3871 
hasServiceTimedOutLocked(ComponentName className, IBinder token)3872     boolean hasServiceTimedOutLocked(ComponentName className, IBinder token) {
3873         final int userId = UserHandle.getCallingUserId();
3874         final long ident = mAm.mInjector.clearCallingIdentity();
3875         try {
3876             ServiceRecord sr = findServiceLocked(className, token, userId);
3877             if (sr == null) {
3878                 return false;
3879             }
3880             return getTimeLimitedFgsType(sr.foregroundServiceType)
3881                     != ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
3882         } finally {
3883             mAm.mInjector.restoreCallingIdentity(ident);
3884         }
3885     }
3886 
onFgsTimeout(ServiceRecord sr)3887     void onFgsTimeout(ServiceRecord sr) {
3888         synchronized (mAm) {
3889             final int fgsType = getTimeLimitedFgsType(sr.foregroundServiceType);
3890             if (fgsType == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE || sr.app == null) {
3891                 mAm.mHandler.removeMessages(
3892                                 ActivityManagerService.SERVICE_FGS_CRASH_TIMEOUT_MSG, sr);
3893                 return;
3894             }
3895 
3896             final boolean currentlyTop = sr.app.mState.getCurProcState() <= PROCESS_STATE_TOP;
3897             final long nowUptime = SystemClock.uptimeMillis();
3898             final long lastTopTime = currentlyTop ? nowUptime : sr.app.mState.getLastTopTime();
3899             final long constantTimeLimit = getTimeLimitForFgsType(fgsType);
3900             if (lastTopTime != Long.MIN_VALUE && constantTimeLimit > (nowUptime - lastTopTime)) {
3901                 // Discard any other messages for this service
3902                 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
3903                 mAm.mHandler.removeMessages(
3904                                 ActivityManagerService.SERVICE_FGS_CRASH_TIMEOUT_MSG, sr);
3905                 // The app was in the TOP state after the FGS was started so its time allowance
3906                 // should be counted from that time since this is considered a user interaction
3907                 final Message msg = mAm.mHandler.obtainMessage(
3908                                         ActivityManagerService.SERVICE_FGS_TIMEOUT_MSG, sr);
3909                 mAm.mHandler.sendMessageAtTime(msg, lastTopTime + constantTimeLimit);
3910                 return;
3911             }
3912 
3913             Slog.e(TAG_SERVICE, "FGS (" + ServiceInfo.foregroundServiceTypeToLabel(fgsType)
3914                     + ") timed out: " + sr);
3915             traceInstant("FGS timed out: ", sr);
3916 
3917             final TimeLimitedFgsInfo fgsTypeInfo = getFgsTimeLimitedInfo(sr.appInfo.uid, fgsType);
3918             if (fgsTypeInfo != null) {
3919                 // Update total runtime for the time-limited fgs type and mark it as timed out.
3920                 fgsTypeInfo.updateTotalRuntime(nowUptime);
3921                 fgsTypeInfo.setTimeLimitExceededAt(nowUptime);
3922 
3923                 logFGSStateChangeLocked(sr,
3924                         FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT,
3925                         nowUptime > fgsTypeInfo.getFirstFgsStartUptime()
3926                                 ? (int) (nowUptime - fgsTypeInfo.getFirstFgsStartUptime()) : 0,
3927                         FGS_STOP_REASON_UNKNOWN,
3928                         FGS_TYPE_POLICY_CHECK_UNKNOWN,
3929                         FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
3930                         false /* fgsRestrictionRecalculated */
3931                 );
3932             }
3933 
3934             try {
3935                 sr.app.getThread().scheduleTimeoutServiceForType(sr, sr.getLastStartId(), fgsType);
3936             } catch (RemoteException e) {
3937                 Slog.w(TAG_SERVICE, "Exception from scheduleTimeoutServiceForType: " + e);
3938             }
3939 
3940             // Crash the service after giving the service some time to clean up.
3941             final Message msg = mAm.mHandler.obtainMessage(
3942                                     ActivityManagerService.SERVICE_FGS_CRASH_TIMEOUT_MSG, sr);
3943             mAm.mHandler.sendMessageDelayed(msg, mAm.mConstants.mFgsCrashExtraWaitDuration);
3944         }
3945     }
3946 
onFgsCrashTimeout(ServiceRecord sr)3947     void onFgsCrashTimeout(ServiceRecord sr) {
3948         final int fgsType = getTimeLimitedFgsType(sr.foregroundServiceType);
3949         if (fgsType == ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE) {
3950             return; // no timed out FGS type was found (either it was stopped or it switched types)
3951         }
3952 
3953         synchronized (mAm) {
3954             final TimeLimitedFgsInfo fgsTypeInfo = getFgsTimeLimitedInfo(sr.appInfo.uid, fgsType);
3955             if (fgsTypeInfo != null) {
3956                 // Runtime is already updated when the service times out - if the app didn't
3957                 // stop the service, decrement the number of parallel running services here.
3958                 fgsTypeInfo.decNumParallelServices();
3959             }
3960 
3961             final String reason = "A foreground service of type "
3962                     + ServiceInfo.foregroundServiceTypeToLabel(fgsType)
3963                     + " did not stop within its timeout: " + sr.getComponentName();
3964             if (android.app.Flags.enableFgsTimeoutCrashBehavior()) {
3965                 // Crash the app
3966                 Slog.e(TAG_SERVICE, "FGS Crashed: " + sr);
3967                 traceInstant("FGS Crash: ", sr);
3968                 if (sr.app != null) {
3969                     mAm.crashApplicationWithTypeWithExtras(sr.app.uid, sr.app.getPid(),
3970                             sr.app.info.packageName, sr.app.userId, reason, false /*force*/,
3971                             ForegroundServiceDidNotStopInTimeException.TYPE_ID,
3972                             ForegroundServiceDidNotStopInTimeException
3973                                     .createExtrasForService(sr.getComponentName()));
3974                 }
3975             } else {
3976                 // Log a WTF instead of crashing the app while the new behavior is gated.
3977                 Slog.wtf(TAG, reason);
3978             }
3979         }
3980     }
3981 
updateAllowlistManagerLocked(ProcessServiceRecord psr)3982     private void updateAllowlistManagerLocked(ProcessServiceRecord psr) {
3983         psr.mAllowlistManager = false;
3984         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
3985             ServiceRecord sr = psr.getRunningServiceAt(i);
3986             if (sr.allowlistManager) {
3987                 psr.mAllowlistManager = true;
3988                 break;
3989             }
3990         }
3991     }
3992 
stopServiceAndUpdateAllowlistManagerLocked(ServiceRecord service)3993     private void stopServiceAndUpdateAllowlistManagerLocked(ServiceRecord service) {
3994         maybeStopShortFgsTimeoutLocked(service);
3995         final ProcessServiceRecord psr = service.app.mServices;
3996         psr.stopService(service);
3997         psr.updateBoundClientUids();
3998         if (service.allowlistManager) {
3999             updateAllowlistManagerLocked(psr);
4000         }
4001     }
4002 
updateServiceConnectionActivitiesLocked(ProcessServiceRecord clientPsr)4003     void updateServiceConnectionActivitiesLocked(ProcessServiceRecord clientPsr) {
4004         ArraySet<ProcessRecord> updatedProcesses = null;
4005         for (int i = 0; i < clientPsr.numberOfConnections(); i++) {
4006             final ConnectionRecord conn = clientPsr.getConnectionAt(i);
4007             final ProcessRecord proc = conn.binding.service.app;
4008             if (proc == null || proc == clientPsr.mApp) {
4009                 continue;
4010             } else if (updatedProcesses == null) {
4011                 updatedProcesses = new ArraySet<>();
4012             } else if (updatedProcesses.contains(proc)) {
4013                 continue;
4014             }
4015             updatedProcesses.add(proc);
4016             updateServiceClientActivitiesLocked(proc.mServices, null, false);
4017         }
4018     }
4019 
updateServiceClientActivitiesLocked(ProcessServiceRecord psr, ConnectionRecord modCr, boolean updateLru)4020     private boolean updateServiceClientActivitiesLocked(ProcessServiceRecord psr,
4021             ConnectionRecord modCr, boolean updateLru) {
4022         if (modCr != null && modCr.binding.client != null) {
4023             if (!modCr.binding.client.hasActivities()) {
4024                 // This connection is from a client without activities, so adding
4025                 // and removing is not interesting.
4026                 return false;
4027             }
4028         }
4029 
4030         boolean anyClientActivities = false;
4031         for (int i = psr.numberOfRunningServices() - 1; i >= 0 && !anyClientActivities; i--) {
4032             ServiceRecord sr = psr.getRunningServiceAt(i);
4033             ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = sr.getConnections();
4034             for (int conni = connections.size() - 1; conni >= 0 && !anyClientActivities; conni--) {
4035                 ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
4036                 for (int cri=clist.size()-1; cri>=0; cri--) {
4037                     ConnectionRecord cr = clist.get(cri);
4038                     if (cr.binding.client == null || cr.binding.client == psr.mApp) {
4039                         // Binding to ourself is not interesting.
4040                         continue;
4041                     }
4042                     if (cr.binding.client.hasActivities()) {
4043                         anyClientActivities = true;
4044                         break;
4045                     }
4046                 }
4047             }
4048         }
4049         if (anyClientActivities != psr.hasClientActivities()) {
4050             psr.setHasClientActivities(anyClientActivities);
4051             if (updateLru) {
4052                 mAm.updateLruProcessLocked(psr.mApp, anyClientActivities, null);
4053             }
4054             return true;
4055         }
4056         return false;
4057     }
4058 
bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType, final IServiceConnection connection, long flags, String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, IApplicationThread sdkSandboxClientApplicationThread, String callingPackage, final int userId)4059     int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
4060             String resolvedType, final IServiceConnection connection, long flags,
4061             String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid,
4062             String sdkSandboxClientAppPackage, IApplicationThread sdkSandboxClientApplicationThread,
4063             String callingPackage, final int userId)
4064             throws TransactionTooLargeException {
4065         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
4066                 + " type=" + resolvedType + " conn=" + connection.asBinder()
4067                 + " flags=0x" + Long.toHexString(flags));
4068         final int callingPid = mAm.mInjector.getCallingPid();
4069         final int callingUid = mAm.mInjector.getCallingUid();
4070         final ProcessRecord callerApp = mAm.getRecordForAppLOSP(caller);
4071         if (callerApp == null) {
4072             throw new SecurityException(
4073                     "Unable to find app for caller " + caller
4074                     + " (pid=" + callingPid
4075                     + ") when binding service " + service);
4076         }
4077 
4078         ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
4079         if (token != null) {
4080             activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
4081             if (activity == null) {
4082                 Slog.w(TAG, "Binding with unknown activity: " + token);
4083                 return 0;
4084             }
4085         }
4086 
4087         int clientLabel = 0;
4088         PendingIntent clientIntent = null;
4089         final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
4090 
4091         if (isCallerSystem) {
4092             // Hacky kind of thing -- allow system stuff to tell us
4093             // what they are, so we can report this elsewhere for
4094             // others to know why certain services are running.
4095             service.setDefusable(true);
4096             clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
4097             if (clientIntent != null) {
4098                 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
4099                 if (clientLabel != 0) {
4100                     // There are no useful extras in the intent, trash them.
4101                     // System code calling with this stuff just needs to know
4102                     // this will happen.
4103                     service = service.cloneFilter();
4104                 }
4105             }
4106         }
4107 
4108         if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
4109             mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_TASKS,
4110                     "BIND_TREAT_LIKE_ACTIVITY");
4111         }
4112 
4113         if ((flags & Context.BIND_SCHEDULE_LIKE_TOP_APP) != 0 && !isCallerSystem) {
4114             throw new SecurityException("Non-system caller (pid=" + callingPid
4115                     + ") set BIND_SCHEDULE_LIKE_TOP_APP when binding service " + service);
4116         }
4117 
4118         if ((flags & BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
4119             throw new SecurityException(
4120                     "Non-system caller " + caller + " (pid=" + callingPid
4121                     + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
4122         }
4123 
4124         if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
4125             throw new SecurityException(
4126                     "Non-system caller " + caller + " (pid=" + callingPid
4127                             + ") set BIND_ALLOW_INSTANT when binding service " + service);
4128         }
4129 
4130         if ((flags & Context.BIND_ALMOST_PERCEPTIBLE) != 0 && !isCallerSystem) {
4131             throw new SecurityException("Non-system caller (pid=" + callingPid
4132                     + ") set BIND_ALMOST_PERCEPTIBLE when binding service " + service);
4133         }
4134 
4135         if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
4136             mAm.enforceCallingPermission(
4137                     android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
4138                     "BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS");
4139         }
4140 
4141         if ((flags & Context.BIND_ALLOW_FOREGROUND_SERVICE_STARTS_FROM_BACKGROUND) != 0) {
4142             mAm.enforceCallingPermission(
4143                     android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND,
4144                     "BIND_ALLOW_FOREGROUND_SERVICE_STARTS_FROM_BACKGROUND");
4145         }
4146 
4147         final boolean callerFg = callerApp.mState.getSetSchedGroup()
4148                 != ProcessList.SCHED_GROUP_BACKGROUND;
4149         final boolean isBindExternal =
4150                 (flags & Integer.toUnsignedLong(Context.BIND_EXTERNAL_SERVICE)) != 0
4151                 || (flags & Context.BIND_EXTERNAL_SERVICE_LONG) != 0;
4152         final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
4153         final boolean inSharedIsolatedProcess = (flags & Context.BIND_SHARED_ISOLATED_PROCESS) != 0;
4154         final boolean inPrivateSharedIsolatedProcess =
4155                 ((flags & Context.BIND_PACKAGE_ISOLATED_PROCESS) != 0)
4156                         && enableBindPackageIsolatedProcess();
4157         final boolean matchQuarantined =
4158                 (flags & Context.BIND_MATCH_QUARANTINED_COMPONENTS) != 0;
4159 
4160         ProcessRecord attributedApp = null;
4161         if (sdkSandboxClientAppUid > 0) {
4162             attributedApp = mAm.getRecordForAppLOSP(sdkSandboxClientApplicationThread);
4163         }
4164         ServiceLookupResult res = retrieveServiceLocked(service, instanceName,
4165                 isSdkSandboxService, sdkSandboxClientAppUid, sdkSandboxClientAppPackage,
4166                 resolvedType, callingPackage, callingPid, callingUid, userId, true, callerFg,
4167                 isBindExternal, allowInstant, null /* fgsDelegateOptions */,
4168                 inSharedIsolatedProcess, inPrivateSharedIsolatedProcess, matchQuarantined);
4169         if (res == null) {
4170             return 0;
4171         }
4172         if (res.record == null) {
4173             return -1;
4174         }
4175         ServiceRecord s = res.record;
4176         final AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp, attributedApp);
4177         final ProcessServiceRecord clientPsr = b.client.mServices;
4178         if (clientPsr.numberOfConnections() >= mAm.mConstants.mMaxServiceConnectionsPerProcess) {
4179             Slog.w(TAG, "bindService exceeded max service connection number per process, "
4180                     + "callerApp:" + callerApp.processName
4181                     + " intent:" + service);
4182             return 0;
4183         }
4184 
4185         final ProcessRecord callingApp;
4186         synchronized (mAm.mPidsSelfLocked) {
4187             callingApp = mAm.mPidsSelfLocked.get(callingPid);
4188         }
4189         final String callingProcessName = callingApp != null
4190                 ? callingApp.processName : callingPackage;
4191         final int callingProcessState =
4192                 callingApp != null && callingApp.getThread() != null && !callingApp.isKilled()
4193                 ? callingApp.mState.getCurProcState() : ActivityManager.PROCESS_STATE_UNKNOWN;
4194         s.updateProcessStateOnRequest();
4195 
4196         // The package could be frozen (meaning it's doing surgery), defer the actual
4197         // binding until the package is unfrozen.
4198         boolean packageFrozen = deferServiceBringupIfFrozenLocked(s, service, callingPackage, null,
4199                 callingUid, callingPid, callingProcessName, callingProcessState,
4200                 false, callerFg, userId, BackgroundStartPrivileges.NONE, true, connection);
4201 
4202         // If permissions need a review before any of the app components can run,
4203         // we schedule binding to the service but do not start its process, then
4204         // we launch a review activity to which is passed a callback to invoke
4205         // when done to start the bound service's process to completing the binding.
4206         boolean permissionsReviewRequired = !packageFrozen
4207                 && !requestStartTargetPermissionsReviewIfNeededLocked(s, callingPackage, null,
4208                         callingUid, service, callerFg, userId, true, connection);
4209 
4210         final long origId = mAm.mInjector.clearCallingIdentity();
4211 
4212         try {
4213             if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
4214                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
4215                         + s);
4216             }
4217 
4218             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
4219                 s.lastActivity = SystemClock.uptimeMillis();
4220                 if (!s.hasAutoCreateConnections()) {
4221                     // This is the first binding, let the tracker know.
4222                     synchronized (mAm.mProcessStats.mLock) {
4223                         final ServiceState stracker = s.getTracker();
4224                         if (stracker != null) {
4225                             stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
4226                                     SystemClock.uptimeMillis());
4227                         }
4228                     }
4229                 }
4230             }
4231 
4232             if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
4233                 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
4234             }
4235 
4236             final boolean wasStartRequested = s.startRequested;
4237             final boolean hadConnections = !s.getConnections().isEmpty();
4238             mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
4239                     callerApp.mState.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
4240                     s.instanceName, s.processName);
4241             // Once the apps have become associated, if one of them is caller is ephemeral
4242             // the target app should now be able to see the calling app
4243             mAm.grantImplicitAccess(callerApp.userId, service,
4244                     callerApp.uid, UserHandle.getAppId(s.appInfo.uid));
4245 
4246             ConnectionRecord c = new ConnectionRecord(b, activity,
4247                     connection, flags, clientLabel, clientIntent,
4248                     callerApp.uid, callerApp.processName, callingPackage, res.aliasComponent);
4249 
4250             IBinder binder = connection.asBinder();
4251             s.addConnection(binder, c);
4252             b.connections.add(c);
4253             if (activity != null) {
4254                 activity.addConnection(c);
4255             }
4256             clientPsr.addConnection(c);
4257             c.startAssociationIfNeeded();
4258             // Don't set hasAboveClient if binding to self to prevent modifyRawOomAdj() from
4259             // dropping the process' adjustment level.
4260             if (b.client != s.app && c.hasFlag(Context.BIND_ABOVE_CLIENT)) {
4261                 clientPsr.setHasAboveClient(true);
4262             }
4263             if (c.hasFlag(BIND_ALLOW_WHITELIST_MANAGEMENT)) {
4264                 s.allowlistManager = true;
4265             }
4266             if (c.hasFlag(Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS)) {
4267                 s.setAllowedBgActivityStartsByBinding(true);
4268             }
4269 
4270             if (c.hasFlag(Context.BIND_NOT_APP_COMPONENT_USAGE)) {
4271                 s.isNotAppComponentUsage = true;
4272             }
4273 
4274             if (s.app != null && s.app.mState != null
4275                     && s.app.mState.getCurProcState() <= PROCESS_STATE_TOP
4276                     && c.hasFlag(Context.BIND_ALMOST_PERCEPTIBLE)) {
4277                 s.lastTopAlmostPerceptibleBindRequestUptimeMs = SystemClock.uptimeMillis();
4278             }
4279 
4280             if (s.app != null) {
4281                 updateServiceClientActivitiesLocked(s.app.mServices, c, true);
4282             }
4283             ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
4284             if (clist == null) {
4285                 clist = new ArrayList<>();
4286                 mServiceConnections.put(binder, clist);
4287             }
4288             clist.add(c);
4289 
4290             final boolean isolated = (s.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
4291             final ProcessRecord hostApp = isolated
4292                     ? null
4293                     : mAm.getProcessRecordLocked(s.processName, s.appInfo.uid);
4294             final int serviceBindingOomAdjPolicy = hostApp != null
4295                     ? getServiceBindingOomAdjPolicyForAddLocked(b.client, hostApp, c)
4296                     : SERVICE_BIND_OOMADJ_POLICY_LEGACY;
4297 
4298             final boolean shouldFreezeCaller = !packageFrozen && !permissionsReviewRequired
4299                     && (serviceBindingOomAdjPolicy & SERVICE_BIND_OOMADJ_POLICY_FREEZE_CALLER) != 0
4300                     && callerApp.isFreezable();
4301 
4302             if (shouldFreezeCaller) {
4303                 // Freeze the caller immediately, so the following #onBind/#onConnected will be
4304                 // queued up in the app side as they're one way calls. And we'll also hold off
4305                 // the service timeout timer until the process is unfrozen.
4306                 mAm.mOomAdjuster.updateAppFreezeStateLSP(callerApp, OOM_ADJ_REASON_BIND_SERVICE,
4307                         true);
4308             }
4309 
4310             final boolean wasStopped = hostApp == null ? wasStopped(s) : false;
4311             final boolean firstLaunch =
4312                     hostApp == null ? !mAm.wasPackageEverLaunched(s.packageName, s.userId) : false;
4313 
4314             boolean needOomAdj = false;
4315             if (c.hasFlag(Context.BIND_AUTO_CREATE)) {
4316                 s.lastActivity = SystemClock.uptimeMillis();
4317                 needOomAdj = (serviceBindingOomAdjPolicy
4318                         & SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CREATE) == 0;
4319                 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
4320                         permissionsReviewRequired, packageFrozen, true, serviceBindingOomAdjPolicy)
4321                         != null) {
4322                     mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_BIND_SERVICE);
4323                     return 0;
4324                 }
4325             }
4326             setFgsRestrictionLocked(callingPackage, callingPid, callingUid, service, s, userId,
4327                     BackgroundStartPrivileges.NONE, true /* isBindService */);
4328 
4329             if (s.app != null) {
4330                 ProcessServiceRecord servicePsr = s.app.mServices;
4331                 if (c.hasFlag(Context.BIND_TREAT_LIKE_ACTIVITY)) {
4332                     servicePsr.setTreatLikeActivity(true);
4333                 }
4334                 if (s.allowlistManager) {
4335                     servicePsr.mAllowlistManager = true;
4336                 }
4337                 // This could have made the service more important.
4338                 mAm.updateLruProcessLocked(s.app, (callerApp.hasActivitiesOrRecentTasks()
4339                             && servicePsr.hasClientActivities())
4340                         || (callerApp.mState.getCurProcState() <= PROCESS_STATE_TOP
4341                             && c.hasFlag(Context.BIND_TREAT_LIKE_ACTIVITY)),
4342                         b.client);
4343                 if (!s.wasOomAdjUpdated() && (serviceBindingOomAdjPolicy
4344                         & SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT) == 0) {
4345                     needOomAdj = true;
4346                     mAm.enqueueOomAdjTargetLocked(s.app);
4347                 }
4348             }
4349             if (needOomAdj) {
4350                 mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_BIND_SERVICE);
4351             }
4352 
4353             final int packageState = wasStopped
4354                     ? SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_STOPPED
4355                     : SERVICE_REQUEST_EVENT_REPORTED__PACKAGE_STOPPED_STATE__PACKAGE_STATE_NORMAL;
4356             if (DEBUG_PROCESSES) {
4357                 Slog.d(TAG, "Logging bindService for " + s.packageName
4358                         + ", stopped=" + wasStopped + ", firstLaunch=" + firstLaunch);
4359             }
4360             FrameworkStatsLog.write(SERVICE_REQUEST_EVENT_REPORTED, s.appInfo.uid, callingUid,
4361                     ActivityManagerService.getShortAction(service.getAction()),
4362                     SERVICE_REQUEST_EVENT_REPORTED__REQUEST_TYPE__BIND, false,
4363                     s.app == null || s.app.getThread() == null
4364                     ? SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_COLD
4365                     : (wasStartRequested || hadConnections
4366                     ? SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_HOT
4367                     : SERVICE_REQUEST_EVENT_REPORTED__PROC_START_TYPE__PROCESS_START_TYPE_WARM),
4368                     getShortProcessNameForStats(callingUid, callerApp.processName),
4369                     getShortServiceNameForStats(s),
4370                     packageState,
4371                     s.packageName,
4372                     callerApp.info.packageName,
4373                     callerApp.mState.getCurProcState(),
4374                     s.mProcessStateOnRequest,
4375                     firstLaunch,
4376                     0L /* TODO */);
4377 
4378             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
4379                     + ": received=" + b.intent.received
4380                     + " apps=" + b.intent.apps.size()
4381                     + " doRebind=" + b.intent.doRebind);
4382 
4383             if (s.app != null && b.intent.received) {
4384                 // Service is already running, so we can immediately
4385                 // publish the connection.
4386 
4387                 // If what the client try to start/connect was an alias, then we need to
4388                 // pass the alias component name instead to the client.
4389                 final ComponentName clientSideComponentName =
4390                         res.aliasComponent != null ? res.aliasComponent : s.name;
4391                 try {
4392                     c.conn.connected(clientSideComponentName, b.intent.binder, false);
4393                 } catch (Exception e) {
4394                     Slog.w(TAG, "Failure sending service " + s.shortInstanceName
4395                             + " to connection " + c.conn.asBinder()
4396                             + " (in " + c.binding.client.processName + ")", e);
4397                 }
4398 
4399                 // If this is the first app connected back to this binding,
4400                 // and the service had previously asked to be told when
4401                 // rebound, then do so.
4402                 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
4403                     requestServiceBindingLocked(s, b.intent, callerFg, true,
4404                             serviceBindingOomAdjPolicy);
4405                 }
4406             } else if (!b.intent.requested) {
4407                 requestServiceBindingLocked(s, b.intent, callerFg, false,
4408                         serviceBindingOomAdjPolicy);
4409             }
4410 
4411             maybeLogBindCrossProfileService(userId, callingPackage, callerApp.info.uid);
4412 
4413             getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
4414 
4415         } finally {
4416             mAm.mInjector.restoreCallingIdentity(origId);
4417         }
4418 
4419         notifyBindingServiceEventLocked(callerApp, callingPackage);
4420 
4421         return 1;
4422     }
4423 
4424     @GuardedBy("mAm")
notifyBindingServiceEventLocked(ProcessRecord callerApp, String callingPackage)4425     private void notifyBindingServiceEventLocked(ProcessRecord callerApp, String callingPackage) {
4426         final ApplicationInfo ai = callerApp.info;
4427         final String callerPackage = ai != null ? ai.packageName : callingPackage;
4428         if (callerPackage != null) {
4429             mAm.mHandler.obtainMessage(ActivityManagerService.DISPATCH_BINDING_SERVICE_EVENT,
4430                     callerApp.uid, 0, callerPackage).sendToTarget();
4431         }
4432     }
4433 
maybeLogBindCrossProfileService( int userId, String callingPackage, int callingUid)4434     private void maybeLogBindCrossProfileService(
4435             int userId, String callingPackage, int callingUid) {
4436         if (UserHandle.isCore(callingUid)) {
4437             return;
4438         }
4439         final int callingUserId = UserHandle.getUserId(callingUid);
4440         if (callingUserId == userId
4441                 || !mAm.mUserController.isSameProfileGroup(callingUserId, userId)) {
4442             return;
4443         }
4444         DevicePolicyEventLogger.createEvent(DevicePolicyEnums.BIND_CROSS_PROFILE_SERVICE)
4445                 .setStrings(callingPackage)
4446                 .write();
4447     }
4448 
publishServiceLocked(ServiceRecord r, Intent intent, IBinder service)4449     void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
4450         final long origId = mAm.mInjector.clearCallingIdentity();
4451         try {
4452             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
4453                     + " " + intent + ": " + service);
4454             if (r != null) {
4455                 Intent.FilterComparison filter
4456                         = new Intent.FilterComparison(intent);
4457                 IntentBindRecord b = r.bindings.get(filter);
4458                 if (b != null && !b.received) {
4459                     b.binder = service;
4460                     b.requested = true;
4461                     b.received = true;
4462                     ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4463                     for (int conni = connections.size() - 1; conni >= 0; conni--) {
4464                         ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
4465                         for (int i=0; i<clist.size(); i++) {
4466                             ConnectionRecord c = clist.get(i);
4467                             if (!filter.equals(c.binding.intent.intent)) {
4468                                 if (DEBUG_SERVICE) Slog.v(
4469                                         TAG_SERVICE, "Not publishing to: " + c);
4470                                 if (DEBUG_SERVICE) Slog.v(
4471                                         TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
4472                                 if (DEBUG_SERVICE) Slog.v(
4473                                         TAG_SERVICE, "Published intent: " + intent);
4474                                 continue;
4475                             }
4476                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
4477                             // If what the client try to start/connect was an alias, then we need to
4478                             // pass the alias component name instead to the client.
4479                             final ComponentName clientSideComponentName =
4480                                     c.aliasComponent != null ? c.aliasComponent : r.name;
4481                             try {
4482                                 c.conn.connected(clientSideComponentName, service, false);
4483                             } catch (Exception e) {
4484                                 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
4485                                       + " to connection " + c.conn.asBinder()
4486                                       + " (in " + c.binding.client.processName + ")", e);
4487                             }
4488                         }
4489                     }
4490                 }
4491 
4492                 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false, false,
4493                         !Flags.serviceBindingOomAdjPolicy() || r.wasOomAdjUpdated()
4494                         ? OOM_ADJ_REASON_EXECUTING_SERVICE : OOM_ADJ_REASON_NONE);
4495             }
4496         } finally {
4497             mAm.mInjector.restoreCallingIdentity(origId);
4498         }
4499     }
4500 
updateServiceGroupLocked(IServiceConnection connection, int group, int importance)4501     void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
4502         final IBinder binder = connection.asBinder();
4503         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
4504         final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
4505         if (clist == null) {
4506             throw new IllegalArgumentException("Could not find connection for "
4507                     + connection.asBinder());
4508         }
4509         for (int i = clist.size() - 1; i >= 0; i--) {
4510             final ConnectionRecord crec = clist.get(i);
4511             final ServiceRecord srec = crec.binding.service;
4512             if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
4513                 if (srec.app != null) {
4514                     final ProcessServiceRecord psr = srec.app.mServices;
4515                     if (group > 0) {
4516                         psr.setConnectionService(srec);
4517                         psr.setConnectionGroup(group);
4518                         psr.setConnectionImportance(importance);
4519                     } else {
4520                         psr.setConnectionService(null);
4521                         psr.setConnectionGroup(0);
4522                         psr.setConnectionImportance(0);
4523                     }
4524                 } else {
4525                     if (group > 0) {
4526                         srec.pendingConnectionGroup = group;
4527                         srec.pendingConnectionImportance = importance;
4528                     } else {
4529                         srec.pendingConnectionGroup = 0;
4530                         srec.pendingConnectionImportance = 0;
4531                     }
4532                 }
4533             }
4534         }
4535     }
4536 
unbindServiceLocked(IServiceConnection connection)4537     boolean unbindServiceLocked(IServiceConnection connection) {
4538         IBinder binder = connection.asBinder();
4539         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
4540         ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
4541         if (clist == null) {
4542             Slog.w(TAG, "Unbind failed: could not find connection for "
4543                   + connection.asBinder());
4544             return false;
4545         }
4546 
4547         final int callingPid = mAm.mInjector.getCallingPid();
4548         final long origId = mAm.mInjector.clearCallingIdentity();
4549         try {
4550             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
4551                 String info;
4552                 if (clist.size() > 0) {
4553                     final ConnectionRecord r = clist.get(0);
4554                     info = r.binding.service.shortInstanceName + " from " + r.clientProcessName;
4555                 } else {
4556                     info = Integer.toString(callingPid);
4557                 }
4558                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "unbindServiceLocked: " + info);
4559             }
4560 
4561             boolean needOomAdj = false;
4562             while (clist.size() > 0) {
4563                 ConnectionRecord r = clist.get(0);
4564                 int serviceBindingOomAdjPolicy = removeConnectionLocked(r, null, null, true);
4565                 if (clist.size() > 0 && clist.get(0) == r) {
4566                     // In case it didn't get removed above, do it now.
4567                     Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
4568                     clist.remove(0);
4569                 }
4570 
4571                 final ProcessRecord app = r.binding.service.app;
4572                 if (app != null) {
4573                     final ProcessServiceRecord psr = app.mServices;
4574                     if (psr.mAllowlistManager) {
4575                         updateAllowlistManagerLocked(psr);
4576                     }
4577                     // This could have made the service less important.
4578                     if (r.hasFlag(Context.BIND_TREAT_LIKE_ACTIVITY)) {
4579                         psr.setTreatLikeActivity(true);
4580                         mAm.updateLruProcessLocked(app, true, null);
4581                     }
4582                     // If the bindee is more important than the binder, we may skip the OomAdjuster.
4583                     if (serviceBindingOomAdjPolicy == SERVICE_BIND_OOMADJ_POLICY_LEGACY) {
4584                         mAm.enqueueOomAdjTargetLocked(app);
4585                         needOomAdj = true;
4586                     }
4587                 }
4588             }
4589 
4590             if (needOomAdj) {
4591                 mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_UNBIND_SERVICE);
4592             }
4593 
4594         } finally {
4595             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
4596             mAm.mInjector.restoreCallingIdentity(origId);
4597         }
4598 
4599         return true;
4600     }
4601 
unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind)4602     void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
4603         final long origId = mAm.mInjector.clearCallingIdentity();
4604         try {
4605             if (r != null) {
4606                 Intent.FilterComparison filter
4607                         = new Intent.FilterComparison(intent);
4608                 IntentBindRecord b = r.bindings.get(filter);
4609                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
4610                         + " at " + b + ": apps="
4611                         + (b != null ? b.apps.size() : 0));
4612 
4613                 boolean inDestroying = mDestroyingServices.contains(r);
4614                 if (b != null) {
4615                     if (b.apps.size() > 0 && !inDestroying) {
4616                         // Applications have already bound since the last
4617                         // unbind, so just rebind right here.
4618                         boolean inFg = false;
4619                         for (int i=b.apps.size()-1; i>=0; i--) {
4620                             ProcessRecord client = b.apps.valueAt(i).client;
4621                             if (client != null && client.mState.getSetSchedGroup()
4622                                     != ProcessList.SCHED_GROUP_BACKGROUND) {
4623                                 inFg = true;
4624                                 break;
4625                             }
4626                         }
4627                         try {
4628                             requestServiceBindingLocked(r, b, inFg, true,
4629                                     SERVICE_BIND_OOMADJ_POLICY_LEGACY);
4630                         } catch (TransactionTooLargeException e) {
4631                             // Don't pass this back to ActivityThread, it's unrelated.
4632                         }
4633                     } else {
4634                         // Note to tell the service the next time there is
4635                         // a new client.
4636                         b.doRebind = true;
4637                     }
4638                 }
4639 
4640                 serviceDoneExecutingLocked(r, inDestroying, false, false,
4641                         !Flags.serviceBindingOomAdjPolicy() || r.wasOomAdjUpdated()
4642                         ? OOM_ADJ_REASON_UNBIND_SERVICE : OOM_ADJ_REASON_NONE);
4643             }
4644         } finally {
4645             mAm.mInjector.restoreCallingIdentity(origId);
4646         }
4647     }
4648 
findServiceLocked(ComponentName name, IBinder token, int userId)4649     private final ServiceRecord findServiceLocked(ComponentName name,
4650             IBinder token, int userId) {
4651         ServiceRecord r = getServiceByNameLocked(name, userId);
4652         return r == token ? r : null;
4653     }
4654 
4655     private final class ServiceLookupResult {
4656         final ServiceRecord record;
4657         final String permission;
4658 
4659         /**
4660          * Set only when we looked up to this service via an alias. Otherwise, it's null.
4661          */
4662         @Nullable
4663         final ComponentName aliasComponent;
4664 
ServiceLookupResult(ServiceRecord _record, ComponentName _aliasComponent)4665         ServiceLookupResult(ServiceRecord _record, ComponentName _aliasComponent) {
4666             record = _record;
4667             permission = null;
4668             aliasComponent = _aliasComponent;
4669         }
4670 
ServiceLookupResult(String _permission)4671         ServiceLookupResult(String _permission) {
4672             record = null;
4673             permission = _permission;
4674             aliasComponent = null;
4675         }
4676     }
4677 
4678     private class ServiceRestarter implements Runnable {
4679         private ServiceRecord mService;
4680 
setService(ServiceRecord service)4681         void setService(ServiceRecord service) {
4682             mService = service;
4683         }
4684 
run()4685         public void run() {
4686             synchronized (mAm) {
4687                 performServiceRestartLocked(mService);
4688             }
4689         }
4690     }
4691 
retrieveServiceLocked(Intent service, String instanceName, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, boolean allowInstant, boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess)4692     private ServiceLookupResult retrieveServiceLocked(Intent service,
4693             String instanceName, String resolvedType, String callingPackage, int callingPid,
4694             int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg,
4695             boolean isBindExternal, boolean allowInstant, boolean inSharedIsolatedProcess,
4696             boolean inPrivateSharedIsolatedProcess) {
4697         return retrieveServiceLocked(service, instanceName, false, INVALID_UID, null, resolvedType,
4698                 callingPackage, callingPid, callingUid, userId, createIfNeeded, callingFromFg,
4699                 isBindExternal, allowInstant, null /* fgsDelegateOptions */,
4700                 inSharedIsolatedProcess, inPrivateSharedIsolatedProcess);
4701     }
4702 
4703     // TODO(b/265746493): Special case for HotwordDetectionService,
4704     // VisualQueryDetectionService, WearableSensingService and OnDeviceSandboxedInferenceService
4705     // Need a cleaner way to append this seInfo.
generateAdditionalSeInfoFromService(Intent service)4706     private String generateAdditionalSeInfoFromService(Intent service) {
4707         if (service != null && service.getAction() != null
4708                 && (service.getAction().equals(HotwordDetectionService.SERVICE_INTERFACE)
4709                 || service.getAction().equals(VisualQueryDetectionService.SERVICE_INTERFACE)
4710                 || service.getAction().equals(WearableSensingService.SERVICE_INTERFACE)
4711             || service.getAction().equals(OnDeviceSandboxedInferenceService.SERVICE_INTERFACE))) {
4712             return ":isolatedComputeApp";
4713         }
4714         return "";
4715     }
4716 
retrieveServiceLocked(Intent service, String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, boolean allowInstant, ForegroundServiceDelegationOptions fgsDelegateOptions, boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess)4717     private ServiceLookupResult retrieveServiceLocked(Intent service,
4718             String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid,
4719             String sdkSandboxClientAppPackage, String resolvedType,
4720             String callingPackage, int callingPid, int callingUid, int userId,
4721             boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
4722             boolean allowInstant, ForegroundServiceDelegationOptions fgsDelegateOptions,
4723             boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess) {
4724         return retrieveServiceLocked(service, instanceName, isSdkSandboxService,
4725                 sdkSandboxClientAppUid, sdkSandboxClientAppPackage, resolvedType, callingPackage,
4726                 callingPid, callingUid, userId, createIfNeeded, callingFromFg, isBindExternal,
4727                 allowInstant, fgsDelegateOptions, inSharedIsolatedProcess,
4728                 inPrivateSharedIsolatedProcess, false /* matchQuarantined */);
4729     }
4730 
retrieveServiceLocked( Intent service, String instanceName, boolean isSdkSandboxService, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, boolean allowInstant, ForegroundServiceDelegationOptions fgsDelegateOptions, boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess, boolean matchQuarantined)4731     private ServiceLookupResult retrieveServiceLocked(
4732             Intent service, String instanceName, boolean isSdkSandboxService,
4733             int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, String resolvedType,
4734             String callingPackage, int callingPid, int callingUid, int userId,
4735             boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
4736             boolean allowInstant, ForegroundServiceDelegationOptions fgsDelegateOptions,
4737             boolean inSharedIsolatedProcess, boolean inPrivateSharedIsolatedProcess,
4738             boolean matchQuarantined) {
4739         if (isSdkSandboxService && instanceName == null) {
4740             throw new IllegalArgumentException("No instanceName provided for sdk sandbox process");
4741         }
4742 
4743         ServiceRecord r = null;
4744         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
4745                 + " type=" + resolvedType + " callingUid=" + callingUid);
4746 
4747         userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId,
4748                 /* allowAll= */false, getAllowMode(service, callingPackage),
4749                 /* name= */ "service", callingPackage);
4750 
4751         ServiceMap smap = getServiceMapLocked(userId);
4752 
4753         // See if the intent refers to an alias. If so, update the intent with the target component
4754         // name. `resolution` will contain the alias component name, which we need to return
4755         // to the client.
4756         final ComponentAliasResolver.Resolution<ComponentName> resolution =
4757                 mAm.mComponentAliasResolver.resolveService(service, resolvedType,
4758                         /* match flags */ 0, userId, callingUid);
4759 
4760         final ComponentName comp;
4761         if (instanceName == null) {
4762             comp = service.getComponent();
4763         } else {
4764             final ComponentName realComp = service.getComponent();
4765             if (realComp == null) {
4766                 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
4767                         + "' without expicit component in Intent");
4768             }
4769             comp = new ComponentName(realComp.getPackageName(),
4770                     realComp.getClassName() + ":" + instanceName);
4771         }
4772 
4773         if (comp != null) {
4774             r = smap.mServicesByInstanceName.get(comp);
4775             if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
4776         }
4777         if (r == null && !isBindExternal && instanceName == null) {
4778             Intent.FilterComparison filter = new Intent.FilterComparison(service);
4779             r = smap.mServicesByIntent.get(filter);
4780             if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
4781         }
4782         if (r != null) {
4783             // Compared to resolveService below, the ServiceRecord here is retrieved from
4784             // ServiceMap so the package visibility doesn't apply to it. We need to filter it.
4785             if (mAm.getPackageManagerInternal().filterAppAccess(r.packageName, callingUid,
4786                     userId)) {
4787                 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId
4788                         + ": not found");
4789                 return null;
4790             }
4791             if ((r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
4792                     && !callingPackage.equals(r.packageName)) {
4793                 // If an external service is running within its own package, other packages
4794                 // should not bind to that instance.
4795                 r = null;
4796                 if (DEBUG_SERVICE) {
4797                     Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
4798                 }
4799             }
4800         }
4801 
4802         if (r == null && fgsDelegateOptions != null) {
4803             // Create a ServiceRecord for FGS delegate.
4804             final ServiceInfo sInfo = new ServiceInfo();
4805             ApplicationInfo aInfo = null;
4806             try {
4807                 aInfo = AppGlobals.getPackageManager().getApplicationInfo(
4808                         fgsDelegateOptions.mClientPackageName,
4809                         ActivityManagerService.STOCK_PM_FLAGS,
4810                         userId);
4811             } catch (RemoteException ex) {
4812             // pm is in same process, this will never happen.
4813             }
4814             if (aInfo == null) {
4815                 throw new SecurityException("startForegroundServiceDelegate failed, "
4816                         + "could not resolve client package " + callingPackage);
4817             }
4818             if (aInfo.uid != fgsDelegateOptions.mClientUid) {
4819                 throw new SecurityException("startForegroundServiceDelegate failed, "
4820                         + "uid:" + aInfo.uid
4821                         + " does not match clientUid:" + fgsDelegateOptions.mClientUid);
4822             }
4823             sInfo.applicationInfo = aInfo;
4824             sInfo.packageName = aInfo.packageName;
4825             sInfo.mForegroundServiceType = fgsDelegateOptions.mForegroundServiceTypes;
4826             sInfo.processName = aInfo.processName;
4827             final ComponentName cn = service.getComponent();
4828             sInfo.name = cn.getClassName();
4829             if (createIfNeeded) {
4830                 final Intent.FilterComparison filter =
4831                         new Intent.FilterComparison(service.cloneFilter());
4832                 final ServiceRestarter res = new ServiceRestarter();
4833                 final String processName = getProcessNameForService(sInfo, cn, callingPackage,
4834                         null /* instanceName */, false /* isSdkSandbox */,
4835                         false /* inSharedIsolatedProcess */,
4836                         false /*inPrivateSharedIsolatedProcess*/);
4837                 r = new ServiceRecord(mAm, cn /* name */, cn /* instanceName */,
4838                         sInfo.applicationInfo.packageName, sInfo.applicationInfo.uid, filter, sInfo,
4839                         callingFromFg, res, processName,
4840                         INVALID_UID /* sdkSandboxClientAppUid */,
4841                         null /* sdkSandboxClientAppPackage */,
4842                         false /* inSharedIsolatedProcess */);
4843                 r.foregroundId = fgsDelegateOptions.mClientNotificationId;
4844                 r.foregroundNoti = fgsDelegateOptions.mClientNotification;
4845                 res.setService(r);
4846                 smap.mServicesByInstanceName.put(cn, r);
4847                 smap.mServicesByIntent.put(filter, r);
4848                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
4849                 r.mRecentCallingPackage = callingPackage;
4850                 r.mRecentCallingUid = callingUid;
4851             }
4852             r.appInfo.seInfo += generateAdditionalSeInfoFromService(service);
4853             return new ServiceLookupResult(r, resolution.getAlias());
4854         }
4855 
4856         if (r == null) {
4857             try {
4858                 long flags = ActivityManagerService.STOCK_PM_FLAGS
4859                         | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4860                 if (allowInstant) {
4861                     flags |= PackageManager.MATCH_INSTANT;
4862                 }
4863                 if (matchQuarantined) {
4864                     flags |= PackageManager.MATCH_QUARANTINED_COMPONENTS;
4865                 }
4866                 // TODO: come back and remove this assumption to triage all services
4867                 ResolveInfo rInfo = mAm.getPackageManagerInternal().resolveService(service,
4868                         resolvedType, flags, userId, callingUid, callingPid);
4869                 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
4870                 if (sInfo == null) {
4871                     Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
4872                           ": not found");
4873                     return null;
4874                 }
4875                 if (instanceName != null
4876                         && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0
4877                         && !isSdkSandboxService) {
4878                     throw new IllegalArgumentException("Can't use instance name '" + instanceName
4879                             + "' with non-isolated non-sdk sandbox service '" + sInfo.name + "'");
4880                 }
4881                 if (isSdkSandboxService
4882                         && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
4883                     throw new IllegalArgumentException("Service cannot be both sdk sandbox and "
4884                             + "isolated");
4885                 }
4886 
4887                 ComponentName className = new ComponentName(sInfo.applicationInfo.packageName,
4888                                                             sInfo.name);
4889                 ComponentName name = comp != null ? comp : className;
4890                 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
4891                         name.getPackageName(), sInfo.applicationInfo.uid)) {
4892                     String msg = "association not allowed between packages "
4893                             + callingPackage + " and " + name.getPackageName();
4894                     Slog.w(TAG, "Service lookup failed: " + msg);
4895                     return new ServiceLookupResult(msg);
4896                 }
4897 
4898                 // Store the defining packageName and uid, as they might be changed in
4899                 // the ApplicationInfo for external services (which run with the package name
4900                 // and uid of the caller).
4901                 String definingPackageName = sInfo.applicationInfo.packageName;
4902                 int definingUid = sInfo.applicationInfo.uid;
4903                 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
4904                     if (isBindExternal) {
4905                         if (!sInfo.exported) {
4906                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
4907                                     + className + " is not exported");
4908                         }
4909                         if (inPrivateSharedIsolatedProcess) {
4910                             throw new SecurityException("BIND_PACKAGE_ISOLATED_PROCESS cannot be "
4911                                     + "applied to an external service.");
4912                         }
4913                         if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
4914                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
4915                                     + className + " is not an isolatedProcess");
4916                         }
4917                         if (!mAm.getPackageManagerInternal().isSameApp(callingPackage, callingUid,
4918                                 userId)) {
4919                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
4920                                     + "calling package not owned by calling UID ");
4921                         }
4922                         // Run the service under the calling package's application.
4923                         ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
4924                                 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
4925                         if (aInfo == null) {
4926                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
4927                                     "could not resolve client package " + callingPackage);
4928                         }
4929                         sInfo = new ServiceInfo(sInfo);
4930                         sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
4931                         sInfo.applicationInfo.packageName = aInfo.packageName;
4932                         sInfo.applicationInfo.uid = aInfo.uid;
4933                         name = new ComponentName(aInfo.packageName, name.getClassName());
4934                         className = new ComponentName(aInfo.packageName,
4935                                 instanceName == null ? className.getClassName()
4936                                         : (className.getClassName() + ":" + instanceName));
4937                         service.setComponent(name);
4938                     } else {
4939                         throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
4940                                 name);
4941                     }
4942                 } else if (isBindExternal) {
4943                     throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
4944                             " is not an externalService");
4945                 }
4946                 if (inSharedIsolatedProcess && inPrivateSharedIsolatedProcess) {
4947                     throw new SecurityException("Either BIND_SHARED_ISOLATED_PROCESS or "
4948                             + "BIND_PACKAGE_ISOLATED_PROCESS should be set. Not both.");
4949                 }
4950                 if (inSharedIsolatedProcess || inPrivateSharedIsolatedProcess) {
4951                     if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
4952                         throw new SecurityException("BIND_SHARED_ISOLATED_PROCESS failed, "
4953                                 + className + " is not an isolatedProcess");
4954                     }
4955                 }
4956                 if (inPrivateSharedIsolatedProcess && isDefaultProcessService(sInfo)) {
4957                     throw new SecurityException("BIND_PACKAGE_ISOLATED_PROCESS cannot be used for "
4958                             + "services running in the main app process.");
4959                 }
4960                 if (inSharedIsolatedProcess) {
4961                     if (instanceName == null) {
4962                         throw new IllegalArgumentException("instanceName must be provided for "
4963                                 + "binding a service into a shared isolated process.");
4964                     }
4965                     if ((sInfo.flags & ServiceInfo.FLAG_ALLOW_SHARED_ISOLATED_PROCESS) == 0) {
4966                         throw new SecurityException("BIND_SHARED_ISOLATED_PROCESS failed, "
4967                                 + className + " has not set the allowSharedIsolatedProcess "
4968                                 + " attribute.");
4969                     }
4970                 }
4971                 if (userId > 0) {
4972                     if (mAm.isSystemUserOnly(sInfo.flags)) {
4973                         Slog.w(TAG_SERVICE, service + " is only available for the SYSTEM user,"
4974                                 + " calling userId is: " + userId);
4975                         return null;
4976                     }
4977 
4978                     if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
4979                             sInfo.name, sInfo.flags)
4980                             && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
4981                         userId = 0;
4982                         smap = getServiceMapLocked(0);
4983                         // Bypass INTERACT_ACROSS_USERS permission check
4984                         final long token = mAm.mInjector.clearCallingIdentity();
4985                         try {
4986                             ResolveInfo rInfoForUserId0 =
4987                                     mAm.getPackageManagerInternal().resolveService(service,
4988                                             resolvedType, flags, userId, callingUid, callingPid);
4989                             if (rInfoForUserId0 == null) {
4990                                 Slog.w(TAG_SERVICE,
4991                                         "Unable to resolve service " + service + " U=" + userId
4992                                                 + ": not found");
4993                                 return null;
4994                             }
4995                             sInfo = rInfoForUserId0.serviceInfo;
4996                         } finally {
4997                             mAm.mInjector.restoreCallingIdentity(token);
4998                         }
4999                     }
5000                     sInfo = new ServiceInfo(sInfo);
5001                     sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
5002                 }
5003                 r = smap.mServicesByInstanceName.get(name);
5004                 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
5005                         "Retrieved via pm by intent: " + r);
5006                 if (r == null && createIfNeeded) {
5007                     final Intent.FilterComparison filter
5008                             = new Intent.FilterComparison(service.cloneFilter());
5009                     final ServiceRestarter res = new ServiceRestarter();
5010                     String processName = getProcessNameForService(sInfo, name, callingPackage,
5011                             instanceName, isSdkSandboxService, inSharedIsolatedProcess,
5012                             inPrivateSharedIsolatedProcess);
5013                     r = new ServiceRecord(mAm, className, name, definingPackageName,
5014                             definingUid, filter, sInfo, callingFromFg, res,
5015                             processName, sdkSandboxClientAppUid,
5016                             sdkSandboxClientAppPackage,
5017                             (inSharedIsolatedProcess || inPrivateSharedIsolatedProcess));
5018                     res.setService(r);
5019                     smap.mServicesByInstanceName.put(name, r);
5020                     smap.mServicesByIntent.put(filter, r);
5021 
5022                     // Make sure this component isn't in the pending list.
5023                     for (int i=mPendingServices.size()-1; i>=0; i--) {
5024                         final ServiceRecord pr = mPendingServices.get(i);
5025                         if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
5026                                 && pr.instanceName.equals(name)) {
5027                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
5028                             mPendingServices.remove(i);
5029                         }
5030                     }
5031                     for (int i = mPendingBringups.size() - 1; i >= 0; i--) {
5032                         final ServiceRecord pr = mPendingBringups.keyAt(i);
5033                         if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
5034                                 && pr.instanceName.equals(name)) {
5035                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending bringup: " + pr);
5036                             mPendingBringups.removeAt(i);
5037                         }
5038                     }
5039                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
5040                 }
5041             } catch (RemoteException ex) {
5042                 // pm is in same process, this will never happen.
5043             }
5044         }
5045         if (r != null) {
5046             r.mRecentCallingPackage = callingPackage;
5047             r.mRecentCallingUid = callingUid;
5048             try {
5049                 r.mRecentCallerApplicationInfo =
5050                         mAm.mContext.getPackageManager().getApplicationInfoAsUser(callingPackage,
5051                                 0, UserHandle.getUserId(callingUid));
5052             } catch (PackageManager.NameNotFoundException e) {
5053             }
5054             if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
5055                     r.appInfo.uid)) {
5056                 String msg = "association not allowed between packages "
5057                         + callingPackage + " and " + r.packageName;
5058                 Slog.w(TAG, "Service lookup failed: " + msg);
5059                 return new ServiceLookupResult(msg);
5060             }
5061             if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
5062                     resolvedType, r.appInfo)) {
5063                 return new ServiceLookupResult("blocked by firewall");
5064             }
5065             if (mAm.checkComponentPermission(r.permission,
5066                     callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
5067                 if (!r.exported) {
5068                     Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
5069                             + " from pid=" + callingPid
5070                             + ", uid=" + callingUid
5071                             + " that is not exported from uid " + r.appInfo.uid);
5072                     return new ServiceLookupResult("not exported from uid "
5073                             + r.appInfo.uid);
5074                 }
5075                 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
5076                         + " from pid=" + callingPid
5077                         + ", uid=" + callingUid
5078                         + " requires " + r.permission);
5079                 return new ServiceLookupResult(r.permission);
5080             } else if ((Manifest.permission.BIND_HOTWORD_DETECTION_SERVICE.equals(r.permission)
5081                     || Manifest.permission.BIND_VISUAL_QUERY_DETECTION_SERVICE.equals(r.permission))
5082                     && callingUid != Process.SYSTEM_UID) {
5083                 // Hotword detection and visual query detection must run in its own sandbox, and we
5084                 // don't even trust its enclosing application to bind to it - only the system.
5085                 // TODO(b/185746653) remove this special case and generalize
5086                 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
5087                         + " from pid=" + callingPid
5088                         + ", uid=" + callingUid
5089                         + " requiring permission " + r.permission
5090                         + " can only be bound to from the system.");
5091                 return new ServiceLookupResult("can only be bound to "
5092                         + "by the system.");
5093             } else if (r.permission != null && callingPackage != null) {
5094                 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
5095                 if (opCode != AppOpsManager.OP_NONE && mAm.getAppOpsManager().checkOpNoThrow(
5096                         opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
5097                     Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
5098                             + " from pid=" + callingPid
5099                             + ", uid=" + callingUid
5100                             + " requires appop " + AppOpsManager.opToName(opCode));
5101                     return null;
5102                 }
5103             }
5104             r.appInfo.seInfo += generateAdditionalSeInfoFromService(service);
5105             return new ServiceLookupResult(r, resolution.getAlias());
5106         }
5107         return null;
5108     }
5109 
getAllowMode(Intent service, @Nullable String callingPackage)5110     private int getAllowMode(Intent service, @Nullable String callingPackage) {
5111         if (callingPackage != null && service.getComponent() != null
5112                 && callingPackage.equals(service.getComponent().getPackageName())) {
5113             return ActivityManagerInternal.ALLOW_PROFILES_OR_NON_FULL;
5114         } else {
5115             return ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
5116         }
5117     }
5118 
5119     /**
5120      * Bump the given service record into executing state.
5121      * @param oomAdjReason The caller requests it to perform the oomAdjUpdate not {@link
5122      *         ActivityManagerInternal#OOM_ADJ_REASON_NONE}.
5123      */
bumpServiceExecutingLocked( ServiceRecord r, boolean fg, String why, @OomAdjReason int oomAdjReason, boolean skipTimeoutIfPossible)5124     private void bumpServiceExecutingLocked(
5125             ServiceRecord r, boolean fg, String why, @OomAdjReason int oomAdjReason,
5126             boolean skipTimeoutIfPossible) {
5127         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
5128                 + why + " of " + r + " in app " + r.app);
5129         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
5130                 + why + " of " + r.shortInstanceName);
5131 
5132         // For b/34123235: Services within the system server won't start until SystemServer
5133         // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
5134         // process. However, since there's a little point of showing the ANR dialog in that case,
5135         // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
5136         //
5137         // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
5138         // which technically could also trigger this timeout if there's a system server
5139         // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
5140         // happen.)
5141         boolean timeoutNeeded = true;
5142         if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
5143                 && (r.app != null) && (r.app.getPid() == ActivityManagerService.MY_PID)) {
5144 
5145             Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
5146                     + " " + r.getComponentName());
5147             timeoutNeeded = false;
5148         }
5149 
5150         // If the process is frozen or to be frozen, and we want to skip the timeout, skip it.
5151         final boolean shouldSkipTimeout = skipTimeoutIfPossible && r.app != null
5152                 && (r.app.mOptRecord.isPendingFreeze() || r.app.mOptRecord.isFrozen());
5153 
5154         ProcessServiceRecord psr;
5155         if (r.executeNesting == 0) {
5156             r.executeFg = fg;
5157             synchronized (mAm.mProcessStats.mLock) {
5158                 final ServiceState stracker = r.getTracker();
5159                 if (stracker != null) {
5160                     stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(),
5161                             SystemClock.uptimeMillis());
5162                 }
5163             }
5164             if (r.app != null) {
5165                 psr = r.app.mServices;
5166                 psr.startExecutingService(r);
5167                 psr.setExecServicesFg(psr.shouldExecServicesFg() || fg);
5168                 if (timeoutNeeded && psr.numberOfExecutingServices() == 1) {
5169                     if (!shouldSkipTimeout) {
5170                         scheduleServiceTimeoutLocked(r.app);
5171                     } else {
5172                         r.app.mServices.noteScheduleServiceTimeoutPending(true);
5173                     }
5174                 }
5175             }
5176         } else if (r.app != null && fg) {
5177             psr = r.app.mServices;
5178             if (!psr.shouldExecServicesFg()) {
5179                 psr.setExecServicesFg(true);
5180                 if (timeoutNeeded) {
5181                     if (!shouldSkipTimeout) {
5182                         scheduleServiceTimeoutLocked(r.app);
5183                     } else {
5184                         r.app.mServices.noteScheduleServiceTimeoutPending(true);
5185                     }
5186                 }
5187             }
5188         }
5189         if (r.app != null
5190                 && r.app.mState.getCurProcState() > ActivityManager.PROCESS_STATE_SERVICE) {
5191             // Enqueue the oom adj target anyway for opportunistic oom adj updates.
5192             mAm.enqueueOomAdjTargetLocked(r.app);
5193             r.updateOomAdjSeq();
5194             if (oomAdjReason != OOM_ADJ_REASON_NONE) {
5195                 // Force an immediate oomAdjUpdate, so the client app could be in the correct
5196                 // process state before doing any service related transactions
5197                 mAm.updateOomAdjPendingTargetsLocked(oomAdjReason);
5198             }
5199         }
5200         r.executeFg |= fg;
5201         r.executeNesting++;
5202         r.executingStart = SystemClock.uptimeMillis();
5203     }
5204 
requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)5205     private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
5206             boolean execInFg, boolean rebind,
5207             @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)
5208             throws TransactionTooLargeException {
5209         if (r.app == null || r.app.getThread() == null) {
5210             // If service is not currently running, can't yet bind.
5211             return false;
5212         }
5213         if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
5214                 + " rebind=" + rebind);
5215         final boolean skipOomAdj = (serviceBindingOomAdjPolicy
5216                 & SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_BIND) != 0;
5217         if ((!i.requested || rebind) && i.apps.size() > 0) {
5218             try {
5219                 bumpServiceExecutingLocked(r, execInFg, "bind",
5220                         skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_BIND_SERVICE,
5221                         skipOomAdj /* skipTimeoutIfPossible */);
5222                 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
5223                     Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER, "requestServiceBinding="
5224                             + i.intent.getIntent() + ". bindSeq=" + mBindServiceSeqCounter);
5225                 }
5226                 r.app.getThread().scheduleBindService(r, i.intent.getIntent(), rebind,
5227                         r.app.mState.getReportedProcState(), mBindServiceSeqCounter++);
5228                 if (!rebind) {
5229                     i.requested = true;
5230                 }
5231                 i.hasBound = true;
5232                 i.doRebind = false;
5233             } catch (TransactionTooLargeException e) {
5234                 // Keep the executeNesting count accurate.
5235                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
5236                 final boolean inDestroying = mDestroyingServices.contains(r);
5237                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, false,
5238                         !Flags.serviceBindingOomAdjPolicy() || r.wasOomAdjUpdated()
5239                         ? OOM_ADJ_REASON_UNBIND_SERVICE : OOM_ADJ_REASON_NONE);
5240                 throw e;
5241             } catch (RemoteException e) {
5242                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
5243                 // Keep the executeNesting count accurate.
5244                 final boolean inDestroying = mDestroyingServices.contains(r);
5245                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, false,
5246                         !Flags.serviceBindingOomAdjPolicy() || r.wasOomAdjUpdated()
5247                         ? OOM_ADJ_REASON_UNBIND_SERVICE : OOM_ADJ_REASON_NONE);
5248                 return false;
5249             }
5250         }
5251         return true;
5252     }
5253 
5254     /** @return {@code true} if the restart is scheduled. */
scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel)5255     private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
5256         if (mAm.mAtmInternal.isShuttingDown()) {
5257             Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
5258                     + " - system is shutting down");
5259             return false;
5260         }
5261 
5262         ServiceMap smap = getServiceMapLocked(r.userId);
5263         if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
5264             ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
5265             Slog.wtf(TAG, "Attempting to schedule restart of " + r
5266                     + " when found in map: " + cur);
5267             return false;
5268         }
5269 
5270         final long now = SystemClock.uptimeMillis();
5271 
5272         final String reason;
5273         final int oldPosInRestarting = mRestartingServices.indexOf(r);
5274         boolean inRestarting = oldPosInRestarting != -1;
5275         if ((r.serviceInfo.applicationInfo.flags
5276                 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
5277             long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
5278             long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
5279             boolean canceled = false;
5280 
5281             // Any delivered but not yet finished starts should be put back
5282             // on the pending list.
5283             final int N = r.deliveredStarts.size();
5284             if (N > 0) {
5285                 for (int i=N-1; i>=0; i--) {
5286                     ServiceRecord.StartItem si = r.deliveredStarts.get(i);
5287                     si.removeUriPermissionsLocked();
5288                     if (si.intent == null) {
5289                         // We'll generate this again if needed.
5290                     } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
5291                             && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
5292                         r.pendingStarts.add(0, si);
5293                         long dur = SystemClock.uptimeMillis() - si.deliveredTime;
5294                         dur *= 2;
5295                         if (minDuration < dur) minDuration = dur;
5296                         if (resetTime < dur) resetTime = dur;
5297                     } else {
5298                         Slog.w(TAG, "Canceling start item " + si.intent + " in service "
5299                                 + r.shortInstanceName);
5300                         canceled = true;
5301                     }
5302                 }
5303                 r.deliveredStarts.clear();
5304             }
5305 
5306             if (allowCancel) {
5307                 final boolean shouldStop = r.canStopIfKilled(canceled);
5308                 if (shouldStop && !r.hasAutoCreateConnections()) {
5309                     // Nothing to restart.
5310                     return false;
5311                 }
5312                 reason = (r.startRequested && !shouldStop) ? "start-requested" : "connection";
5313             } else {
5314                 reason = "always";
5315             }
5316 
5317             r.totalRestartCount++;
5318             if (r.restartDelay == 0) {
5319                 r.restartCount++;
5320                 r.restartDelay = minDuration;
5321             } else if (r.crashCount > 1) {
5322                 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
5323                         * (r.crashCount - 1);
5324             } else {
5325                 // If it has been a "reasonably long time" since the service
5326                 // was started, then reset our restart duration back to
5327                 // the beginning, so we don't infinitely increase the duration
5328                 // on a service that just occasionally gets killed (which is
5329                 // a normal case, due to process being killed to reclaim memory).
5330                 if (now > (r.restartTime+resetTime)) {
5331                     r.restartCount = 1;
5332                     r.restartDelay = minDuration;
5333                 } else {
5334                     r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
5335                     if (r.restartDelay < minDuration) {
5336                         r.restartDelay = minDuration;
5337                     }
5338                 }
5339             }
5340 
5341             if (isServiceRestartBackoffEnabledLocked(r.packageName)) {
5342                 r.nextRestartTime = r.mEarliestRestartTime = now + r.restartDelay;
5343 
5344                 if (inRestarting) {
5345                     // Take it out of the list temporarily for easier maintenance of the list.
5346                     mRestartingServices.remove(oldPosInRestarting);
5347                     inRestarting = false;
5348                 }
5349                 if (mRestartingServices.isEmpty()) {
5350                     // Apply the extra delay even if it's the only one in the list.
5351                     final long extraDelay = getExtraRestartTimeInBetweenLocked();
5352                     r.nextRestartTime = Math.max(now + extraDelay, r.nextRestartTime);
5353                     r.restartDelay = r.nextRestartTime - now;
5354                 } else {
5355                     // Make sure that we don't end up restarting a bunch of services
5356                     // all at the same time.
5357                     boolean repeat;
5358                     final long restartTimeBetween = getExtraRestartTimeInBetweenLocked()
5359                             + mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
5360                     do {
5361                         repeat = false;
5362                         final long nextRestartTime = r.nextRestartTime;
5363                         // mRestartingServices is sorted by nextRestartTime.
5364                         for (int i = mRestartingServices.size() - 1; i >= 0; i--) {
5365                             final ServiceRecord r2 = mRestartingServices.get(i);
5366                             final long nextRestartTime2 = r2.nextRestartTime;
5367                             if (nextRestartTime >= (nextRestartTime2 - restartTimeBetween)
5368                                     && nextRestartTime < (nextRestartTime2 + restartTimeBetween)) {
5369                                 r.nextRestartTime = nextRestartTime2 + restartTimeBetween;
5370                                 r.restartDelay = r.nextRestartTime - now;
5371                                 repeat = true;
5372                                 break;
5373                             } else if (nextRestartTime >= nextRestartTime2 + restartTimeBetween) {
5374                                 // This spot fulfills our needs, bail out.
5375                                 break;
5376                             }
5377                         }
5378                     } while (repeat);
5379                 }
5380             } else {
5381                 // It's been forced to ignore the restart backoff, fix the delay here.
5382                 r.restartDelay = mAm.mConstants.SERVICE_RESTART_DURATION;
5383                 r.nextRestartTime = now + r.restartDelay;
5384             }
5385         } else {
5386             // Persistent processes are immediately restarted, so there is no
5387             // reason to hold of on restarting their services.
5388             r.totalRestartCount++;
5389             r.restartCount = 0;
5390             r.restartDelay = 0;
5391             r.mEarliestRestartTime = 0;
5392             r.nextRestartTime = now;
5393             reason = "persistent";
5394         }
5395 
5396         r.mRestartSchedulingTime = now;
5397         if (!inRestarting) {
5398             if (oldPosInRestarting == -1) {
5399                 r.createdFromFg = false;
5400                 synchronized (mAm.mProcessStats.mLock) {
5401                     r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(),
5402                             SystemClock.uptimeMillis());
5403                 }
5404             }
5405             boolean added = false;
5406             for (int i = 0, size = mRestartingServices.size(); i < size; i++) {
5407                 final ServiceRecord r2 = mRestartingServices.get(i);
5408                 if (r2.nextRestartTime > r.nextRestartTime) {
5409                     mRestartingServices.add(i, r);
5410                     added = true;
5411                     break;
5412                 }
5413             }
5414             if (!added) {
5415                 mRestartingServices.add(r);
5416             }
5417         }
5418 
5419         cancelForegroundNotificationLocked(r);
5420 
5421         performScheduleRestartLocked(r, "Scheduling", reason, now);
5422 
5423         return true;
5424     }
5425 
5426     @GuardedBy("mAm")
performScheduleRestartLocked(ServiceRecord r, @NonNull String scheduling, @NonNull String reason, @UptimeMillisLong long now)5427     void performScheduleRestartLocked(ServiceRecord r, @NonNull String scheduling,
5428             @NonNull String reason, @UptimeMillisLong long now) {
5429 
5430         // If the service is waiting to become a foreground service, remove the pending
5431         // SERVICE_FOREGROUND_TIMEOUT_MSG msg, and set fgWaiting to false, so next time the service
5432         // is brought up, scheduleServiceForegroundTransitionTimeoutLocked() can be called again and
5433         // a new SERVICE_FOREGROUND_TIMEOUT_MSG is scheduled in SERVICE_START_FOREGROUND_TIMEOUT
5434         // again.
5435         if (r.fgRequired && r.fgWaiting) {
5436             mServiceFGAnrTimer.cancel(r);
5437             r.fgWaiting = false;
5438         }
5439 
5440         mAm.mHandler.removeCallbacks(r.restarter);
5441         mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
5442         r.nextRestartTime = now + r.restartDelay;
5443         Slog.w(TAG, scheduling + " restart of crashed service "
5444                 + r.shortInstanceName + " in " + r.restartDelay + "ms for " + reason);
5445         EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
5446                 r.userId, r.shortInstanceName, r.restartDelay);
5447     }
5448 
5449     /**
5450      * Reschedule service restarts based on the given memory pressure.
5451      *
5452      * @param prevMemFactor The previous memory factor.
5453      * @param curMemFactor The current memory factor.
5454      * @param reason The human-readable text about why we're doing rescheduling.
5455      * @param now The uptimeMillis
5456      */
5457     @GuardedBy("mAm")
rescheduleServiceRestartOnMemoryPressureIfNeededLocked(@emFactor int prevMemFactor, @MemFactor int curMemFactor, @NonNull String reason, @UptimeMillisLong long now)5458     void rescheduleServiceRestartOnMemoryPressureIfNeededLocked(@MemFactor int prevMemFactor,
5459             @MemFactor int curMemFactor, @NonNull String reason, @UptimeMillisLong long now) {
5460         final boolean enabled = mAm.mConstants.mEnableExtraServiceRestartDelayOnMemPressure;
5461         if (!enabled) {
5462             return;
5463         }
5464         performRescheduleServiceRestartOnMemoryPressureLocked(
5465                 mAm.mConstants.mExtraServiceRestartDelayOnMemPressure[prevMemFactor],
5466                 mAm.mConstants.mExtraServiceRestartDelayOnMemPressure[curMemFactor], reason, now);
5467     }
5468 
5469     /**
5470      * Reschedule service restarts based on if the extra delays are enabled or not.
5471      *
5472      * @param prevEnabled The previous state of whether or not it's enabled.
5473      * @param curEnabled The current state of whether or not it's enabled.
5474      * @param now The uptimeMillis
5475      */
5476     @GuardedBy("mAm")
rescheduleServiceRestartOnMemoryPressureIfNeededLocked(boolean prevEnabled, boolean curEnabled, @UptimeMillisLong long now)5477     void rescheduleServiceRestartOnMemoryPressureIfNeededLocked(boolean prevEnabled,
5478             boolean curEnabled, @UptimeMillisLong long now) {
5479         if (prevEnabled == curEnabled) {
5480             return;
5481         }
5482         final @MemFactor int memFactor = mAm.mAppProfiler.getLastMemoryLevelLocked();
5483         final long delay = mAm.mConstants.mExtraServiceRestartDelayOnMemPressure[memFactor];
5484         performRescheduleServiceRestartOnMemoryPressureLocked(prevEnabled ? delay : 0,
5485                 curEnabled ? delay : 0, "config", now);
5486     }
5487 
5488     /**
5489      * Rescan the list of pending restarts, reschedule them if needed.
5490      *
5491      * @param extraRestartTimeBetween The extra interval between restarts.
5492      * @param minRestartTimeBetween The minimal interval between restarts.
5493      * @param reason The human-readable text about why we're doing rescheduling.
5494      * @param now The uptimeMillis
5495      */
5496     @GuardedBy("mAm")
rescheduleServiceRestartIfPossibleLocked(long extraRestartTimeBetween, long minRestartTimeBetween, @NonNull String reason, @UptimeMillisLong long now)5497     void rescheduleServiceRestartIfPossibleLocked(long extraRestartTimeBetween,
5498             long minRestartTimeBetween, @NonNull String reason, @UptimeMillisLong long now) {
5499         final long restartTimeBetween = extraRestartTimeBetween + minRestartTimeBetween;
5500         final long spanForInsertOne = restartTimeBetween * 2; // Min space to insert a restart.
5501 
5502         long lastRestartTime = now;
5503         int lastRestartTimePos = -1; // The list index where the "lastRestartTime" comes from.
5504         for (int i = 0, size = mRestartingServices.size(); i < size; i++) {
5505             final ServiceRecord r = mRestartingServices.get(i);
5506             if ((r.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
5507                     || !isServiceRestartBackoffEnabledLocked(r.packageName)) {
5508                 lastRestartTime = r.nextRestartTime;
5509                 lastRestartTimePos = i;
5510                 continue;
5511             }
5512             if (lastRestartTime + restartTimeBetween <= r.mEarliestRestartTime) {
5513                 // Bounded by the earliest restart time, honor it; but we also need to
5514                 // check if the interval between the earlist and its prior one is enough or not.
5515                 r.nextRestartTime = Math.max(now, Math.max(r.mEarliestRestartTime, i > 0
5516                         ? mRestartingServices.get(i - 1).nextRestartTime + restartTimeBetween
5517                         : 0));
5518             } else {
5519                 if (lastRestartTime <= now) {
5520                     // It hasn't moved, this is the first one (besides persistent process),
5521                     // we don't need to insert the minRestartTimeBetween for it, but need
5522                     // the extraRestartTimeBetween still.
5523                     r.nextRestartTime = Math.max(now, Math.max(r.mEarliestRestartTime,
5524                             r.mRestartSchedulingTime + extraRestartTimeBetween));
5525                 } else {
5526                     r.nextRestartTime = Math.max(now, lastRestartTime + restartTimeBetween);
5527                 }
5528                 if (i > lastRestartTimePos + 1) {
5529                     // Move the current service record ahead in the list.
5530                     mRestartingServices.remove(i);
5531                     mRestartingServices.add(lastRestartTimePos + 1, r);
5532                 }
5533             }
5534             // Find the next available slot to insert one if there is any
5535             for (int j = lastRestartTimePos + 1; j <= i; j++) {
5536                 final ServiceRecord r2 = mRestartingServices.get(j);
5537                 final long timeInBetween = r2.nextRestartTime - (j == 0 ? lastRestartTime
5538                         : mRestartingServices.get(j - 1).nextRestartTime);
5539                 if (timeInBetween >= spanForInsertOne) {
5540                     break;
5541                 }
5542                 lastRestartTime = r2.nextRestartTime;
5543                 lastRestartTimePos = j;
5544             }
5545             r.restartDelay = r.nextRestartTime - now;
5546             performScheduleRestartLocked(r, "Rescheduling", reason, now);
5547         }
5548     }
5549 
5550     @GuardedBy("mAm")
performRescheduleServiceRestartOnMemoryPressureLocked(long oldExtraDelay, long newExtraDelay, @NonNull String reason, @UptimeMillisLong long now)5551     void performRescheduleServiceRestartOnMemoryPressureLocked(long oldExtraDelay,
5552             long newExtraDelay, @NonNull String reason, @UptimeMillisLong long now) {
5553         final long delta = newExtraDelay - oldExtraDelay;
5554         if (delta == 0) {
5555             return;
5556         }
5557         if (delta > 0) {
5558             final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN
5559                     + newExtraDelay;
5560             long lastRestartTime = now;
5561             // Make the delay in between longer.
5562             for (int i = 0, size = mRestartingServices.size(); i < size; i++) {
5563                 final ServiceRecord r = mRestartingServices.get(i);
5564                 if ((r.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
5565                         || !isServiceRestartBackoffEnabledLocked(r.packageName)) {
5566                     lastRestartTime = r.nextRestartTime;
5567                     continue;
5568                 }
5569                 boolean reschedule = false;
5570                 if (lastRestartTime <= now) {
5571                     // It hasn't moved, this is the first one (besides persistent process),
5572                     // we don't need to insert the minRestartTimeBetween for it, but need
5573                     // the newExtraDelay still.
5574                     final long oldVal = r.nextRestartTime;
5575                     r.nextRestartTime = Math.max(now, Math.max(r.mEarliestRestartTime,
5576                             r.mRestartSchedulingTime + newExtraDelay));
5577                     reschedule = r.nextRestartTime != oldVal;
5578                 } else if (r.nextRestartTime - lastRestartTime < restartTimeBetween) {
5579                     r.nextRestartTime = Math.max(lastRestartTime + restartTimeBetween, now);
5580                     reschedule = true;
5581                 }
5582                 r.restartDelay = r.nextRestartTime - now;
5583                 lastRestartTime = r.nextRestartTime;
5584                 if (reschedule) {
5585                     performScheduleRestartLocked(r, "Rescheduling", reason, now);
5586                 }
5587             }
5588         } else if (delta < 0) {
5589             // Make the delay in between shorter, we'd do a rescan and reschedule.
5590             rescheduleServiceRestartIfPossibleLocked(newExtraDelay,
5591                     mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN, reason, now);
5592         }
5593     }
5594 
5595     @GuardedBy("mAm")
getExtraRestartTimeInBetweenLocked()5596     long getExtraRestartTimeInBetweenLocked() {
5597         if (!mAm.mConstants.mEnableExtraServiceRestartDelayOnMemPressure) {
5598             return 0;
5599         }
5600         final @MemFactor int memFactor = mAm.mAppProfiler.getLastMemoryLevelLocked();
5601         return mAm.mConstants.mExtraServiceRestartDelayOnMemPressure[memFactor];
5602     }
5603 
performServiceRestartLocked(ServiceRecord r)5604     final void performServiceRestartLocked(ServiceRecord r) {
5605         if (!mRestartingServices.contains(r)) {
5606             return;
5607         }
5608         if (!isServiceNeededLocked(r, false, false)) {
5609             // Paranoia: is this service actually needed?  In theory a service that is not
5610             // needed should never remain on the restart list.  In practice...  well, there
5611             // have been bugs where this happens, and bad things happen because the process
5612             // ends up just being cached, so quickly killed, then restarted again and again.
5613             // Let's not let that happen.
5614             Slog.wtf(TAG, "Restarting service that is not needed: " + r);
5615             return;
5616         }
5617         try {
5618             bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false,
5619                     false, true, SERVICE_BIND_OOMADJ_POLICY_LEGACY);
5620         } catch (TransactionTooLargeException e) {
5621             // Ignore, it's been logged and nothing upstack cares.
5622         } finally {
5623             /* Will be a no-op if nothing pending */
5624             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
5625         }
5626     }
5627 
unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, boolean force)5628     private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
5629             boolean force) {
5630         if (!force && r.restartDelay == 0) {
5631             return false;
5632         }
5633         // Remove from the restarting list; if the service is currently on the
5634         // restarting list, or the call is coming from another app, then this
5635         // service has become of much more interest so we reset the restart interval.
5636         boolean removed = mRestartingServices.remove(r);
5637         if (removed || callingUid != r.appInfo.uid) {
5638             r.resetRestartCounter();
5639         }
5640         if (removed) {
5641             clearRestartingIfNeededLocked(r);
5642         }
5643         mAm.mHandler.removeCallbacks(r.restarter);
5644         return true;
5645     }
5646 
clearRestartingIfNeededLocked(ServiceRecord r)5647     private void clearRestartingIfNeededLocked(ServiceRecord r) {
5648         if (r.restartTracker != null) {
5649             // If this is the last restarting record with this tracker, then clear
5650             // the tracker's restarting state.
5651             boolean stillTracking = false;
5652             for (int i=mRestartingServices.size()-1; i>=0; i--) {
5653                 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
5654                     stillTracking = true;
5655                     break;
5656                 }
5657             }
5658             if (!stillTracking) {
5659                 synchronized (mAm.mProcessStats.mLock) {
5660                     r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
5661                             SystemClock.uptimeMillis());
5662                 }
5663                 r.restartTracker = null;
5664             }
5665         }
5666     }
5667 
5668     /**
5669      * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}.
5670      */
5671     @GuardedBy("mAm")
setServiceRestartBackoffEnabledLocked(@onNull String packageName, boolean enable, @NonNull String reason)5672     void setServiceRestartBackoffEnabledLocked(@NonNull String packageName, boolean enable,
5673             @NonNull String reason) {
5674         if (!enable) {
5675             if (mRestartBackoffDisabledPackages.contains(packageName)) {
5676                 // Already disabled, do nothing.
5677                 return;
5678             }
5679             mRestartBackoffDisabledPackages.add(packageName);
5680 
5681             final long now = SystemClock.uptimeMillis();
5682             for (int i = 0, size = mRestartingServices.size(); i < size; i++) {
5683                 final ServiceRecord r = mRestartingServices.get(i);
5684                 if (TextUtils.equals(r.packageName, packageName)) {
5685                     final long remaining = r.nextRestartTime - now;
5686                     if (remaining > mAm.mConstants.SERVICE_RESTART_DURATION) {
5687                         r.restartDelay = mAm.mConstants.SERVICE_RESTART_DURATION;
5688                         r.nextRestartTime = now + r.restartDelay;
5689                         performScheduleRestartLocked(r, "Rescheduling", reason, now);
5690                     }
5691                 }
5692                 // mRestartingServices is sorted by nextRestartTime.
5693                 Collections.sort(mRestartingServices,
5694                         (a, b) -> (int) (a.nextRestartTime - b.nextRestartTime));
5695             }
5696         } else {
5697             removeServiceRestartBackoffEnabledLocked(packageName);
5698             // For the simplicity, we are not going to reschedule its pending restarts
5699             // when we turn the backoff policy back on.
5700         }
5701     }
5702 
5703     @GuardedBy("mAm")
removeServiceRestartBackoffEnabledLocked(@onNull String packageName)5704     private void removeServiceRestartBackoffEnabledLocked(@NonNull String packageName) {
5705         mRestartBackoffDisabledPackages.remove(packageName);
5706     }
5707 
5708     /**
5709      * @return {@code false} if the given package has been disable from enforcing the service
5710      * restart backoff policy, used by {@link ActivityManagerShellCommand}.
5711      */
5712     @GuardedBy("mAm")
isServiceRestartBackoffEnabledLocked(@onNull String packageName)5713     boolean isServiceRestartBackoffEnabledLocked(@NonNull String packageName) {
5714         return !mRestartBackoffDisabledPackages.contains(packageName);
5715     }
5716 
bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen, boolean enqueueOomAdj, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)5717     private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
5718             boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen,
5719             boolean enqueueOomAdj, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)
5720             throws TransactionTooLargeException {
5721         try {
5722             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
5723                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
5724                         "bringUpServiceLocked: " + r.shortInstanceName);
5725             }
5726             return bringUpServiceInnerLocked(r, intentFlags, execInFg, whileRestarting,
5727                     permissionsReviewRequired, packageFrozen, enqueueOomAdj,
5728                     serviceBindingOomAdjPolicy);
5729         } finally {
5730             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5731         }
5732     }
5733 
bringUpServiceInnerLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen, boolean enqueueOomAdj, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)5734     private String bringUpServiceInnerLocked(ServiceRecord r, int intentFlags, boolean execInFg,
5735             boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen,
5736             boolean enqueueOomAdj, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)
5737             throws TransactionTooLargeException {
5738         if (r.app != null && r.app.isThreadReady()) {
5739             r.updateOomAdjSeq();
5740             sendServiceArgsLocked(r, execInFg, false);
5741             return null;
5742         }
5743 
5744         if (!whileRestarting && mRestartingServices.contains(r)) {
5745             // If waiting for a restart, then do nothing.
5746             return null;
5747         }
5748 
5749         final long startTimeNs = SystemClock.elapsedRealtimeNanos();
5750 
5751         if (DEBUG_SERVICE) {
5752             Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
5753         }
5754 
5755         // We are now bringing the service up, so no longer in the
5756         // restarting state.
5757         if (mRestartingServices.remove(r)) {
5758             clearRestartingIfNeededLocked(r);
5759         }
5760 
5761         // Make sure this service is no longer considered delayed, we are starting it now.
5762         if (r.delayed) {
5763             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
5764             getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
5765             r.delayed = false;
5766         }
5767 
5768         // Make sure that the user who owns this service is started.  If not,
5769         // we don't want to allow it to run.
5770         if (!mAm.mUserController.hasStartedUserState(r.userId)) {
5771             String msg = "Unable to launch app "
5772                     + r.appInfo.packageName + "/"
5773                     + r.appInfo.uid + " for service "
5774                     + r.intent.getIntent() + ": user " + r.userId + " is stopped";
5775             Slog.w(TAG, msg);
5776             bringDownServiceLocked(r, enqueueOomAdj);
5777             return msg;
5778         }
5779 
5780         // Report usage if binding is from a different package except for explicitly exempted
5781         // bindings
5782         if (!r.appInfo.packageName.equals(r.mRecentCallingPackage)
5783                 && !r.isNotAppComponentUsage) {
5784             mAm.mUsageStatsService.reportEvent(
5785                     r.packageName, r.userId, UsageEvents.Event.APP_COMPONENT_USED);
5786         }
5787 
5788         try {
5789             mAm.mPackageManagerInt.notifyComponentUsed(
5790                     r.packageName, r.userId, r.mRecentCallingPackage, r.toString());
5791         } catch (IllegalArgumentException e) {
5792             Slog.w(TAG, "Failed trying to unstop package "
5793                     + r.packageName + ": " + e);
5794         }
5795 
5796         final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
5797         final String procName = r.processName;
5798         HostingRecord hostingRecord = new HostingRecord(
5799                 HostingRecord.HOSTING_TYPE_SERVICE, r.instanceName,
5800                 r.definingPackageName, r.definingUid, r.serviceInfo.processName,
5801                 getHostingRecordTriggerType(r));
5802         ProcessRecord app;
5803 
5804         if (!isolated) {
5805             app = mAm.getProcessRecordLocked(procName, r.appInfo.uid);
5806             if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
5807                         + " app=" + app);
5808             if (app != null) {
5809                 final IApplicationThread thread = app.getThread();
5810                 final int pid = app.getPid();
5811                 final UidRecord uidRecord = app.getUidRecord();
5812                 if (app.isThreadReady()) {
5813                     try {
5814                         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
5815                             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
5816                                     "realStartServiceLocked: " + r.shortInstanceName);
5817                         }
5818                         app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode,
5819                                 mAm.mProcessStats);
5820                         realStartServiceLocked(r, app, thread, pid, uidRecord, execInFg,
5821                                 enqueueOomAdj, serviceBindingOomAdjPolicy);
5822                         return null;
5823                     } catch (TransactionTooLargeException e) {
5824                         throw e;
5825                     } catch (RemoteException e) {
5826                         Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
5827                     } finally {
5828                         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5829                     }
5830 
5831                     // If a dead object exception was thrown -- fall through to
5832                     // restart the application.
5833                 }
5834             }
5835         } else {
5836             if (r.inSharedIsolatedProcess) {
5837                 app = mAm.mProcessList.getSharedIsolatedProcess(procName, r.appInfo.uid,
5838                         r.appInfo.packageName);
5839                 if (app != null) {
5840                     final IApplicationThread thread = app.getThread();
5841                     final int pid = app.getPid();
5842                     final UidRecord uidRecord = app.getUidRecord();
5843                     r.isolationHostProc = app;
5844                     if (app.isThreadReady()) {
5845                         try {
5846                             if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
5847                                 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
5848                                         "realStartServiceLocked: " + r.shortInstanceName);
5849                             }
5850                             realStartServiceLocked(r, app, thread, pid, uidRecord, execInFg,
5851                                     enqueueOomAdj, SERVICE_BIND_OOMADJ_POLICY_LEGACY);
5852                             return null;
5853                         } catch (TransactionTooLargeException e) {
5854                             throw e;
5855                         } catch (RemoteException e) {
5856                             Slog.w(TAG, "Exception when starting service " + r.shortInstanceName,
5857                                     e);
5858                         } finally {
5859                             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
5860                         }
5861                         // If a dead object exception was thrown -- fall through to
5862                         // restart the application.
5863                     }
5864                 }
5865             } else {
5866                 // If this service runs in an isolated process, then each time
5867                 // we call startProcessLocked() we will get a new isolated
5868                 // process, starting another process if we are currently waiting
5869                 // for a previous process to come up.  To deal with this, we store
5870                 // in the service any current isolated process it is running in or
5871                 // waiting to have come up.
5872                 app = r.isolationHostProc;
5873                 if (WebViewZygote.isMultiprocessEnabled()
5874                         && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
5875                     hostingRecord = HostingRecord.byWebviewZygote(r.instanceName,
5876                             r.definingPackageName,
5877                             r.definingUid, r.serviceInfo.processName);
5878                 }
5879                 if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
5880                     hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName,
5881                             r.definingUid, r.serviceInfo.processName);
5882                 }
5883             }
5884         }
5885 
5886         // Not running -- get it started, and enqueue this service record
5887         // to be executed when the app comes up.
5888         if (app == null && !permissionsReviewRequired && !packageFrozen) {
5889             // TODO (chriswailes): Change the Zygote policy flags based on if the launch-for-service
5890             //  was initiated from a notification tap or not.
5891             if (r.isSdkSandbox) {
5892                 final int uid = Process.toSdkSandboxUid(r.sdkSandboxClientAppUid);
5893                 app = mAm.startSdkSandboxProcessLocked(procName, r.appInfo, true, intentFlags,
5894                         hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, uid, r.sdkSandboxClientAppPackage);
5895                 r.isolationHostProc = app;
5896             } else {
5897                 app = mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
5898                         hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated);
5899             }
5900             if (app == null) {
5901                 String msg = "Unable to launch app "
5902                         + r.appInfo.packageName + "/"
5903                         + r.appInfo.uid + " for service "
5904                         + r.intent.getIntent() + ": process is bad";
5905                 Slog.w(TAG, msg);
5906                 bringDownServiceLocked(r, enqueueOomAdj);
5907                 return msg;
5908             }
5909             mAm.mProcessList.getAppStartInfoTracker().handleProcessServiceStart(startTimeNs, app,
5910                     r);
5911             if (isolated) {
5912                 r.isolationHostProc = app;
5913             }
5914         }
5915 
5916         if (r.fgRequired) {
5917             if (DEBUG_FOREGROUND_SERVICE) {
5918                 Slog.v(TAG, "Allowlisting " + UserHandle.formatUid(r.appInfo.uid)
5919                         + " for fg-service launch");
5920             }
5921             mAm.tempAllowlistUidLocked(r.appInfo.uid,
5922                     mAm.mConstants.mServiceStartForegroundTimeoutMs, REASON_SERVICE_LAUNCH,
5923                     "fg-service-launch",
5924                     TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
5925                     r.mRecentCallingUid);
5926         }
5927 
5928         if (!mPendingServices.contains(r)) {
5929             mPendingServices.add(r);
5930         }
5931 
5932         if (r.delayedStop) {
5933             // Oh and hey we've already been asked to stop!
5934             r.delayedStop = false;
5935             if (r.startRequested) {
5936                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
5937                         "Applying delayed stop (in bring up): " + r);
5938                 stopServiceLocked(r, enqueueOomAdj);
5939             }
5940         }
5941 
5942         return null;
5943     }
5944 
getHostingRecordTriggerType(ServiceRecord r)5945     private String getHostingRecordTriggerType(ServiceRecord r) {
5946         if (Manifest.permission.BIND_JOB_SERVICE.equals(r.permission)
5947                 && r.mRecentCallingUid == SYSTEM_UID) {
5948             return HostingRecord.TRIGGER_TYPE_JOB;
5949         }
5950         return HostingRecord.TRIGGER_TYPE_UNKNOWN;
5951     }
5952 
requestServiceBindingsLocked(ServiceRecord r, boolean execInFg, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)5953     private void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg,
5954             @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)
5955             throws TransactionTooLargeException {
5956         for (int i=r.bindings.size()-1; i>=0; i--) {
5957             IntentBindRecord ibr = r.bindings.valueAt(i);
5958             if (!requestServiceBindingLocked(r, ibr, execInFg, false, serviceBindingOomAdjPolicy)) {
5959                 break;
5960             }
5961         }
5962     }
5963 
5964     @ServiceBindingOomAdjPolicy
getServiceBindingOomAdjPolicyForAddLocked(ProcessRecord clientApp, ProcessRecord hostApp, ConnectionRecord cr)5965     private int getServiceBindingOomAdjPolicyForAddLocked(ProcessRecord clientApp,
5966             ProcessRecord hostApp, ConnectionRecord cr) {
5967         @ServiceBindingOomAdjPolicy int policy = SERVICE_BIND_OOMADJ_POLICY_LEGACY;
5968         if (Flags.serviceBindingOomAdjPolicy() && clientApp != null && hostApp != null) {
5969             if (clientApp == hostApp) {
5970                 policy = DEFAULT_SERVICE_NO_BUMP_BIND_POLICY_FLAG;
5971             } else if (clientApp.isCached()) {
5972                 policy = DEFAULT_SERVICE_NO_BUMP_BIND_POLICY_FLAG;
5973                 if (clientApp.isFreezable()) {
5974                     policy |= SERVICE_BIND_OOMADJ_POLICY_FREEZE_CALLER;
5975                 }
5976             }
5977             if ((policy & SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT) == 0) {
5978                 // Binding between two different processes.
5979                 // Check if the caller has a better process state, oom adj score,
5980                 // or if the caller has more capabilities.
5981                 if (!mAm.mOomAdjuster.evaluateServiceConnectionAdd(clientApp, hostApp, cr)) {
5982                     // Running an oom adjuster won't be give the host app a better score, skip it.
5983                     policy = DEFAULT_SERVICE_NO_BUMP_BIND_POLICY_FLAG;
5984                 }
5985             }
5986         }
5987         return policy;
5988     }
5989 
5990     @ServiceBindingOomAdjPolicy
getServiceBindingOomAdjPolicyForRemovalLocked(ProcessRecord clientApp, ProcessRecord hostApp, ConnectionRecord cr)5991     private int getServiceBindingOomAdjPolicyForRemovalLocked(ProcessRecord clientApp,
5992             ProcessRecord hostApp, ConnectionRecord cr) {
5993         @ServiceBindingOomAdjPolicy int policy = SERVICE_BIND_OOMADJ_POLICY_LEGACY;
5994         if (Flags.serviceBindingOomAdjPolicy() && clientApp != null && hostApp != null
5995                 && cr != null) {
5996             if (clientApp == hostApp) {
5997                 policy = DEFAULT_SERVICE_NO_BUMP_BIND_POLICY_FLAG;
5998             } else {
5999                 if (!mAm.mOomAdjuster.evaluateServiceConnectionRemoval(clientApp, hostApp, cr)) {
6000                     // Running an oom adjuster won't be give the host app a better score, skip it.
6001                     policy = DEFAULT_SERVICE_NO_BUMP_BIND_POLICY_FLAG;
6002                 }
6003             }
6004         }
6005         return policy;
6006     }
6007 
6008     /**
6009      * Note the name of this method should not be confused with the started services concept.
6010      * The "start" here means bring up the instance in the client, and this method is called
6011      * from bindService() as well.
6012      */
realStartServiceLocked(ServiceRecord r, ProcessRecord app, IApplicationThread thread, int pid, UidRecord uidRecord, boolean execInFg, boolean enqueueOomAdj, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)6013     private void realStartServiceLocked(ServiceRecord r, ProcessRecord app,
6014             IApplicationThread thread, int pid, UidRecord uidRecord, boolean execInFg,
6015             boolean enqueueOomAdj, @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy)
6016             throws RemoteException {
6017         if (thread == null) {
6018             throw new RemoteException();
6019         }
6020         if (DEBUG_MU)
6021             Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
6022                     + ", ProcessRecord.uid = " + app.uid);
6023         r.setProcess(app, thread, pid, uidRecord);
6024         r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
6025         final boolean skipOomAdj = (serviceBindingOomAdjPolicy
6026                 & SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CREATE) != 0;
6027         final ProcessServiceRecord psr = app.mServices;
6028         final boolean newService = psr.startService(r);
6029         bumpServiceExecutingLocked(r, execInFg, "create",
6030                 OOM_ADJ_REASON_NONE /* use "none" to avoid extra oom adj */,
6031                 skipOomAdj /* skipTimeoutIfPossible */);
6032         mAm.updateLruProcessLocked(app, false, null);
6033         updateServiceForegroundLocked(psr, /* oomAdj= */ false);
6034         // Skip the oom adj update if it's a self-binding, the Service#onCreate() will be running
6035         // at its current adj score.
6036         if (!skipOomAdj) {
6037             // Force an immediate oomAdjUpdate, so the host app could be in the correct
6038             // process state before doing any service related transactions
6039             mAm.enqueueOomAdjTargetLocked(app);
6040             r.updateOomAdjSeq();
6041             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
6042         } else {
6043             // Since we skipped the oom adj update, the Service#onCreate() might be running in
6044             // the cached state, if the service process drops into the cached state after the call.
6045             // But there is still a grace period before freezing it, so we should be fine
6046             // in terms of not getting an ANR.
6047         }
6048 
6049         boolean created = false;
6050         try {
6051             if (LOG_SERVICE_START_STOP) {
6052                 String nameTerm;
6053                 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
6054                 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
6055                         : r.shortInstanceName;
6056                 EventLogTags.writeAmCreateService(
6057                         r.userId, System.identityHashCode(r), nameTerm, r.app.uid, pid);
6058             }
6059 
6060             final int uid = r.appInfo.uid;
6061             final String packageName = r.name.getPackageName();
6062             final String serviceName = r.name.getClassName();
6063             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_LAUNCH_REPORTED, uid, packageName,
6064                     serviceName);
6065             mAm.mBatteryStatsService.noteServiceStartLaunch(uid, packageName, serviceName);
6066             mAm.notifyPackageUse(r.serviceInfo.packageName,
6067                                  PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
6068             thread.scheduleCreateService(r, r.serviceInfo,
6069                     null /* compatInfo (unused but need to keep method signature) */,
6070                     app.mState.getReportedProcState());
6071             r.postNotification(false);
6072             created = true;
6073         } catch (DeadObjectException e) {
6074             Slog.w(TAG, "Application dead when creating service " + r);
6075             mAm.appDiedLocked(app, "Died when creating service");
6076             throw e;
6077         } finally {
6078             if (!created) {
6079                 // Keep the executeNesting count accurate.
6080                 final boolean inDestroying = mDestroyingServices.contains(r);
6081                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, false,
6082                         !Flags.serviceBindingOomAdjPolicy() || r.wasOomAdjUpdated()
6083                         ? OOM_ADJ_REASON_STOP_SERVICE : OOM_ADJ_REASON_NONE);
6084 
6085                 // Cleanup.
6086                 if (newService) {
6087                     psr.stopService(r);
6088                     r.setProcess(null, null, 0, null);
6089                 }
6090 
6091                 // Retry.
6092                 if (!inDestroying) {
6093                     scheduleServiceRestartLocked(r, false);
6094                 }
6095             }
6096         }
6097 
6098         if (r.allowlistManager) {
6099             psr.mAllowlistManager = true;
6100         }
6101 
6102         requestServiceBindingsLocked(r, execInFg, serviceBindingOomAdjPolicy);
6103 
6104         updateServiceClientActivitiesLocked(psr, null, true);
6105 
6106         if (newService && created) {
6107             psr.addBoundClientUidsOfNewService(r);
6108         }
6109 
6110         // If the service is in the started state, and there are no
6111         // pending arguments, then fake up one so its onStartCommand() will
6112         // be called.
6113         if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
6114             r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
6115                     null, null, 0, null, null, ActivityManager.PROCESS_STATE_UNKNOWN));
6116         }
6117 
6118         sendServiceArgsLocked(r, execInFg, r.wasOomAdjUpdated());
6119 
6120         if (r.delayed) {
6121             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
6122             getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
6123             r.delayed = false;
6124         }
6125 
6126         if (r.delayedStop) {
6127             // Oh and hey we've already been asked to stop!
6128             r.delayedStop = false;
6129             if (r.startRequested) {
6130                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
6131                         "Applying delayed stop (from start): " + r);
6132                 stopServiceLocked(r, enqueueOomAdj);
6133             }
6134         }
6135     }
6136 
sendServiceArgsLocked(ServiceRecord r, boolean execInFg, boolean oomAdjusted)6137     private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
6138             boolean oomAdjusted) throws TransactionTooLargeException {
6139         final int N = r.pendingStarts.size();
6140         if (N == 0) {
6141             return;
6142         }
6143 
6144         ArrayList<ServiceStartArgs> args = new ArrayList<>();
6145 
6146         while (r.pendingStarts.size() > 0) {
6147             ServiceRecord.StartItem si = r.pendingStarts.remove(0);
6148             if (DEBUG_SERVICE) {
6149                 Slog.v(TAG_SERVICE, "Sending arguments to: "
6150                         + r + " " + r.intent + " args=" + si.intent);
6151             }
6152             if (si.intent == null && N > 1) {
6153                 // If somehow we got a dummy null intent in the middle,
6154                 // then skip it.  DO NOT skip a null intent when it is
6155                 // the only one in the list -- this is to support the
6156                 // onStartCommand(null) case.
6157                 continue;
6158             }
6159             si.deliveredTime = SystemClock.uptimeMillis();
6160             r.deliveredStarts.add(si);
6161             si.deliveryCount++;
6162             if (si.neededGrants != null) {
6163                 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
6164                         si.getUriPermissionsLocked());
6165             }
6166             mAm.grantImplicitAccess(r.userId, si.intent, si.callingId,
6167                     UserHandle.getAppId(r.appInfo.uid)
6168             );
6169             bumpServiceExecutingLocked(r, execInFg, "start",
6170                     OOM_ADJ_REASON_NONE /* use "none" to avoid extra oom adj */,
6171                     false /* skipTimeoutIfPossible */);
6172             if (r.fgRequired && !r.fgWaiting) {
6173                 if (!r.isForeground) {
6174                     if (DEBUG_BACKGROUND_CHECK) {
6175                         Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
6176                     }
6177                     scheduleServiceForegroundTransitionTimeoutLocked(r);
6178                 } else {
6179                     if (DEBUG_BACKGROUND_CHECK) {
6180                         Slog.i(TAG, "Service already foreground; no new timeout: " + r);
6181                     }
6182                     r.fgRequired = false;
6183                 }
6184             }
6185             int flags = 0;
6186             if (si.deliveryCount > 1) {
6187                 flags |= Service.START_FLAG_RETRY;
6188             }
6189             if (si.doneExecutingCount > 0) {
6190                 flags |= Service.START_FLAG_REDELIVERY;
6191             }
6192             args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
6193         }
6194 
6195         if (!oomAdjusted) {
6196             mAm.enqueueOomAdjTargetLocked(r.app);
6197             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
6198         }
6199         ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
6200         slice.setInlineCountLimit(4);
6201         Exception caughtException = null;
6202         try {
6203             r.app.getThread().scheduleServiceArgs(r, slice);
6204         } catch (TransactionTooLargeException e) {
6205             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
6206                     + " args, first: " + args.get(0).args);
6207             Slog.w(TAG, "Failed delivering service starts", e);
6208             caughtException = e;
6209         } catch (RemoteException e) {
6210             // Remote process gone...  we'll let the normal cleanup take care of this.
6211             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
6212             Slog.w(TAG, "Failed delivering service starts", e);
6213             caughtException = e;
6214         } catch (Exception e) {
6215             Slog.w(TAG, "Unexpected exception", e);
6216             caughtException = e;
6217         }
6218 
6219         if (caughtException != null) {
6220             // Keep nesting count correct
6221             final boolean inDestroying = mDestroyingServices.contains(r);
6222             for (int i = 0, size = args.size(); i < size; i++) {
6223                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, true,
6224                         OOM_ADJ_REASON_STOP_SERVICE);
6225             }
6226             /* Will be a no-op if nothing pending */
6227             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_STOP_SERVICE);
6228             if (caughtException instanceof TransactionTooLargeException) {
6229                 throw (TransactionTooLargeException)caughtException;
6230             }
6231         }
6232     }
6233 
isServiceNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)6234     private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
6235             boolean hasConn) {
6236         // Are we still explicitly being asked to run?
6237         if (r.startRequested) {
6238             return true;
6239         }
6240 
6241         // Is someone still bound to us keeping us running?
6242         if (!knowConn) {
6243             hasConn = r.hasAutoCreateConnections();
6244         }
6245         if (hasConn) {
6246             return true;
6247         }
6248 
6249         return false;
6250     }
6251 
bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn, boolean enqueueOomAdj, String debugReason)6252     private void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
6253             boolean hasConn, boolean enqueueOomAdj, String debugReason) {
6254         if (DEBUG_SERVICE) {
6255             Slog.i(TAG, "Bring down service for " + debugReason + " :" + r.toString());
6256         }
6257 
6258         if (isServiceNeededLocked(r, knowConn, hasConn)) {
6259             return;
6260         }
6261 
6262         // Are we in the process of launching?
6263         if (mPendingServices.contains(r)) {
6264             return;
6265         }
6266 
6267         bringDownServiceLocked(r, enqueueOomAdj);
6268     }
6269 
bringDownServiceLocked(ServiceRecord r, boolean enqueueOomAdj)6270     private void bringDownServiceLocked(ServiceRecord r, boolean enqueueOomAdj) {
6271         //Slog.i(TAG, "Bring down service:");
6272         //r.dump("  ");
6273 
6274         if (r.isShortFgs()) {
6275             // FGS can be stopped without the app calling stopService() or stopSelf(),
6276             // due to force-app-standby, or from Task Manager.
6277             Slog.w(TAG_SERVICE, "Short FGS brought down without stopping: " + r);
6278             maybeStopShortFgsTimeoutLocked(r);
6279         }
6280 
6281         // Report to all of the connections that the service is no longer
6282         // available.
6283         ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
6284         for (int conni = connections.size() - 1; conni >= 0; conni--) {
6285             ArrayList<ConnectionRecord> c = connections.valueAt(conni);
6286             for (int i=0; i<c.size(); i++) {
6287                 ConnectionRecord cr = c.get(i);
6288                 // There is still a connection to the service that is
6289                 // being brought down.  Mark it as dead.
6290                 cr.serviceDead = true;
6291                 cr.stopAssociation();
6292                 final ComponentName clientSideComponentName =
6293                         cr.aliasComponent != null ? cr.aliasComponent : r.name;
6294                 try {
6295                     cr.conn.connected(clientSideComponentName, null, true);
6296                 } catch (Exception e) {
6297                     Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
6298                           + " to connection " + c.get(i).conn.asBinder()
6299                           + " (in " + c.get(i).binding.client.processName + ")", e);
6300                 }
6301             }
6302         }
6303 
6304         boolean oomAdjusted = Flags.serviceBindingOomAdjPolicy() && r.wasOomAdjUpdated();
6305 
6306         // Tell the service that it has been unbound.
6307         if (r.app != null && r.app.isThreadReady()) {
6308             for (int i = r.bindings.size() - 1; i >= 0; i--) {
6309                 IntentBindRecord ibr = r.bindings.valueAt(i);
6310                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
6311                         + ": hasBound=" + ibr.hasBound);
6312                 if (ibr.hasBound) {
6313                     try {
6314                         bumpServiceExecutingLocked(r, false, "bring down unbind",
6315                                 oomAdjusted ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE,
6316                                 oomAdjusted /* skipTimeoutIfPossible */);
6317                         oomAdjusted |= r.wasOomAdjUpdated();
6318                         ibr.hasBound = false;
6319                         ibr.requested = false;
6320                         r.app.getThread().scheduleUnbindService(r,
6321                                 ibr.intent.getIntent());
6322                     } catch (Exception e) {
6323                         Slog.w(TAG, "Exception when unbinding service "
6324                                 + r.shortInstanceName, e);
6325                         serviceProcessGoneLocked(r, enqueueOomAdj);
6326                         break;
6327                     }
6328                 }
6329             }
6330         }
6331 
6332         // Check to see if the service had been started as foreground, but being
6333         // brought down before actually showing a notification.  That is not allowed.
6334         if (r.fgRequired) {
6335             Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
6336                     + r);
6337             r.fgRequired = false;
6338             r.fgWaiting = false;
6339             synchronized (mAm.mProcessStats.mLock) {
6340                 ServiceState stracker = r.getTracker();
6341                 if (stracker != null) {
6342                     stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
6343                             SystemClock.uptimeMillis());
6344                 }
6345             }
6346             mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
6347                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
6348             mServiceFGAnrTimer.cancel(r);
6349             if (r.app != null) {
6350                 Message msg = mAm.mHandler.obtainMessage(
6351                         ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
6352                 SomeArgs args = SomeArgs.obtain();
6353                 args.arg1 = r.app;
6354                 args.arg2 = r.toString();
6355                 args.arg3 = r.getComponentName();
6356 
6357                 msg.obj = args;
6358                 mAm.mHandler.sendMessage(msg);
6359             }
6360         }
6361 
6362         if (DEBUG_SERVICE) {
6363             RuntimeException here = new RuntimeException();
6364             here.fillInStackTrace();
6365             Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
6366         }
6367         r.destroyTime = SystemClock.uptimeMillis();
6368         if (LOG_SERVICE_START_STOP) {
6369             EventLogTags.writeAmDestroyService(
6370                     r.userId, System.identityHashCode(r), (r.app != null) ? r.app.getPid() : -1);
6371         }
6372 
6373         final ServiceMap smap = getServiceMapLocked(r.userId);
6374         ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
6375 
6376         // Note when this method is called by bringUpServiceLocked(), the service is not found
6377         // in mServicesByInstanceName and found will be null.
6378         if (found != null && found != r) {
6379             // This is not actually the service we think is running...  this should not happen,
6380             // but if it does, fail hard.
6381             smap.mServicesByInstanceName.put(r.instanceName, found);
6382             throw new IllegalStateException("Bringing down " + r + " but actually running "
6383                     + found);
6384         }
6385         smap.mServicesByIntent.remove(r.intent);
6386         r.totalRestartCount = 0;
6387         unscheduleServiceRestartLocked(r, 0, true);
6388 
6389         // Also make sure it is not on the pending list.
6390         for (int i=mPendingServices.size()-1; i>=0; i--) {
6391             if (mPendingServices.get(i) == r) {
6392                 mPendingServices.remove(i);
6393                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
6394             }
6395         }
6396         if (mPendingBringups.remove(r) != null) {
6397             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending bringup: " + r);
6398         }
6399 
6400         cancelForegroundNotificationLocked(r);
6401         final boolean exitingFg = r.isForeground;
6402         if (exitingFg) {
6403             maybeStopShortFgsTimeoutLocked(r);
6404             decActiveForegroundAppLocked(smap, r);
6405             synchronized (mAm.mProcessStats.mLock) {
6406                 ServiceState stracker = r.getTracker();
6407                 if (stracker != null) {
6408                     stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
6409                             SystemClock.uptimeMillis());
6410                 }
6411             }
6412             mAm.mAppOpsService.finishOperation(
6413                     AppOpsManager.getToken(mAm.mAppOpsService),
6414                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
6415             unregisterAppOpCallbackLocked(r);
6416             r.mFgsExitTime = SystemClock.uptimeMillis();
6417             logFGSStateChangeLocked(r,
6418                     FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT,
6419                     r.mFgsExitTime > r.mFgsEnterTime
6420                             ? (int) (r.mFgsExitTime - r.mFgsEnterTime) : 0,
6421                     FGS_STOP_REASON_STOP_SERVICE,
6422                     FGS_TYPE_POLICY_CHECK_UNKNOWN,
6423                     FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_NA,
6424                     false /* fgsRestrictionRecalculated */
6425             );
6426             synchronized (mFGSLogger) {
6427                 mFGSLogger.logForegroundServiceStop(r.appInfo.uid, r);
6428             }
6429             mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
6430         }
6431 
6432         r.isForeground = false;
6433         r.mFgsNotificationWasDeferred = false;
6434         dropFgsNotificationStateLocked(r);
6435         r.foregroundId = 0;
6436         r.foregroundNoti = null;
6437         resetFgsRestrictionLocked(r);
6438         // Signal FGS observers *after* changing the isForeground state, and
6439         // only if this was an actual state change.
6440         if (exitingFg) {
6441             signalForegroundServiceObserversLocked(r);
6442         }
6443 
6444         // Clear start entries.
6445         r.clearDeliveredStartsLocked();
6446         r.pendingStarts.clear();
6447         smap.mDelayedStartList.remove(r);
6448 
6449         if (r.app != null) {
6450             mAm.mBatteryStatsService.noteServiceStopLaunch(r.appInfo.uid, r.name.getPackageName(),
6451                     r.name.getClassName());
6452             stopServiceAndUpdateAllowlistManagerLocked(r);
6453             if (r.app.isThreadReady()) {
6454                 // Bump the process to the top of LRU list
6455                 mAm.updateLruProcessLocked(r.app, false, null);
6456                 updateServiceForegroundLocked(r.app.mServices, false);
6457                 if (r.mIsFgsDelegate) {
6458                     if (r.mFgsDelegation.mConnection != null) {
6459                         mAm.mHandler.post(() -> {
6460                             r.mFgsDelegation.mConnection.onServiceDisconnected(
6461                                     r.mFgsDelegation.mOptions.getComponentName());
6462                         });
6463                     }
6464                     for (int i = mFgsDelegations.size() - 1; i >= 0; i--) {
6465                         if (mFgsDelegations.valueAt(i) == r) {
6466                             mFgsDelegations.removeAt(i);
6467                             break;
6468                         }
6469                     }
6470                 } else {
6471                     try {
6472                         bumpServiceExecutingLocked(r, false, "destroy",
6473                                 oomAdjusted ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE,
6474                                 oomAdjusted /* skipTimeoutIfPossible */);
6475                         mDestroyingServices.add(r);
6476                         oomAdjusted |= r.wasOomAdjUpdated();
6477                         r.destroying = true;
6478                         r.app.getThread().scheduleStopService(r);
6479                     } catch (Exception e) {
6480                         Slog.w(TAG, "Exception when destroying service "
6481                                 + r.shortInstanceName, e);
6482                         serviceProcessGoneLocked(r, enqueueOomAdj);
6483                     }
6484                 }
6485             } else {
6486                 if (DEBUG_SERVICE) Slog.v(
6487                     TAG_SERVICE, "Removed service that has no process: " + r);
6488             }
6489         } else {
6490             if (DEBUG_SERVICE) Slog.v(
6491                 TAG_SERVICE, "Removed service that is not running: " + r);
6492         }
6493 
6494         if (!oomAdjusted) {
6495             mAm.enqueueOomAdjTargetLocked(r.app);
6496             if (!enqueueOomAdj) {
6497                 mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_STOP_SERVICE);
6498             }
6499         }
6500         if (r.bindings.size() > 0) {
6501             r.bindings.clear();
6502         }
6503 
6504         if (r.restarter instanceof ServiceRestarter) {
6505            ((ServiceRestarter)r.restarter).setService(null);
6506         }
6507 
6508         synchronized (mAm.mProcessStats.mLock) {
6509             final int memFactor = mAm.mProcessStats.getMemFactorLocked();
6510             if (r.tracker != null) {
6511                 final long now = SystemClock.uptimeMillis();
6512                 r.tracker.setStarted(false, memFactor, now);
6513                 r.tracker.setBound(false, memFactor, now);
6514                 if (r.executeNesting == 0) {
6515                     r.tracker.clearCurrentOwner(r, false);
6516                     r.tracker = null;
6517                 }
6518             }
6519         }
6520 
6521         smap.ensureNotStartingBackgroundLocked(r);
6522         updateNumForegroundServicesLocked();
6523     }
6524 
dropFgsNotificationStateLocked(ServiceRecord r)6525     private void dropFgsNotificationStateLocked(ServiceRecord r) {
6526         if (r.foregroundNoti == null) {
6527             return;
6528         }
6529 
6530         // If this is the only FGS using this notification, clear its FGS flag
6531         boolean shared = false;
6532         final ServiceMap smap = mServiceMap.get(r.userId);
6533         if (smap != null) {
6534             // Is any other FGS using this notification?
6535             final int numServices = smap.mServicesByInstanceName.size();
6536             for (int i = 0; i < numServices; i++) {
6537                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
6538                 if (sr == r) {
6539                     continue;
6540                 }
6541                 if (sr.isForeground
6542                         && r.foregroundId == sr.foregroundId
6543                         && r.appInfo.packageName.equals(sr.appInfo.packageName)) {
6544                     shared = true;
6545                     break;
6546                 }
6547             }
6548         } else {
6549             Slog.wtf(TAG, "FGS " + r + " not found!");
6550         }
6551 
6552         // No other FGS is sharing this notification, so we're done with it
6553         if (!shared) {
6554             r.stripForegroundServiceFlagFromNotification();
6555         }
6556     }
6557 
6558     /**
6559      * @return The ServiceBindingOomAdjPolicy used in this removal.
6560      */
6561     @ServiceBindingOomAdjPolicy
removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp, ActivityServiceConnectionsHolder skipAct, boolean enqueueOomAdj)6562     int removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
6563             ActivityServiceConnectionsHolder skipAct, boolean enqueueOomAdj) {
6564         IBinder binder = c.conn.asBinder();
6565         AppBindRecord b = c.binding;
6566         ServiceRecord s = b.service;
6567         @ServiceBindingOomAdjPolicy int serviceBindingOomAdjPolicy =
6568                 SERVICE_BIND_OOMADJ_POLICY_LEGACY;
6569         ArrayList<ConnectionRecord> clist = s.getConnections().get(binder);
6570         if (clist != null) {
6571             clist.remove(c);
6572             if (clist.size() == 0) {
6573                 s.removeConnection(binder);
6574             }
6575         }
6576         b.connections.remove(c);
6577         c.stopAssociation();
6578         if (c.activity != null && c.activity != skipAct) {
6579             c.activity.removeConnection(c);
6580         }
6581         if (b.client != skipApp) {
6582             final ProcessServiceRecord psr = b.client.mServices;
6583             psr.removeConnection(c);
6584             if (c.hasFlag(Context.BIND_ABOVE_CLIENT)) {
6585                 psr.updateHasAboveClientLocked();
6586             }
6587             // If this connection requested allowlist management, see if we should
6588             // now clear that state.
6589             if (c.hasFlag(BIND_ALLOW_WHITELIST_MANAGEMENT)) {
6590                 s.updateAllowlistManager();
6591                 if (!s.allowlistManager && s.app != null) {
6592                     updateAllowlistManagerLocked(s.app.mServices);
6593                 }
6594             }
6595             // And do the same for bg activity starts ability.
6596             if (c.hasFlag(Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS)) {
6597                 s.updateIsAllowedBgActivityStartsByBinding();
6598             }
6599             // And for almost perceptible exceptions.
6600             if (c.hasFlag(Context.BIND_ALMOST_PERCEPTIBLE)) {
6601                 psr.updateHasTopStartedAlmostPerceptibleServices();
6602             }
6603             if (s.app != null) {
6604                 updateServiceClientActivitiesLocked(s.app.mServices, c, true);
6605             }
6606         }
6607         clist = mServiceConnections.get(binder);
6608         if (clist != null) {
6609             clist.remove(c);
6610             if (clist.size() == 0) {
6611                 mServiceConnections.remove(binder);
6612             }
6613         }
6614 
6615         mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
6616                 s.appInfo.longVersionCode, s.instanceName, s.processName);
6617 
6618         if (b.connections.size() == 0) {
6619             b.intent.apps.remove(b.client);
6620         }
6621 
6622         if (!c.serviceDead) {
6623             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
6624                     + ": shouldUnbind=" + b.intent.hasBound);
6625             if (s.app != null && s.app.isThreadReady() && b.intent.apps.size() == 0
6626                     && b.intent.hasBound) {
6627                 serviceBindingOomAdjPolicy = getServiceBindingOomAdjPolicyForRemovalLocked(b.client,
6628                         s.app, c);
6629                 final boolean skipOomAdj = (serviceBindingOomAdjPolicy
6630                         & SERVICE_BIND_OOMADJ_POLICY_SKIP_OOM_UPDATE_ON_CONNECT) != 0;
6631                 try {
6632                     bumpServiceExecutingLocked(s, false, "unbind",
6633                             skipOomAdj ? OOM_ADJ_REASON_NONE : OOM_ADJ_REASON_UNBIND_SERVICE,
6634                             skipOomAdj /* skipTimeoutIfPossible */);
6635                     if (b.client != s.app && c.notHasFlag(Context.BIND_WAIVE_PRIORITY)
6636                             && s.app.mState.getSetProcState() <= PROCESS_STATE_HEAVY_WEIGHT) {
6637                         // If this service's process is not already in the cached list,
6638                         // then update it in the LRU list here because this may be causing
6639                         // it to go down there and we want it to start out near the top.
6640                         mAm.updateLruProcessLocked(s.app, false, null);
6641                     }
6642                     b.intent.hasBound = false;
6643                     // Assume the client doesn't want to know about a rebind;
6644                     // we will deal with that later if it asks for one.
6645                     b.intent.doRebind = false;
6646                     s.app.getThread().scheduleUnbindService(s, b.intent.intent.getIntent());
6647                 } catch (Exception e) {
6648                     Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
6649                     serviceProcessGoneLocked(s, enqueueOomAdj);
6650                 }
6651             }
6652 
6653             // If unbound while waiting to start and there is no connection left in this service,
6654             // remove the pending service
6655             if (s.getConnections().isEmpty()) {
6656                 mPendingServices.remove(s);
6657                 mPendingBringups.remove(s);
6658             }
6659 
6660             if (c.hasFlag(Context.BIND_AUTO_CREATE)) {
6661                 boolean hasAutoCreate = s.hasAutoCreateConnections();
6662                 if (!hasAutoCreate) {
6663                     if (s.tracker != null) {
6664                         synchronized (mAm.mProcessStats.mLock) {
6665                             s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
6666                                     SystemClock.uptimeMillis());
6667                         }
6668                     }
6669                 }
6670                 bringDownServiceIfNeededLocked(s, true, hasAutoCreate, enqueueOomAdj,
6671                         "removeConnection");
6672             }
6673         }
6674         return serviceBindingOomAdjPolicy;
6675     }
6676 
serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res, boolean enqueueOomAdj, Intent intent)6677     void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res,
6678             boolean enqueueOomAdj, Intent intent) {
6679         boolean inDestroying = mDestroyingServices.contains(r);
6680         if (r != null) {
6681             boolean skipOomAdj = false;
6682             boolean needOomAdj = false;
6683             if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
6684                 // This is a call from a service start...  take care of
6685                 // book-keeping.
6686                 r.callStart = true;
6687 
6688                 // Set the result to startCommandResult.
6689                 // START_TASK_REMOVED_COMPLETE is _not_ a result from onStartCommand(), so
6690                 // let's ignore.
6691                 if (res != Service.START_TASK_REMOVED_COMPLETE) {
6692                     r.startCommandResult = res;
6693                 }
6694                 switch (res) {
6695                     case Service.START_STICKY_COMPATIBILITY:
6696                     case Service.START_STICKY: {
6697                         // We are done with the associated start arguments.
6698                         r.findDeliveredStart(startId, false, true);
6699                         // Don't stop if killed.
6700                         r.stopIfKilled = false;
6701                         break;
6702                     }
6703                     case Service.START_NOT_STICKY: {
6704                         // We are done with the associated start arguments.
6705                         r.findDeliveredStart(startId, false, true);
6706                         if (r.getLastStartId() == startId) {
6707                             // There is no more work, and this service
6708                             // doesn't want to hang around if killed.
6709                             r.stopIfKilled = true;
6710                         }
6711                         break;
6712                     }
6713                     case Service.START_REDELIVER_INTENT: {
6714                         // We'll keep this item until they explicitly
6715                         // call stop for it, but keep track of the fact
6716                         // that it was delivered.
6717                         ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
6718                         if (si != null) {
6719                             si.deliveryCount = 0;
6720                             si.doneExecutingCount++;
6721                             // Don't stop if killed.
6722                             r.stopIfKilled = true;
6723                         }
6724                         break;
6725                     }
6726                     case Service.START_TASK_REMOVED_COMPLETE: {
6727                         // Special processing for onTaskRemoved().  Don't
6728                         // impact normal onStartCommand() processing.
6729                         r.findDeliveredStart(startId, true, true);
6730                         break;
6731                     }
6732                     default:
6733                         throw new IllegalArgumentException(
6734                                 "Unknown service start result: " + res);
6735                 }
6736                 if (res == Service.START_STICKY_COMPATIBILITY) {
6737                     r.callStart = false;
6738                 }
6739             } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
6740                 // This is the final call from destroying the service...  we should
6741                 // actually be getting rid of the service at this point.  Do some
6742                 // validation of its state, and ensure it will be fully removed.
6743                 if (!inDestroying) {
6744                     // Not sure what else to do with this...  if it is not actually in the
6745                     // destroying list, we don't need to make sure to remove it from it.
6746                     // If the app is null, then it was probably removed because the process died,
6747                     // otherwise wtf
6748                     if (r.app != null) {
6749                         Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
6750                                 + r + ", app=" + r.app);
6751                     }
6752                 } else if (r.executeNesting != 1) {
6753                     Slog.w(TAG, "Service done with onDestroy, but executeNesting="
6754                             + r.executeNesting + ": " + r);
6755                     // Fake it to keep from ANR due to orphaned entry.
6756                     r.executeNesting = 1;
6757                 }
6758                 // The service is done, force an oom adj update.
6759                 needOomAdj = true;
6760             }
6761             final long origId = mAm.mInjector.clearCallingIdentity();
6762             serviceDoneExecutingLocked(r, inDestroying, inDestroying, enqueueOomAdj,
6763                     !Flags.serviceBindingOomAdjPolicy() || r.wasOomAdjUpdated() || needOomAdj
6764                     ? OOM_ADJ_REASON_EXECUTING_SERVICE : OOM_ADJ_REASON_NONE);
6765             mAm.mInjector.restoreCallingIdentity(origId);
6766         } else {
6767             Slog.w(TAG, "Done executing unknown service from pid "
6768                     + mAm.mInjector.getCallingPid());
6769         }
6770     }
6771 
serviceProcessGoneLocked(ServiceRecord r, boolean enqueueOomAdj)6772     private void serviceProcessGoneLocked(ServiceRecord r, boolean enqueueOomAdj) {
6773         if (r.tracker != null) {
6774             synchronized (mAm.mProcessStats.mLock) {
6775                 final int memFactor = mAm.mProcessStats.getMemFactorLocked();
6776                 final long now = SystemClock.uptimeMillis();
6777                 r.tracker.setExecuting(false, memFactor, now);
6778                 r.tracker.setForeground(false, memFactor, now);
6779                 r.tracker.setBound(false, memFactor, now);
6780                 r.tracker.setStarted(false, memFactor, now);
6781             }
6782         }
6783         serviceDoneExecutingLocked(r, true, true, enqueueOomAdj, OOM_ADJ_REASON_PROCESS_END);
6784     }
6785 
serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, boolean finishing, boolean enqueueOomAdj, @OomAdjReason int oomAdjReason)6786     private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
6787             boolean finishing, boolean enqueueOomAdj, @OomAdjReason int oomAdjReason) {
6788         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
6789                 + ": nesting=" + r.executeNesting
6790                 + ", inDestroying=" + inDestroying + ", app=" + r.app);
6791         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
6792                 "<<< DONE EXECUTING " + r.shortInstanceName);
6793         r.executeNesting--;
6794         if (r.executeNesting <= 0) {
6795             if (r.app != null) {
6796                 final ProcessServiceRecord psr = r.app.mServices;
6797                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
6798                         "Nesting at 0 of " + r.shortInstanceName);
6799                 psr.setExecServicesFg(false);
6800                 psr.stopExecutingService(r);
6801                 if (psr.numberOfExecutingServices() == 0) {
6802                     if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
6803                             "No more executingServices of " + r.shortInstanceName);
6804                     if (r.app.mPid != 0) mActiveServiceAnrTimer.cancel(r.app);
6805                 } else if (r.executeFg) {
6806                     // Need to re-evaluate whether the app still needs to be in the foreground.
6807                     for (int i = psr.numberOfExecutingServices() - 1; i >= 0; i--) {
6808                         if (psr.getExecutingServiceAt(i).executeFg) {
6809                             psr.setExecServicesFg(true);
6810                             break;
6811                         }
6812                     }
6813                 }
6814                 if (inDestroying) {
6815                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
6816                             "doneExecuting remove destroying " + r);
6817                     mDestroyingServices.remove(r);
6818                     r.bindings.clear();
6819                 }
6820                 if (oomAdjReason != OOM_ADJ_REASON_NONE) {
6821                     if (enqueueOomAdj) {
6822                         mAm.enqueueOomAdjTargetLocked(r.app);
6823                     } else {
6824                         mAm.updateOomAdjLocked(r.app, oomAdjReason);
6825                     }
6826                 } else {
6827                     // Skip oom adj if it wasn't bumped during the bumpServiceExecutingLocked()
6828                 }
6829                 r.updateOomAdjSeq();
6830             }
6831             r.executeFg = false;
6832             if (r.tracker != null) {
6833                 synchronized (mAm.mProcessStats.mLock) {
6834                     final int memFactor = mAm.mProcessStats.getMemFactorLocked();
6835                     final long now = SystemClock.uptimeMillis();
6836                     r.tracker.setExecuting(false, memFactor, now);
6837                     r.tracker.setForeground(false, memFactor, now);
6838                     if (finishing) {
6839                         r.tracker.clearCurrentOwner(r, false);
6840                         r.tracker = null;
6841                     }
6842                 }
6843             }
6844             if (finishing) {
6845                 if (r.app != null && !r.app.isPersistent()) {
6846                     stopServiceAndUpdateAllowlistManagerLocked(r);
6847                 }
6848                 r.setProcess(null, null, 0, null);
6849             }
6850         }
6851     }
6852 
attachApplicationLocked(ProcessRecord proc, String processName)6853     boolean attachApplicationLocked(ProcessRecord proc, String processName)
6854             throws RemoteException {
6855         boolean didSomething = false;
6856 
6857         // Update the app background restriction of the caller
6858         proc.mState.setBackgroundRestricted(appRestrictedAnyInBackground(
6859                 proc.uid, proc.info.packageName));
6860 
6861         // Collect any services that are waiting for this process to come up.
6862         if (mPendingServices.size() > 0) {
6863             ServiceRecord sr = null;
6864             try {
6865                 for (int i=0; i<mPendingServices.size(); i++) {
6866                     sr = mPendingServices.get(i);
6867                     if (proc != sr.isolationHostProc && (proc.uid != sr.appInfo.uid
6868                             || !processName.equals(sr.processName))) {
6869                         continue;
6870                     }
6871 
6872                     final IApplicationThread thread = proc.getThread();
6873                     final int pid = proc.getPid();
6874                     final UidRecord uidRecord = proc.getUidRecord();
6875                     mPendingServices.remove(i);
6876                     i--;
6877                     proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
6878                             mAm.mProcessStats);
6879                     try {
6880                         if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
6881                             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
6882                                     "realStartServiceLocked: " + sr.shortInstanceName);
6883                         }
6884                         realStartServiceLocked(sr, proc, thread, pid, uidRecord, sr.createdFromFg,
6885                                 true, SERVICE_BIND_OOMADJ_POLICY_LEGACY);
6886                     } finally {
6887                         Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6888                     }
6889                     didSomething = true;
6890                     if (!isServiceNeededLocked(sr, false, false)) {
6891                         // We were waiting for this service to start, but it is actually no
6892                         // longer needed.  This could happen because bringDownServiceIfNeeded
6893                         // won't bring down a service that is pending...  so now the pending
6894                         // is done, so let's drop it.
6895                         bringDownServiceLocked(sr, true);
6896                     }
6897                     /* Will be a no-op if nothing pending */
6898                     mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_START_SERVICE);
6899                 }
6900             } catch (RemoteException e) {
6901                 Slog.w(TAG, "Exception in new application when starting service "
6902                         + sr.shortInstanceName, e);
6903                 throw e;
6904             }
6905         }
6906         // Also, if there are any services that are waiting to restart and
6907         // would run in this process, now is a good time to start them.  It would
6908         // be weird to bring up the process but arbitrarily not let the services
6909         // run at this point just because their restart time hasn't come up.
6910         if (mRestartingServices.size() > 0) {
6911             ServiceRecord sr;
6912             boolean didImmediateRestart = false;
6913             for (int i=0; i<mRestartingServices.size(); i++) {
6914                 sr = mRestartingServices.get(i);
6915                 if (proc != sr.isolationHostProc && (proc.uid != sr.appInfo.uid
6916                         || !processName.equals(sr.processName))) {
6917                     continue;
6918                 }
6919                 mAm.mHandler.removeCallbacks(sr.restarter);
6920                 mAm.mHandler.post(sr.restarter);
6921                 didImmediateRestart = true;
6922             }
6923             if (didImmediateRestart) {
6924                 // Since we kicked off all its pending restarts, there could be some open slots
6925                 // in the pending restarts list, schedule a check on it. We are posting to the same
6926                 // handler, so by the time of the check, those immediate restarts should be done.
6927                 mAm.mHandler.post(() -> {
6928                     final long now = SystemClock.uptimeMillis();
6929                     synchronized (mAm) {
6930                         rescheduleServiceRestartIfPossibleLocked(
6931                                 getExtraRestartTimeInBetweenLocked(),
6932                                 mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN,
6933                                 "other", now);
6934                     }
6935                 });
6936             }
6937         }
6938         return didSomething;
6939     }
6940 
processStartTimedOutLocked(ProcessRecord proc)6941     void processStartTimedOutLocked(ProcessRecord proc) {
6942         boolean needOomAdj = false;
6943         for (int i = 0, size = mPendingServices.size(); i < size; i++) {
6944             ServiceRecord sr = mPendingServices.get(i);
6945             if ((proc.uid == sr.appInfo.uid
6946                     && proc.processName.equals(sr.processName))
6947                     || sr.isolationHostProc == proc) {
6948                 Slog.w(TAG, "Forcing bringing down service: " + sr);
6949                 sr.isolationHostProc = null;
6950                 mPendingServices.remove(i);
6951                 size = mPendingServices.size();
6952                 i--;
6953                 needOomAdj = true;
6954                 bringDownServiceLocked(sr, true);
6955             }
6956         }
6957         if (needOomAdj) {
6958             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_PROCESS_END);
6959         }
6960     }
6961 
collectPackageServicesLocked(String packageName, Set<String> filterByClasses, boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services)6962     private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
6963             boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
6964         boolean didSomething = false;
6965         for (int i = services.size() - 1; i >= 0; i--) {
6966             ServiceRecord service = services.valueAt(i);
6967             final boolean sameComponent = packageName == null
6968                     || (service.packageName.equals(packageName)
6969                         && (filterByClasses == null
6970                             || filterByClasses.contains(service.name.getClassName())));
6971             if (sameComponent
6972                     && (service.app == null || evenPersistent || !service.app.isPersistent())) {
6973                 if (!doit) {
6974                     return true;
6975                 }
6976                 didSomething = true;
6977                 Slog.i(TAG, "  Force stopping service " + service);
6978                 if (service.app != null && !service.app.isPersistent()) {
6979                     stopServiceAndUpdateAllowlistManagerLocked(service);
6980                 }
6981                 service.setProcess(null, null, 0, null);
6982                 service.isolationHostProc = null;
6983                 if (mTmpCollectionResults == null) {
6984                     mTmpCollectionResults = new ArrayList<>();
6985                 }
6986                 mTmpCollectionResults.add(service);
6987             }
6988         }
6989         return didSomething;
6990     }
6991 
bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, int userId, boolean evenPersistent, boolean fullStop, boolean doit)6992     boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
6993             int userId, boolean evenPersistent, boolean fullStop, boolean doit) {
6994         boolean didSomething = false;
6995 
6996         if (mTmpCollectionResults != null) {
6997             mTmpCollectionResults.clear();
6998         }
6999 
7000         if (userId == UserHandle.USER_ALL) {
7001             for (int i = mServiceMap.size() - 1; i >= 0; i--) {
7002                 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
7003                         evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
7004                 if (!doit && didSomething) {
7005                     return true;
7006                 }
7007                 if (doit && filterByClasses == null) {
7008                     forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
7009                 }
7010             }
7011         } else {
7012             ServiceMap smap = mServiceMap.get(userId);
7013             if (smap != null) {
7014                 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
7015                 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
7016                         evenPersistent, doit, items);
7017             }
7018             if (doit && filterByClasses == null) {
7019                 forceStopPackageLocked(packageName, userId);
7020             }
7021         }
7022 
7023         if (mTmpCollectionResults != null) {
7024             final int size = mTmpCollectionResults.size();
7025             for (int i = size - 1; i >= 0; i--) {
7026                 bringDownServiceLocked(mTmpCollectionResults.get(i), true);
7027             }
7028             if (size > 0) {
7029                 mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_COMPONENT_DISABLED);
7030             }
7031             if (fullStop && !mTmpCollectionResults.isEmpty()) {
7032                 // if we're tearing down the app's entire service state, account for possible
7033                 // races around FGS notifications by explicitly tidying up in a separate
7034                 // pass post-shutdown
7035                 final ArrayList<ServiceRecord> allServices =
7036                         (ArrayList<ServiceRecord>) mTmpCollectionResults.clone();
7037                 mAm.mHandler.postDelayed(() -> {
7038                     for (int i = 0; i < allServices.size(); i++) {
7039                         allServices.get(i).cancelNotification();
7040                     }
7041                 }, 250L);
7042             }
7043             mTmpCollectionResults.clear();
7044         }
7045 
7046         return didSomething;
7047     }
7048 
7049     @GuardedBy("mAm")
signalForegroundServiceObserversLocked(ServiceRecord r)7050     private void signalForegroundServiceObserversLocked(ServiceRecord r) {
7051         final int num = mFgsObservers.beginBroadcast();
7052         for (int i = 0; i < num; i++) {
7053             try {
7054                 mFgsObservers.getBroadcastItem(i).onForegroundStateChanged(r,
7055                         r.appInfo.packageName, r.userId, r.isForeground);
7056             } catch (RemoteException e) {
7057                 // Will be unregistered automatically by RemoteCallbackList's dead-object
7058                 // tracking, so nothing we need to do here.
7059             }
7060         }
7061         mFgsObservers.finishBroadcast();
7062     }
7063 
7064     @GuardedBy("mAm")
registerForegroundServiceObserverLocked(final int callingUid, IForegroundServiceObserver callback)7065     boolean registerForegroundServiceObserverLocked(final int callingUid,
7066             IForegroundServiceObserver callback) {
7067         // We always tell the newly-registered observer about any current FGSes.  The
7068         // most common case for this is a SysUI crash & relaunch; it needs to
7069         // reconstruct its tracking of stoppable-FGS-hosting apps.
7070         try {
7071             final int mapSize = mServiceMap.size();
7072             for (int mapIndex = 0; mapIndex < mapSize; mapIndex++) {
7073                 final ServiceMap smap = mServiceMap.valueAt(mapIndex);
7074                 if (smap != null) {
7075                     final int numServices = smap.mServicesByInstanceName.size();
7076                     for (int i = 0; i < numServices; i++) {
7077                         final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
7078                         if (sr.isForeground && callingUid == sr.appInfo.uid) {
7079                             callback.onForegroundStateChanged(sr, sr.appInfo.packageName,
7080                                     sr.userId, true);
7081                         }
7082                     }
7083                 }
7084             }
7085             // Callback is fine, go ahead and record it
7086             mFgsObservers.register(callback);
7087         } catch (RemoteException e) {
7088             // Whoops, something wrong with the callback.  Don't register it, and
7089             // report error back to the caller.
7090             Slog.e(TAG_SERVICE, "Bad FGS observer from uid " + callingUid);
7091             return false;
7092         }
7093 
7094         return true;
7095     }
7096 
forceStopPackageLocked(String packageName, int userId)7097     void forceStopPackageLocked(String packageName, int userId) {
7098         ServiceMap smap = mServiceMap.get(userId);
7099         if (smap != null && smap.mActiveForegroundApps.size() > 0) {
7100             for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
7101                 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
7102                 if (aa.mPackageName.equals(packageName)) {
7103                     smap.mActiveForegroundApps.removeAt(i);
7104                     smap.mActiveForegroundAppsChanged = true;
7105                 }
7106             }
7107             if (smap.mActiveForegroundAppsChanged) {
7108                 requestUpdateActiveForegroundAppsLocked(smap, 0);
7109             }
7110         }
7111         for (int i = mPendingBringups.size() - 1; i >= 0; i--) {
7112             ServiceRecord r = mPendingBringups.keyAt(i);
7113             if (TextUtils.equals(r.packageName, packageName) && r.userId == userId) {
7114                 mPendingBringups.removeAt(i);
7115             }
7116         }
7117         removeServiceRestartBackoffEnabledLocked(packageName);
7118         removeServiceNotificationDeferralsLocked(packageName, userId);
7119     }
7120 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)7121     void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
7122         ArrayList<ServiceRecord> services = new ArrayList<>();
7123         ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
7124         for (int i = alls.size() - 1; i >= 0; i--) {
7125             ServiceRecord sr = alls.valueAt(i);
7126             if (sr.packageName.equals(component.getPackageName())) {
7127                 services.add(sr);
7128             }
7129         }
7130 
7131         // Take care of any running services associated with the app.
7132         boolean needOomAdj = false;
7133         for (int i = services.size() - 1; i >= 0; i--) {
7134             ServiceRecord sr = services.get(i);
7135             if (sr.startRequested) {
7136                 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
7137                     Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
7138                     needOomAdj = true;
7139                     stopServiceLocked(sr, true);
7140                 } else {
7141                     sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
7142                             sr.getLastStartId(), baseIntent, null, 0, null, null,
7143                             ActivityManager.PROCESS_STATE_UNKNOWN));
7144                     if (sr.app != null && sr.app.isThreadReady()) {
7145                         // We always run in the foreground, since this is called as
7146                         // part of the "remove task" UI operation.
7147                         try {
7148                             sendServiceArgsLocked(sr, true, false);
7149                         } catch (TransactionTooLargeException e) {
7150                             // Ignore, keep going.
7151                         }
7152                     }
7153                 }
7154             }
7155         }
7156         if (needOomAdj) {
7157             mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_REMOVE_TASK);
7158         }
7159     }
7160 
killServicesLocked(ProcessRecord app, boolean allowRestart)7161     final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
7162         final ProcessServiceRecord psr = app.mServices;
7163         // Report disconnected services.
7164         if (false) {
7165             // XXX we are letting the client link to the service for
7166             // death notifications.
7167             int numberOfRunningServices = psr.numberOfRunningServices();
7168             for (int sIndex = 0; sIndex < numberOfRunningServices; sIndex++) {
7169                 ServiceRecord r = psr.getRunningServiceAt(sIndex);
7170                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
7171                 for (int conni = connections.size() - 1; conni >= 0; conni--) {
7172                     ArrayList<ConnectionRecord> cl = connections.valueAt(conni);
7173                     for (int i = 0; i < cl.size(); i++) {
7174                         ConnectionRecord c = cl.get(i);
7175                         if (c.binding.client != app) {
7176                             try {
7177                                 //c.conn.connected(r.className, null);
7178                             } catch (Exception e) {
7179                                 // todo: this should be asynchronous!
7180                                 Slog.w(TAG, "Exception thrown disconnected servce "
7181                                         + r.shortInstanceName
7182                                         + " from app " + app.processName, e);
7183                             }
7184                         }
7185                     }
7186                 }
7187             }
7188         }
7189 
7190         // Clean up any connections this application has to other services.
7191         for (int i = psr.numberOfConnections() - 1; i >= 0; i--) {
7192             ConnectionRecord r = psr.getConnectionAt(i);
7193             removeConnectionLocked(r, app, null, true);
7194         }
7195         updateServiceConnectionActivitiesLocked(psr);
7196         psr.removeAllConnections();
7197         psr.removeAllSdkSandboxConnections();
7198 
7199         psr.mAllowlistManager = false;
7200 
7201         // Clear app state from services.
7202         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
7203             ServiceRecord sr = psr.getRunningServiceAt(i);
7204             mAm.mBatteryStatsService.noteServiceStopLaunch(sr.appInfo.uid, sr.name.getPackageName(),
7205                     sr.name.getClassName());
7206             if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
7207                 sr.app.mServices.stopService(sr);
7208                 sr.app.mServices.updateBoundClientUids();
7209             }
7210             sr.setProcess(null, null, 0, null);
7211             sr.isolationHostProc = null;
7212             sr.executeNesting = 0;
7213             synchronized (mAm.mProcessStats.mLock) {
7214                 sr.forceClearTracker();
7215             }
7216             if (mDestroyingServices.remove(sr)) {
7217                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
7218             }
7219 
7220             final int numClients = sr.bindings.size();
7221             for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
7222                 IntentBindRecord b = sr.bindings.valueAt(bindingi);
7223                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
7224                         + ": shouldUnbind=" + b.hasBound);
7225                 b.binder = null;
7226                 b.requested = b.received = b.hasBound = false;
7227                 // If this binding is coming from a cached process and is asking to keep
7228                 // the service created, then we'll kill the cached process as well -- we
7229                 // don't want to be thrashing around restarting processes that are only
7230                 // there to be cached.
7231                 for (int appi=b.apps.size()-1; appi>=0; appi--) {
7232                     final ProcessRecord proc = b.apps.keyAt(appi);
7233                     // If the process is already gone, skip it.
7234                     if (proc.isKilledByAm() || proc.getThread() == null) {
7235                         continue;
7236                     }
7237                     // Only do this for processes that have an auto-create binding;
7238                     // otherwise the binding can be left, because it won't cause the
7239                     // service to restart.
7240                     final AppBindRecord abind = b.apps.valueAt(appi);
7241                     boolean hasCreate = false;
7242                     for (int conni = abind.connections.size() - 1; conni >= 0; conni--) {
7243                         ConnectionRecord conn = abind.connections.valueAt(conni);
7244                         if (conn.hasFlag(Context.BIND_AUTO_CREATE)
7245                                 && conn.notHasFlag(Context.BIND_ALLOW_OOM_MANAGEMENT
7246                                 |Context.BIND_WAIVE_PRIORITY)) {
7247                             hasCreate = true;
7248                             break;
7249                         }
7250                     }
7251                     if (!hasCreate) {
7252                         continue;
7253                     }
7254                     // XXX turned off for now until we have more time to get a better policy.
7255                     /*
7256                     if (false && proc != null && !proc.isPersistent() && proc.getThread() != null
7257                             && proc.getPid() != 0 && proc.getPid() != ActivityManagerService.MY_PID
7258                             && proc.mState.getSetProcState() >= PROCESS_STATE_LAST_ACTIVITY) {
7259                         proc.killLocked("bound to service " + sr.shortInstanceName
7260                                 + " in dying proc " + (app != null ? app.processName : "??"),
7261                                 ApplicationExitInfo.REASON_OTHER, true);
7262                     }
7263                     */
7264                 }
7265             }
7266         }
7267 
7268         ServiceMap smap = getServiceMapLocked(app.userId);
7269 
7270         // Now do remaining service cleanup.
7271         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
7272             ServiceRecord sr = psr.getRunningServiceAt(i);
7273 
7274             // Unless the process is persistent, this process record is going away,
7275             // so make sure the service is cleaned out of it.
7276             if (!app.isPersistent()) {
7277                 psr.stopService(sr);
7278                 psr.updateBoundClientUids();
7279             }
7280 
7281             // Check: if the service listed for the app is not one
7282             // we actually are maintaining, just let it drop.
7283             final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
7284             if (curRec != sr) {
7285                 if (curRec != null) {
7286                     Slog.wtf(TAG, "Service " + sr + " in process " + app
7287                             + " not same as in map: " + curRec);
7288                 }
7289                 continue;
7290             }
7291 
7292             // Any services running in the application may need to be placed
7293             // back in the pending list.
7294             if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
7295                     && (sr.serviceInfo.applicationInfo.flags
7296                         &ApplicationInfo.FLAG_PERSISTENT) == 0) {
7297                 Slog.w(TAG, "Service crashed " + sr.crashCount
7298                         + " times, stopping: " + sr);
7299                 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
7300                         sr.userId, sr.crashCount, sr.shortInstanceName,
7301                         sr.app != null ? sr.app.getPid() : -1);
7302                 bringDownServiceLocked(sr, true);
7303             } else if (!allowRestart
7304                     || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
7305                 bringDownServiceLocked(sr, true);
7306             } else {
7307                 final boolean scheduled = scheduleServiceRestartLocked(sr, true /* allowCancel */);
7308 
7309                 // Should the service remain running?  Note that in the
7310                 // extreme case of so many attempts to deliver a command
7311                 // that it failed we also will stop it here.
7312                 if (!scheduled) {
7313                     bringDownServiceLocked(sr, true);
7314                 } else if (sr.canStopIfKilled(false /* isStartCanceled */)) {
7315                     // Update to stopped state because the explicit start is gone. The service is
7316                     // scheduled to restart for other reason (e.g. connections) so we don't bring
7317                     // down it.
7318                     sr.startRequested = false;
7319                     if (sr.tracker != null) {
7320                         synchronized (mAm.mProcessStats.mLock) {
7321                             sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
7322                                     SystemClock.uptimeMillis());
7323                         }
7324                     }
7325                 }
7326             }
7327         }
7328 
7329         mAm.updateOomAdjPendingTargetsLocked(OOM_ADJ_REASON_STOP_SERVICE);
7330 
7331         if (!allowRestart) {
7332             psr.stopAllServices();
7333             psr.clearBoundClientUids();
7334 
7335             // Make sure there are no more restarting services for this process.
7336             for (int i=mRestartingServices.size()-1; i>=0; i--) {
7337                 ServiceRecord r = mRestartingServices.get(i);
7338                 if (r.processName.equals(app.processName) &&
7339                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
7340                     mRestartingServices.remove(i);
7341                     clearRestartingIfNeededLocked(r);
7342                 }
7343             }
7344             for (int i=mPendingServices.size()-1; i>=0; i--) {
7345                 ServiceRecord r = mPendingServices.get(i);
7346                 if (r.processName.equals(app.processName) &&
7347                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
7348                     mPendingServices.remove(i);
7349                 }
7350             }
7351             for (int i = mPendingBringups.size() - 1; i >= 0; i--) {
7352                 ServiceRecord r = mPendingBringups.keyAt(i);
7353                 if (r.processName.equals(app.processName)
7354                         && r.serviceInfo.applicationInfo.uid == app.info.uid) {
7355                     mPendingBringups.removeAt(i);
7356                 }
7357             }
7358         }
7359 
7360         // Make sure we have no more records on the stopping list.
7361         int i = mDestroyingServices.size();
7362         while (i > 0) {
7363             i--;
7364             ServiceRecord sr = mDestroyingServices.get(i);
7365             if (sr.app == app) {
7366                 synchronized (mAm.mProcessStats.mLock) {
7367                     sr.forceClearTracker();
7368                 }
7369                 mDestroyingServices.remove(i);
7370                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
7371             }
7372         }
7373 
7374         psr.stopAllExecutingServices();
7375         psr.noteScheduleServiceTimeoutPending(false);
7376     }
7377 
makeRunningServiceInfoLocked(ServiceRecord r)7378     ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
7379         ActivityManager.RunningServiceInfo info =
7380             new ActivityManager.RunningServiceInfo();
7381         info.service = r.name;
7382         if (r.app != null) {
7383             info.pid = r.app.getPid();
7384         }
7385         info.uid = r.appInfo.uid;
7386         info.process = r.processName;
7387         info.foreground = r.isForeground;
7388         info.activeSince = r.createRealTime;
7389         info.started = r.startRequested;
7390         info.clientCount = r.getConnections().size();
7391         info.crashCount = r.crashCount;
7392         info.lastActivityTime = r.lastActivity;
7393         if (r.isForeground) {
7394             info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
7395         }
7396         if (r.startRequested) {
7397             info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
7398         }
7399         if (r.app != null && r.app.getPid() == ActivityManagerService.MY_PID) {
7400             info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
7401         }
7402         if (r.app != null && r.app.isPersistent()) {
7403             info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
7404         }
7405 
7406         ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
7407         for (int conni = connections.size() - 1; conni >= 0; conni--) {
7408             ArrayList<ConnectionRecord> connl = connections.valueAt(conni);
7409             for (int i=0; i<connl.size(); i++) {
7410                 ConnectionRecord conn = connl.get(i);
7411                 if (conn.clientLabel != 0) {
7412                     info.clientPackage = conn.binding.client.info.packageName;
7413                     info.clientLabel = conn.clientLabel;
7414                     return info;
7415                 }
7416             }
7417         }
7418         return info;
7419     }
7420 
getRunningServiceInfoLocked(int maxNum, int flags, int callingUid, boolean allowed, boolean canInteractAcrossUsers)7421     List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
7422         int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
7423         ArrayList<ActivityManager.RunningServiceInfo> res
7424                 = new ArrayList<ActivityManager.RunningServiceInfo>();
7425 
7426         final long ident = mAm.mInjector.clearCallingIdentity();
7427         try {
7428             if (canInteractAcrossUsers) {
7429                 int[] users = mAm.mUserController.getUsers();
7430                 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
7431                     ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
7432                     for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
7433                         ServiceRecord sr = alls.valueAt(i);
7434                         res.add(makeRunningServiceInfoLocked(sr));
7435                     }
7436                 }
7437 
7438                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
7439                     ServiceRecord r = mRestartingServices.get(i);
7440                     ActivityManager.RunningServiceInfo info =
7441                             makeRunningServiceInfoLocked(r);
7442                     info.restarting = r.nextRestartTime;
7443                     res.add(info);
7444                 }
7445             } else {
7446                 int userId = UserHandle.getUserId(callingUid);
7447                 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
7448                 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
7449                     ServiceRecord sr = alls.valueAt(i);
7450 
7451                     if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
7452                         res.add(makeRunningServiceInfoLocked(sr));
7453                     }
7454                 }
7455 
7456                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
7457                     ServiceRecord r = mRestartingServices.get(i);
7458                     if (r.userId == userId
7459                         && (allowed || (r.app != null && r.app.uid == callingUid))) {
7460                         ActivityManager.RunningServiceInfo info =
7461                                 makeRunningServiceInfoLocked(r);
7462                         info.restarting = r.nextRestartTime;
7463                         res.add(info);
7464                     }
7465                 }
7466             }
7467         } finally {
7468             mAm.mInjector.restoreCallingIdentity(ident);
7469         }
7470 
7471         return res;
7472     }
7473 
getRunningServiceControlPanelLocked(ComponentName name)7474     public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
7475         int userId = UserHandle.getUserId(mAm.mInjector.getCallingUid());
7476         ServiceRecord r = getServiceByNameLocked(name, userId);
7477         if (r != null) {
7478             ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
7479             for (int conni = connections.size() - 1; conni >= 0; conni--) {
7480                 ArrayList<ConnectionRecord> conn = connections.valueAt(conni);
7481                 for (int i=0; i<conn.size(); i++) {
7482                     if (conn.get(i).clientIntent != null) {
7483                         return conn.get(i).clientIntent;
7484                     }
7485                 }
7486             }
7487         }
7488         return null;
7489     }
7490 
serviceTimeout(ProcessRecord proc)7491     void serviceTimeout(ProcessRecord proc) {
7492         try {
7493             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceTimeout()");
7494             TimeoutRecord timeoutRecord = null;
7495             synchronized (mAm) {
7496                 if (proc.isDebugging()) {
7497                     // The app's being debugged, ignore timeout.
7498                     mActiveServiceAnrTimer.discard(proc);
7499                     return;
7500                 }
7501                 final ProcessServiceRecord psr = proc.mServices;
7502                 if (psr.numberOfExecutingServices() == 0 || proc.getThread() == null
7503                         || proc.isKilled()) {
7504                     mActiveServiceAnrTimer.discard(proc);
7505                     return;
7506                 }
7507                 final long now = SystemClock.uptimeMillis();
7508                 final long maxTime =  now
7509                         - (psr.shouldExecServicesFg()
7510                         ? mAm.mConstants.SERVICE_TIMEOUT
7511                         : mAm.mConstants.SERVICE_BACKGROUND_TIMEOUT);
7512                 ServiceRecord timeout = null;
7513                 long nextTime = 0;
7514                 for (int i = psr.numberOfExecutingServices() - 1; i >= 0; i--) {
7515                     ServiceRecord sr = psr.getExecutingServiceAt(i);
7516                     if (sr.executingStart < maxTime) {
7517                         timeout = sr;
7518                         break;
7519                     }
7520                     if (sr.executingStart > nextTime) {
7521                         nextTime = sr.executingStart;
7522                     }
7523                 }
7524                 if (timeout != null && mAm.mProcessList.isInLruListLOSP(proc)) {
7525                     final AutoCloseable timer = mActiveServiceAnrTimer.accept(proc);
7526                     Slog.w(TAG, "Timeout executing service: " + timeout);
7527                     StringWriter sw = new StringWriter();
7528                     PrintWriter pw = new FastPrintWriter(sw, false, 1024);
7529                     pw.println(timeout);
7530                     timeout.dump(pw, "    ");
7531                     pw.close();
7532                     mLastAnrDump = sw.toString();
7533                     mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
7534                     mAm.mHandler.postDelayed(mLastAnrDumpClearer,
7535                             LAST_ANR_LIFETIME_DURATION_MSECS);
7536                     long waitedMillis = now - timeout.executingStart;
7537                     timeoutRecord = TimeoutRecord.forServiceExec(timeout.shortInstanceName,
7538                             waitedMillis).setExpiredTimer(timer);
7539                 } else {
7540                     mActiveServiceAnrTimer.discard(proc);
7541                     final long delay = psr.shouldExecServicesFg()
7542                                        ? (nextTime + mAm.mConstants.SERVICE_TIMEOUT) :
7543                                        (nextTime + mAm.mConstants.SERVICE_BACKGROUND_TIMEOUT)
7544                                        - SystemClock.uptimeMillis();
7545                     mActiveServiceAnrTimer.start(proc, delay);
7546                 }
7547             }
7548 
7549             if (timeoutRecord != null) {
7550                 mAm.mAnrHelper.appNotResponding(proc, timeoutRecord);
7551             }
7552         } finally {
7553             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7554         }
7555     }
7556 
serviceForegroundTimeout(ServiceRecord r)7557     void serviceForegroundTimeout(ServiceRecord r) {
7558         try {
7559             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceForegroundTimeout()");
7560             ProcessRecord app;
7561             // Create a TimeoutRecord .
7562             final String annotation = "Context.startForegroundService() did not then call "
7563                     + "Service.startForeground(): " + r;
7564             TimeoutRecord timeoutRecord = TimeoutRecord.forServiceStartWithEndTime(annotation,
7565                     SystemClock.uptimeMillis());
7566 
7567             timeoutRecord.mLatencyTracker.waitingOnAMSLockStarted();
7568             synchronized (mAm) {
7569                 timeoutRecord.mLatencyTracker.waitingOnAMSLockEnded();
7570                 if (!r.fgRequired || !r.fgWaiting || r.destroying) {
7571                     mServiceFGAnrTimer.discard(r);
7572                     return;
7573                 }
7574 
7575                 app = r.app;
7576                 if (app != null && app.isDebugging()) {
7577                     // The app's being debugged; let it ride
7578                     mServiceFGAnrTimer.discard(r);
7579                     return;
7580                 }
7581 
7582                 mServiceFGAnrTimer.accept(r);
7583 
7584                 if (DEBUG_BACKGROUND_CHECK) {
7585                     Slog.i(TAG, "Service foreground-required timeout for " + r);
7586                 }
7587                 r.fgWaiting = false;
7588                 stopServiceLocked(r, false);
7589             }
7590 
7591             if (app != null) {
7592 
7593                 Message msg = mAm.mHandler.obtainMessage(
7594                         ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_ANR_MSG);
7595                 SomeArgs args = SomeArgs.obtain();
7596                 args.arg1 = app;
7597                 args.arg2 = timeoutRecord;
7598                 msg.obj = args;
7599                 mAm.mHandler.sendMessageDelayed(msg,
7600                         mAm.mConstants.mServiceStartForegroundAnrDelayMs);
7601             }
7602         } finally {
7603             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7604         }
7605     }
7606 
serviceForegroundTimeoutANR(ProcessRecord app, TimeoutRecord timeoutRecord)7607     void serviceForegroundTimeoutANR(ProcessRecord app, TimeoutRecord timeoutRecord) {
7608         mAm.mAnrHelper.appNotResponding(app, timeoutRecord);
7609     }
7610 
updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo)7611     public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
7612         final int userId = UserHandle.getUserId(applicationInfo.uid);
7613         ServiceMap serviceMap = mServiceMap.get(userId);
7614         if (serviceMap != null) {
7615             ArrayMap<ComponentName, ServiceRecord> servicesByName
7616                     = serviceMap.mServicesByInstanceName;
7617             for (int j = servicesByName.size() - 1; j >= 0; j--) {
7618                 ServiceRecord serviceRecord = servicesByName.valueAt(j);
7619                 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
7620                     serviceRecord.appInfo = applicationInfo;
7621                     serviceRecord.serviceInfo.applicationInfo = applicationInfo;
7622                 }
7623             }
7624         }
7625     }
7626 
serviceForegroundCrash(ProcessRecord app, String serviceRecord, ComponentName service)7627     void serviceForegroundCrash(ProcessRecord app, String serviceRecord,
7628             ComponentName service) {
7629         mAm.crashApplicationWithTypeWithExtras(
7630                 app.uid, app.getPid(), app.info.packageName, app.userId,
7631                 "Context.startForegroundService() did not then call " + "Service.startForeground(): "
7632                     + serviceRecord, false /*force*/,
7633                 ForegroundServiceDidNotStartInTimeException.TYPE_ID,
7634                 ForegroundServiceDidNotStartInTimeException.createExtrasForService(service));
7635     }
7636 
7637     private static class ProcessAnrTimer extends AnrTimer<ProcessRecord> {
7638 
ProcessAnrTimer(ActivityManagerService am, int msg, String label)7639         ProcessAnrTimer(ActivityManagerService am, int msg, String label) {
7640             super(Objects.requireNonNull(am).mHandler, msg, label);
7641         }
7642 
ProcessAnrTimer(ActivityManagerService am, int msg, String label, @NonNull AnrTimer.Args args)7643         ProcessAnrTimer(ActivityManagerService am, int msg, String label,
7644                 @NonNull AnrTimer.Args args) {
7645             super(Objects.requireNonNull(am).mHandler, msg, label, args);
7646         }
7647 
7648         @Override
getPid(@onNull ProcessRecord proc)7649         public int getPid(@NonNull ProcessRecord proc) {
7650             return proc.getPid();
7651         }
7652 
7653         @Override
getUid(@onNull ProcessRecord proc)7654         public int getUid(@NonNull ProcessRecord proc) {
7655             return proc.uid;
7656         }
7657     }
7658 
7659     private static class ServiceAnrTimer extends AnrTimer<ServiceRecord> {
7660 
ServiceAnrTimer(ActivityManagerService am, int msg, String label)7661         ServiceAnrTimer(ActivityManagerService am, int msg, String label) {
7662             super(Objects.requireNonNull(am).mHandler, msg, label);
7663         }
7664 
7665         @Override
getPid(@onNull ServiceRecord service)7666         public int getPid(@NonNull ServiceRecord service) {
7667             return (service.app != null) ? service.app.getPid() : 0;
7668         }
7669 
7670         @Override
getUid(@onNull ServiceRecord service)7671         public int getUid(@NonNull ServiceRecord service) {
7672             return (service.appInfo != null) ? service.appInfo.uid : 0;
7673         }
7674     }
7675 
scheduleServiceTimeoutLocked(ProcessRecord proc)7676     void scheduleServiceTimeoutLocked(ProcessRecord proc) {
7677         if (proc.mServices.numberOfExecutingServices() == 0 || proc.getThread() == null) {
7678             return;
7679         }
7680         final long delay = proc.mServices.shouldExecServicesFg()
7681                 ? mAm.mConstants.SERVICE_TIMEOUT : mAm.mConstants.SERVICE_BACKGROUND_TIMEOUT;
7682         mActiveServiceAnrTimer.start(proc, delay);
7683         proc.mServices.noteScheduleServiceTimeoutPending(false);
7684     }
7685 
scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r)7686     void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
7687         if (r.app.mServices.numberOfExecutingServices() == 0 || r.app.getThread() == null) {
7688             return;
7689         }
7690         r.fgWaiting = true;
7691         mServiceFGAnrTimer.start(r, mAm.mConstants.mServiceStartForegroundTimeoutMs);
7692     }
7693 
7694     final class ServiceDumper {
7695         private final FileDescriptor fd;
7696         private final PrintWriter pw;
7697         private final String[] args;
7698         private final boolean dumpAll;
7699         private final String dumpPackage;
7700         private final ItemMatcher matcher;
7701         private final ArrayList<ServiceRecord> services = new ArrayList<>();
7702 
7703         private final long nowReal = SystemClock.elapsedRealtime();
7704 
7705         private boolean needSep = false;
7706         private boolean printedAnything = false;
7707         private boolean printed = false;
7708 
7709         /**
7710          * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
7711          * must be called with the lock held).
7712          */
ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)7713         ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
7714                 int opti, boolean dumpAll, String dumpPackage) {
7715             this.fd = fd;
7716             this.pw = pw;
7717             this.args = args;
7718             this.dumpAll = dumpAll;
7719             this.dumpPackage = dumpPackage;
7720             matcher = new ItemMatcher();
7721             matcher.build(args, opti);
7722 
7723             final int[] users = mAm.mUserController.getUsers();
7724             for (int user : users) {
7725                 ServiceMap smap = getServiceMapLocked(user);
7726                 if (smap.mServicesByInstanceName.size() > 0) {
7727                     for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
7728                         ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
7729                         if (!matcher.match(r, r.name)) {
7730                             continue;
7731                         }
7732                         if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
7733                             continue;
7734                         }
7735                         services.add(r);
7736                     }
7737                 }
7738             }
7739         }
7740 
dumpHeaderLocked()7741         private void dumpHeaderLocked() {
7742             pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
7743             if (mLastAnrDump != null) {
7744                 pw.println("  Last ANR service:");
7745                 pw.print(mLastAnrDump);
7746                 pw.println();
7747             }
7748         }
7749 
dumpLocked()7750         void dumpLocked() {
7751             dumpHeaderLocked();
7752 
7753             try {
7754                 int[] users = mAm.mUserController.getUsers();
7755                 for (int user : users) {
7756                     // Find the first service for this user.
7757                     int serviceIdx = 0;
7758                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
7759                         serviceIdx++;
7760                     }
7761                     printed = false;
7762                     if (serviceIdx < services.size()) {
7763                         needSep = false;
7764                         while (serviceIdx < services.size()) {
7765                             ServiceRecord r = services.get(serviceIdx);
7766                             serviceIdx++;
7767                             if (r.userId != user) {
7768                                 break;
7769                             }
7770                             dumpServiceLocalLocked(r);
7771                         }
7772                         needSep |= printed;
7773                     }
7774 
7775                     dumpUserRemainsLocked(user);
7776                 }
7777             } catch (Exception e) {
7778                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
7779             }
7780 
7781             dumpRemainsLocked();
7782         }
7783 
dumpWithClient()7784         void dumpWithClient() {
7785             synchronized(mAm) {
7786                 dumpHeaderLocked();
7787             }
7788 
7789             try {
7790                 int[] users = mAm.mUserController.getUsers();
7791                 for (int user : users) {
7792                     // Find the first service for this user.
7793                     int serviceIdx = 0;
7794                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
7795                         serviceIdx++;
7796                     }
7797                     printed = false;
7798                     if (serviceIdx < services.size()) {
7799                         needSep = false;
7800                         while (serviceIdx < services.size()) {
7801                             ServiceRecord r = services.get(serviceIdx);
7802                             serviceIdx++;
7803                             if (r.userId != user) {
7804                                 break;
7805                             }
7806                             synchronized(mAm) {
7807                                 dumpServiceLocalLocked(r);
7808                             }
7809                             dumpServiceClient(r);
7810                         }
7811                         needSep |= printed;
7812                     }
7813 
7814                     synchronized(mAm) {
7815                         dumpUserRemainsLocked(user);
7816                     }
7817                 }
7818             } catch (Exception e) {
7819                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
7820             }
7821 
7822             synchronized(mAm) {
7823                 dumpRemainsLocked();
7824             }
7825         }
7826 
dumpUserHeaderLocked(int user)7827         private void dumpUserHeaderLocked(int user) {
7828             if (!printed) {
7829                 if (printedAnything) {
7830                     pw.println();
7831                 }
7832                 pw.println("  User " + user + " active services:");
7833                 printed = true;
7834             }
7835             printedAnything = true;
7836             if (needSep) {
7837                 pw.println();
7838             }
7839         }
7840 
dumpServiceLocalLocked(ServiceRecord r)7841         private void dumpServiceLocalLocked(ServiceRecord r) {
7842             dumpUserHeaderLocked(r.userId);
7843             pw.print("  * ");
7844             pw.println(r);
7845             if (dumpAll) {
7846                 r.dump(pw, "    ");
7847                 needSep = true;
7848             } else {
7849                 pw.print("    app=");
7850                 pw.println(r.app);
7851                 pw.print("    created=");
7852                 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
7853                 pw.print(" started=");
7854                 pw.print(r.startRequested);
7855                 pw.print(" connections=");
7856                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
7857                 pw.println(connections.size());
7858                 if (connections.size() > 0) {
7859                     pw.println("    Connections:");
7860                     for (int conni = 0; conni < connections.size(); conni++) {
7861                         ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
7862                         for (int i = 0; i < clist.size(); i++) {
7863                             ConnectionRecord conn = clist.get(i);
7864                             pw.print("      ");
7865                             pw.print(conn.binding.intent.intent.getIntent()
7866                                     .toShortString(false, false, false, false));
7867                             pw.print(" -> ");
7868                             ProcessRecord proc = conn.binding.client;
7869                             pw.println(proc != null ? proc.toShortString() : "null");
7870                         }
7871                     }
7872                 }
7873             }
7874         }
7875 
dumpServiceClient(ServiceRecord r)7876         private void dumpServiceClient(ServiceRecord r) {
7877             final ProcessRecord proc = r.app;
7878             if (proc == null) {
7879                 return;
7880             }
7881             final IApplicationThread thread = proc.getThread();
7882             if (thread == null) {
7883                 return;
7884             }
7885             pw.println("    Client:");
7886             pw.flush();
7887             try {
7888                 TransferPipe tp = new TransferPipe();
7889                 try {
7890                     thread.dumpService(tp.getWriteFd(), r, args);
7891                     tp.setBufferPrefix("      ");
7892                     // Short timeout, since blocking here can
7893                     // deadlock with the application.
7894                     tp.go(fd, 2000);
7895                 } finally {
7896                     tp.kill();
7897                 }
7898             } catch (IOException e) {
7899                 pw.println("      Failure while dumping the service: " + e);
7900             } catch (RemoteException e) {
7901                 pw.println("      Got a RemoteException while dumping the service");
7902             }
7903             needSep = true;
7904         }
7905 
dumpUserRemainsLocked(int user)7906         private void dumpUserRemainsLocked(int user) {
7907             ServiceMap smap = getServiceMapLocked(user);
7908             printed = false;
7909             for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
7910                 ServiceRecord r = smap.mDelayedStartList.get(si);
7911                 if (!matcher.match(r, r.name)) {
7912                     continue;
7913                 }
7914                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
7915                     continue;
7916                 }
7917                 if (!printed) {
7918                     if (printedAnything) {
7919                         pw.println();
7920                     }
7921                     pw.println("  User " + user + " delayed start services:");
7922                     printed = true;
7923                 }
7924                 printedAnything = true;
7925                 pw.print("  * Delayed start "); pw.println(r);
7926             }
7927             printed = false;
7928             for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
7929                 ServiceRecord r = smap.mStartingBackground.get(si);
7930                 if (!matcher.match(r, r.name)) {
7931                     continue;
7932                 }
7933                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
7934                     continue;
7935                 }
7936                 if (!printed) {
7937                     if (printedAnything) {
7938                         pw.println();
7939                     }
7940                     pw.println("  User " + user + " starting in background:");
7941                     printed = true;
7942                 }
7943                 printedAnything = true;
7944                 pw.print("  * Starting bg "); pw.println(r);
7945             }
7946         }
7947 
dumpRemainsLocked()7948         private void dumpRemainsLocked() {
7949             if (mPendingServices.size() > 0) {
7950                 printed = false;
7951                 for (int i=0; i<mPendingServices.size(); i++) {
7952                     ServiceRecord r = mPendingServices.get(i);
7953                     if (!matcher.match(r, r.name)) {
7954                         continue;
7955                     }
7956                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
7957                         continue;
7958                     }
7959                     printedAnything = true;
7960                     if (!printed) {
7961                         if (needSep) pw.println();
7962                         needSep = true;
7963                         pw.println("  Pending services:");
7964                         printed = true;
7965                     }
7966                     pw.print("  * Pending "); pw.println(r);
7967                     r.dump(pw, "    ");
7968                 }
7969                 needSep = true;
7970             }
7971 
7972             if (mRestartingServices.size() > 0) {
7973                 printed = false;
7974                 for (int i=0; i<mRestartingServices.size(); i++) {
7975                     ServiceRecord r = mRestartingServices.get(i);
7976                     if (!matcher.match(r, r.name)) {
7977                         continue;
7978                     }
7979                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
7980                         continue;
7981                     }
7982                     printedAnything = true;
7983                     if (!printed) {
7984                         if (needSep) pw.println();
7985                         needSep = true;
7986                         pw.println("  Restarting services:");
7987                         printed = true;
7988                     }
7989                     pw.print("  * Restarting "); pw.println(r);
7990                     r.dump(pw, "    ");
7991                 }
7992                 needSep = true;
7993             }
7994 
7995             if (mDestroyingServices.size() > 0) {
7996                 printed = false;
7997                 for (int i=0; i< mDestroyingServices.size(); i++) {
7998                     ServiceRecord r = mDestroyingServices.get(i);
7999                     if (!matcher.match(r, r.name)) {
8000                         continue;
8001                     }
8002                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
8003                         continue;
8004                     }
8005                     printedAnything = true;
8006                     if (!printed) {
8007                         if (needSep) pw.println();
8008                         needSep = true;
8009                         pw.println("  Destroying services:");
8010                         printed = true;
8011                     }
8012                     pw.print("  * Destroy "); pw.println(r);
8013                     r.dump(pw, "    ");
8014                 }
8015                 needSep = true;
8016             }
8017 
8018             if (dumpAll) {
8019                 printed = false;
8020                 for (int ic=0; ic<mServiceConnections.size(); ic++) {
8021                     ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
8022                     for (int i=0; i<r.size(); i++) {
8023                         ConnectionRecord cr = r.get(i);
8024                         if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
8025                             continue;
8026                         }
8027                         if (dumpPackage != null && (cr.binding.client == null
8028                                 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
8029                             continue;
8030                         }
8031                         printedAnything = true;
8032                         if (!printed) {
8033                             if (needSep) pw.println();
8034                             needSep = true;
8035                             pw.println("  Connection bindings to services:");
8036                             printed = true;
8037                         }
8038                         pw.print("  * "); pw.println(cr);
8039                         cr.dump(pw, "    ");
8040                     }
8041                 }
8042             }
8043 
8044             if (matcher.all) {
8045                 final long nowElapsed = SystemClock.elapsedRealtime();
8046                 final int[] users = mAm.mUserController.getUsers();
8047                 for (int user : users) {
8048                     boolean printedUser = false;
8049                     ServiceMap smap = mServiceMap.get(user);
8050                     if (smap == null) {
8051                         continue;
8052                     }
8053                     for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
8054                         ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
8055                         if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
8056                             continue;
8057                         }
8058                         if (!printedUser) {
8059                             printedUser = true;
8060                             printedAnything = true;
8061                             if (needSep) pw.println();
8062                             needSep = true;
8063                             pw.print("Active foreground apps - user ");
8064                             pw.print(user);
8065                             pw.println(":");
8066                         }
8067                         pw.print("  #");
8068                         pw.print(i);
8069                         pw.print(": ");
8070                         pw.println(aa.mPackageName);
8071                         if (aa.mLabel != null) {
8072                             pw.print("    mLabel=");
8073                             pw.println(aa.mLabel);
8074                         }
8075                         pw.print("    mNumActive=");
8076                         pw.print(aa.mNumActive);
8077                         pw.print(" mAppOnTop=");
8078                         pw.print(aa.mAppOnTop);
8079                         pw.print(" mShownWhileTop=");
8080                         pw.print(aa.mShownWhileTop);
8081                         pw.print(" mShownWhileScreenOn=");
8082                         pw.println(aa.mShownWhileScreenOn);
8083                         pw.print("    mStartTime=");
8084                         TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
8085                         pw.print(" mStartVisibleTime=");
8086                         TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
8087                         pw.println();
8088                         if (aa.mEndTime != 0) {
8089                             pw.print("    mEndTime=");
8090                             TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
8091                             pw.println();
8092                         }
8093                     }
8094                     if (smap.hasMessagesOrCallbacks()) {
8095                         if (needSep) {
8096                             pw.println();
8097                         }
8098                         printedAnything = true;
8099                         needSep = true;
8100                         pw.print("  Handler - user ");
8101                         pw.print(user);
8102                         pw.println(":");
8103                         smap.dumpMine(new PrintWriterPrinter(pw), "    ");
8104                     }
8105                 }
8106             }
8107 
8108             if (!printedAnything) {
8109                 pw.println("  (nothing)");
8110             }
8111         }
8112     }
8113 
newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)8114     ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8115             int opti, boolean dumpAll, String dumpPackage) {
8116         return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
8117     }
8118 
dumpDebug(ProtoOutputStream proto, long fieldId)8119     protected void dumpDebug(ProtoOutputStream proto, long fieldId) {
8120         synchronized (mAm) {
8121             final long outterToken = proto.start(fieldId);
8122             int[] users = mAm.mUserController.getUsers();
8123             for (int user : users) {
8124                 ServiceMap smap = mServiceMap.get(user);
8125                 if (smap == null) {
8126                     continue;
8127                 }
8128                 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
8129                 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
8130                 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
8131                 for (int i=0; i<alls.size(); i++) {
8132                     alls.valueAt(i).dumpDebug(proto,
8133                             ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
8134                 }
8135                 proto.end(token);
8136             }
8137             proto.end(outterToken);
8138         }
8139     }
8140 
8141     /**
8142      * There are three ways to call this:
8143      *  - no service specified: dump all the services
8144      *  - a flattened component name that matched an existing service was specified as the
8145      *    first arg: dump that one service
8146      *  - the first arg isn't the flattened component name of an existing service:
8147      *    dump all services whose component contains the first arg as a substring
8148      */
dumpService(FileDescriptor fd, PrintWriter pw, String name, int[] users, String[] args, int opti, boolean dumpAll)8149     protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, int[] users,
8150             String[] args, int opti, boolean dumpAll) {
8151         try {
8152             mAm.mOomAdjuster.mCachedAppOptimizer.enableFreezer(false);
8153             final ArrayList<ServiceRecord> services = new ArrayList<>();
8154 
8155             final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
8156 
8157             synchronized (mAm) {
8158                 if (users == null) {
8159                     users = mAm.mUserController.getUsers();
8160                 }
8161 
8162                 for (int user : users) {
8163                     ServiceMap smap = mServiceMap.get(user);
8164                     if (smap == null) {
8165                         continue;
8166                     }
8167                     ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
8168                     for (int i=0; i<alls.size(); i++) {
8169                         ServiceRecord r1 = alls.valueAt(i);
8170 
8171                         if (filter.test(r1)) {
8172                             services.add(r1);
8173                         }
8174                     }
8175                 }
8176             }
8177 
8178             if (services.size() <= 0) {
8179                 return false;
8180             }
8181 
8182             // Sort by component name.
8183             services.sort(Comparator.comparing(WithComponentName::getComponentName));
8184 
8185             boolean needSep = false;
8186             for (int i=0; i<services.size(); i++) {
8187                 if (needSep) {
8188                     pw.println();
8189                 }
8190                 needSep = true;
8191                 dumpService("", fd, pw, services.get(i), args, dumpAll);
8192             }
8193             return true;
8194         } finally {
8195             mAm.mOomAdjuster.mCachedAppOptimizer.enableFreezer(true);
8196         }
8197     }
8198 
8199     /**
8200      * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8201      * there is a thread associated with the service.
8202      */
dumpService(String prefix, FileDescriptor fd, PrintWriter pw, final ServiceRecord r, String[] args, boolean dumpAll)8203     private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8204             final ServiceRecord r, String[] args, boolean dumpAll) {
8205         String innerPrefix = prefix + "  ";
8206         synchronized (mAm) {
8207             pw.print(prefix); pw.print("SERVICE ");
8208             pw.print(r.shortInstanceName); pw.print(" ");
8209             pw.print(Integer.toHexString(System.identityHashCode(r)));
8210             pw.print(" pid=");
8211             if (r.app != null) {
8212                 pw.print(r.app.getPid());
8213                 pw.print(" user="); pw.println(r.userId);
8214             } else pw.println("(not running)");
8215             if (dumpAll) {
8216                 r.dump(pw, innerPrefix);
8217             }
8218         }
8219         IApplicationThread thread;
8220         if (r.app != null && (thread = r.app.getThread()) != null) {
8221             pw.print(prefix); pw.println("  Client:");
8222             pw.flush();
8223             try {
8224                 TransferPipe tp = new TransferPipe();
8225                 try {
8226                     thread.dumpService(tp.getWriteFd(), r, args);
8227                     tp.setBufferPrefix(prefix + "    ");
8228                     tp.go(fd);
8229                 } finally {
8230                     tp.kill();
8231                 }
8232             } catch (IOException e) {
8233                 pw.println(prefix + "    Failure while dumping the service: " + e);
8234             } catch (RemoteException e) {
8235                 pw.println(prefix + "    Got a RemoteException while dumping the service");
8236             }
8237         }
8238     }
8239 
setFgsRestrictionLocked(String callingPackage, int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId, BackgroundStartPrivileges backgroundStartPrivileges, boolean isBindService)8240     private void setFgsRestrictionLocked(String callingPackage,
8241             int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId,
8242             BackgroundStartPrivileges backgroundStartPrivileges, boolean isBindService) {
8243         setFgsRestrictionLocked(callingPackage, callingPid, callingUid, intent, r, userId,
8244                 backgroundStartPrivileges, isBindService, /*forBoundFgs*/ false);
8245     }
8246 
8247     /**
8248      * There are two FGS restrictions:
8249      * In R, mAllowWhileInUsePermissionInFgs is to allow while-in-use permissions in foreground
8250      *  service or not. while-in-use permissions in FGS started from background might be restricted.
8251      * In S, mAllowStartForeground is to allow FGS to startForeground or not. Service started
8252      * from background may not become a FGS.
8253      * @param callingPackage caller app's package name.
8254      * @param callingUid caller app's uid.
8255      * @param intent intent to start/bind service.
8256      * @param r the service to start.
8257      * @param inBindService True if it's called from bindService().
8258      * @param forBoundFgs set to true if it's called from Service.startForeground() for a
8259      *                    service that's not started but bound.
8260      */
setFgsRestrictionLocked(String callingPackage, int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId, BackgroundStartPrivileges backgroundStartPrivileges, boolean inBindService, boolean forBoundFgs)8261     private void setFgsRestrictionLocked(String callingPackage,
8262             int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId,
8263             BackgroundStartPrivileges backgroundStartPrivileges, boolean inBindService,
8264             boolean forBoundFgs) {
8265 
8266         @ReasonCode int allowWiu;
8267         @ReasonCode int allowStart;
8268 
8269         // If called from bindService(), do not update the actual fields, but instead
8270         // keep it in a separate set of fields.
8271         if (inBindService) {
8272             allowWiu = r.mAllowWiu_inBindService;
8273             allowStart = r.mAllowStart_inBindService;
8274         } else {
8275             allowWiu = r.mAllowWiu_noBinding;
8276             allowStart = r.mAllowStart_noBinding;
8277         }
8278 
8279         if ((allowWiu == REASON_DENIED) || (allowStart == REASON_DENIED)) {
8280             @ReasonCode final int allowWhileInUse = shouldAllowFgsWhileInUsePermissionLocked(
8281                     callingPackage, callingPid, callingUid, r.app, backgroundStartPrivileges);
8282             // We store them to compare the old and new while-in-use logics to each other.
8283             // (They're not used for any other purposes.)
8284             if (allowWiu == REASON_DENIED) {
8285                 allowWiu = allowWhileInUse;
8286             }
8287             if (allowStart == REASON_DENIED) {
8288                 allowStart = shouldAllowFgsStartForegroundWithBindingCheckLocked(
8289                         allowWhileInUse, callingPackage, callingPid, callingUid, intent, r,
8290                         backgroundStartPrivileges, inBindService);
8291             }
8292         }
8293 
8294         if (inBindService) {
8295             r.mAllowWiu_inBindService = allowWiu;
8296             r.mAllowStart_inBindService = allowStart;
8297         } else {
8298             if (!forBoundFgs) {
8299                 // This is for "normal" situation -- either:
8300                 // - in Context.start[Foreground]Service()
8301                 // - or, in Service.startForeground() on a started service.
8302                 r.mAllowWiu_noBinding = allowWiu;
8303                 r.mAllowStart_noBinding = allowStart;
8304             } else {
8305                 // Service.startForeground() is called on a service that's not started, but bound.
8306                 // In this case, we set them to "byBindings", not "noBinding", because
8307                 // we don't want to use them when we calculate the "legacy" code.
8308                 //
8309                 // We don't want to set them to "no binding" codes, because on U-QPR1 and below,
8310                 // we didn't call setFgsRestrictionLocked() in the code path which sets
8311                 // forBoundFgs to true, and we wanted to preserve the original behavior in other
8312                 // places to compare the legacy and new logic.
8313                 if (r.mAllowWiu_byBindings == REASON_DENIED) {
8314                     r.mAllowWiu_byBindings = allowWiu;
8315                 }
8316                 if (r.mAllowStart_byBindings == REASON_DENIED) {
8317                     r.mAllowStart_byBindings = allowStart;
8318                 }
8319             }
8320             // Also do a binding client check, unless called from bindService().
8321             if (r.mAllowWiu_byBindings == REASON_DENIED) {
8322                 r.mAllowWiu_byBindings =
8323                         shouldAllowFgsWhileInUsePermissionByBindingsLocked(callingUid);
8324             }
8325             if (r.mAllowStart_byBindings == REASON_DENIED) {
8326                 r.mAllowStart_byBindings = r.mAllowWiu_byBindings;
8327             }
8328         }
8329     }
8330 
8331     /**
8332      * Reset various while-in-use and BFSL related information.
8333      */
resetFgsRestrictionLocked(ServiceRecord r)8334     void resetFgsRestrictionLocked(ServiceRecord r) {
8335         r.clearFgsAllowWiu();
8336         r.clearFgsAllowStart();
8337 
8338         r.mInfoAllowStartForeground = null;
8339         r.mInfoTempFgsAllowListReason = null;
8340         r.mLoggedInfoAllowStartForeground = false;
8341         r.updateAllowUiJobScheduling(r.isFgsAllowedWiu_forStart());
8342     }
8343 
canStartForegroundServiceLocked(int callingPid, int callingUid, String callingPackage)8344     boolean canStartForegroundServiceLocked(int callingPid, int callingUid, String callingPackage) {
8345         if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) {
8346             return true;
8347         }
8348         final @ReasonCode int allowWhileInUse = shouldAllowFgsWhileInUsePermissionLocked(
8349                 callingPackage, callingPid, callingUid, null /* targetProcess */,
8350                 BackgroundStartPrivileges.NONE);
8351         @ReasonCode int allowStartFgs = shouldAllowFgsStartForegroundNoBindingCheckLocked(
8352                 allowWhileInUse, callingPid, callingUid, callingPackage, null /* targetService */,
8353                 BackgroundStartPrivileges.NONE);
8354 
8355         if (allowStartFgs == REASON_DENIED) {
8356             if (canBindingClientStartFgsLocked(callingUid) != null) {
8357                 allowStartFgs = REASON_FGS_BINDING;
8358             }
8359         }
8360         return allowStartFgs != REASON_DENIED;
8361     }
8362 
8363     /**
8364      * Should allow while-in-use permissions in FGS or not.
8365      * A typical BG started FGS is not allowed to have while-in-use permissions.
8366      *
8367      * @param callingPackage caller app's package name.
8368      * @param callingUid     caller app's uid.
8369      * @param targetProcess  the process of the service to start.
8370      * @return {@link ReasonCode}
8371      */
shouldAllowFgsWhileInUsePermissionLocked(String callingPackage, int callingPid, int callingUid, @Nullable ProcessRecord targetProcess, BackgroundStartPrivileges backgroundStartPrivileges)8372     @ReasonCode int shouldAllowFgsWhileInUsePermissionLocked(String callingPackage,
8373             int callingPid, int callingUid, @Nullable ProcessRecord targetProcess,
8374             BackgroundStartPrivileges backgroundStartPrivileges) {
8375         int ret = REASON_DENIED;
8376 
8377         final int uidState = mAm.getUidStateLocked(callingUid);
8378         if (ret == REASON_DENIED) {
8379             // Allow FGS while-in-use if the caller's process state is PROCESS_STATE_PERSISTENT,
8380             // PROCESS_STATE_PERSISTENT_UI or PROCESS_STATE_TOP.
8381             if (uidState <= PROCESS_STATE_TOP) {
8382                 ret = getReasonCodeFromProcState(uidState);
8383             }
8384         }
8385 
8386         if (ret == REASON_DENIED) {
8387             // Allow FGS while-in-use if the caller has visible activity.
8388             // Here we directly check ActivityTaskManagerService, instead of checking
8389             // PendingStartActivityUids in ActivityManagerService, which gives the same result.
8390             final boolean isCallingUidVisible = mAm.mAtmInternal.isUidForeground(callingUid);
8391             if (isCallingUidVisible) {
8392                 ret = REASON_UID_VISIBLE;
8393             }
8394         }
8395 
8396         if (ret == REASON_DENIED) {
8397             // Allow FGS while-in-use if the background activity start flag is on. Because
8398             // activity start can lead to FGS start in TOP state and obtain while-in-use.
8399             if (backgroundStartPrivileges.allowsBackgroundActivityStarts()) {
8400                 ret = REASON_START_ACTIVITY_FLAG;
8401             }
8402         }
8403 
8404         if (ret == REASON_DENIED) {
8405             boolean isCallerSystem = false;
8406             final int callingAppId = UserHandle.getAppId(callingUid);
8407             // Allow FGS while-in-use for a list of special UIDs.
8408             switch (callingAppId) {
8409                 case ROOT_UID:
8410                 case SYSTEM_UID:
8411                 case NFC_UID:
8412                 case SHELL_UID:
8413                     isCallerSystem = true;
8414                     break;
8415                 default:
8416                     isCallerSystem = false;
8417                     break;
8418             }
8419 
8420             if (isCallerSystem) {
8421                 ret = REASON_SYSTEM_UID;
8422             }
8423         }
8424 
8425         if (ret == REASON_DENIED) {
8426             // Allow FGS while-in-use if the WindowManager allows background activity start.
8427             // This is mainly to get the 10 seconds grace period if any activity in the caller has
8428             // either started or finished very recently. The binding flag
8429             // BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS is also allowed by the check here.
8430             final Integer allowedType = mAm.mProcessList.searchEachLruProcessesLOSP(false, pr -> {
8431                 if (pr.uid == callingUid) {
8432                     if (pr.getWindowProcessController().areBackgroundFgsStartsAllowed()) {
8433                         return REASON_ACTIVITY_STARTER;
8434                     }
8435                 }
8436                 return null;
8437             });
8438             if (allowedType != null) {
8439                 ret = allowedType;
8440             }
8441         }
8442 
8443         if (ret == REASON_DENIED) {
8444             // Allow FGS while-in-use if the caller UID is in ActivityManagerService's
8445             // mFgsWhileInUseTempAllowList. This is a temp allowlist to allow FGS while-in-use. It
8446             // is used when MediaSessionService's bluetooth button or play/resume/stop commands are
8447             // issued. The typical temp allowlist duration is 10 seconds.
8448             // This temp allowlist mechanism can also be called by other system_server internal
8449             // components such as Telephone/VOIP if they want to start a FGS and get while-in-use.
8450             if (mAm.mInternal.isTempAllowlistedForFgsWhileInUse(callingUid)) {
8451                 return REASON_TEMP_ALLOWED_WHILE_IN_USE;
8452             }
8453         }
8454 
8455         if (ret == REASON_DENIED) {
8456             if (targetProcess != null) {
8457                 // Allow FGS while-in-use if the caller of the instrumentation has
8458                 // START_ACTIVITIES_FROM_BACKGROUND permission.
8459                 ActiveInstrumentation instr = targetProcess.getActiveInstrumentation();
8460                 if (instr != null && instr.mHasBackgroundActivityStartsPermission) {
8461                     ret = REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION;
8462                 }
8463             }
8464         }
8465 
8466         if (ret == REASON_DENIED) {
8467             // Allow FGS while-in-use if the caller has START_ACTIVITIES_FROM_BACKGROUND
8468             // permission, because starting an activity can lead to starting FGS from the TOP state
8469             // and obtain while-in-use.
8470             if (mAm.checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
8471                     == PERMISSION_GRANTED) {
8472                 ret = REASON_BACKGROUND_ACTIVITY_PERMISSION;
8473             }
8474         }
8475 
8476         if (ret == REASON_DENIED) {
8477             // Allow FGS while-in-use if the caller is in the while-in-use allowlist. Right now
8478             // AttentionService and SystemCaptionsService packageName are in this allowlist.
8479             if (verifyPackage(callingPackage, callingUid)) {
8480                 final boolean isAllowedPackage =
8481                         mAllowListWhileInUsePermissionInFgs.contains(callingPackage);
8482                 if (isAllowedPackage) {
8483                     ret = REASON_ALLOWLISTED_PACKAGE;
8484                 }
8485             } else {
8486                 EventLog.writeEvent(0x534e4554, "215003903", callingUid,
8487                         "callingPackage:" + callingPackage + " does not belong to callingUid:"
8488                                 + callingUid);
8489             }
8490         }
8491 
8492         if (ret == REASON_DENIED) {
8493             // Allow FGS while-in-use if the caller is the device owner.
8494             final boolean isDeviceOwner = mAm.mInternal.isDeviceOwner(callingUid);
8495             if (isDeviceOwner) {
8496                 ret = REASON_DEVICE_OWNER;
8497             }
8498         }
8499         return ret;
8500     }
8501 
8502     /**
8503      * Check all bindings into the calling UID, and see if:
8504      * - It's bound by a TOP app
8505      * - or, bound by a persistent process with BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS.
8506      */
shouldAllowFgsWhileInUsePermissionByBindingsLocked(int callingUid)8507     private @ReasonCode int shouldAllowFgsWhileInUsePermissionByBindingsLocked(int callingUid) {
8508         final ArraySet<Integer> checkedClientUids = new ArraySet<>();
8509         final Integer result = mAm.mProcessList.searchEachLruProcessesLOSP(
8510                 false, pr -> {
8511                     if (pr.uid != callingUid) {
8512                         return null;
8513                     }
8514                     final ProcessServiceRecord psr = pr.mServices;
8515                     final int serviceCount = psr.mServices.size();
8516                     for (int svc = 0; svc < serviceCount; svc++) {
8517                         final ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns =
8518                                 psr.mServices.valueAt(svc).getConnections();
8519                         final int size = conns.size();
8520                         for (int conni = 0; conni < size; conni++) {
8521                             final ArrayList<ConnectionRecord> crs = conns.valueAt(conni);
8522                             for (int con = 0; con < crs.size(); con++) {
8523                                 final ConnectionRecord cr = crs.get(con);
8524                                 final ProcessRecord clientPr = cr.binding.client;
8525                                 final int clientUid = clientPr.uid;
8526 
8527                                 // An UID can bind to itself, do not check on itself again.
8528                                 // Also skip already checked clientUid.
8529                                 if (clientUid == callingUid
8530                                         || checkedClientUids.contains(clientUid)) {
8531                                     continue;
8532                                 }
8533 
8534                                 // Binding found, check the client procstate and the flag.
8535                                 final int clientUidState = mAm.getUidStateLocked(callingUid);
8536                                 final boolean boundByTop = clientUidState == PROCESS_STATE_TOP;
8537                                 final boolean boundByPersistentWithBal =
8538                                         clientUidState < PROCESS_STATE_TOP
8539                                         && cr.hasFlag(
8540                                                 Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS);
8541                                 if (boundByTop || boundByPersistentWithBal) {
8542                                     return getReasonCodeFromProcState(clientUidState);
8543                                 }
8544 
8545                                 // Don't check the same UID.
8546                                 checkedClientUids.add(clientUid);
8547                             }
8548                         }
8549                     }
8550                     return null;
8551                 });
8552         return result == null ? REASON_DENIED : result;
8553     }
8554 
8555     /**
8556      * The uid is not allowed to start FGS, but the uid has a service that is bound
8557      * by a clientUid, if the clientUid can start FGS, then the clientUid can propagate its
8558      * BG-FGS-start capability down to the callingUid.
8559      * @param uid
8560      * @return The first binding client's packageName that can start FGS. Return null if no client
8561      *         can start FGS.
8562      */
canBindingClientStartFgsLocked(int uid)8563     private String canBindingClientStartFgsLocked(int uid) {
8564         String bindFromPackage = null;
8565         final ArraySet<Integer> checkedClientUids = new ArraySet<>();
8566         final Pair<Integer, String> isAllowed = mAm.mProcessList.searchEachLruProcessesLOSP(
8567                 false, pr -> {
8568                 if (pr.uid == uid) {
8569                     final ProcessServiceRecord psr = pr.mServices;
8570                     final int serviceCount = psr.mServices.size();
8571                     for (int svc = 0; svc < serviceCount; svc++) {
8572                         final ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns =
8573                                 psr.mServices.valueAt(svc).getConnections();
8574                         final int size = conns.size();
8575                         for (int conni = 0; conni < size; conni++) {
8576                             final ArrayList<ConnectionRecord> crs = conns.valueAt(conni);
8577                             for (int con = 0; con < crs.size(); con++) {
8578                                 final ConnectionRecord cr = crs.get(con);
8579                                 final ProcessRecord clientPr = cr.binding.client;
8580                                 // If a binding is from a persistent process, we don't automatically
8581                                 // always allow the bindee to allow FGS BG starts. In this case,
8582                                 // the binder will have to explicitly make sure the bindee's
8583                                 // procstate will be BFGS or above. Otherwise, for example, even if
8584                                 // the system server binds to an app with BIND_NOT_FOREGROUND,
8585                                 // the binder would have to be able to start FGS, which is not what
8586                                 // we want. (e.g. job services shouldn't be allowed BG-FGS.)
8587                                 if (clientPr.isPersistent()) {
8588                                     continue;
8589                                 }
8590                                 final int clientPid = clientPr.mPid;
8591                                 final int clientUid = clientPr.uid;
8592                                 // An UID can bind to itself, do not check on itself again.
8593                                 // Also skip already checked clientUid.
8594                                 if (clientUid == uid
8595                                         || checkedClientUids.contains(clientUid)) {
8596                                     continue;
8597                                 }
8598                                 final String clientPackageName = cr.clientPackageName;
8599                                 final @ReasonCode int allowWhileInUse2 =
8600                                         shouldAllowFgsWhileInUsePermissionLocked(
8601                                                 clientPackageName,
8602                                                 clientPid, clientUid, null /* targetProcess */,
8603                                                 BackgroundStartPrivileges.NONE);
8604                                 final @ReasonCode int allowStartFgs =
8605                                         shouldAllowFgsStartForegroundNoBindingCheckLocked(
8606                                                 allowWhileInUse2,
8607                                                 clientPid, clientUid, clientPackageName,
8608                                                 null /* targetService */,
8609                                                 BackgroundStartPrivileges.NONE);
8610                                 if (allowStartFgs != REASON_DENIED) {
8611                                     return new Pair<>(allowStartFgs, clientPackageName);
8612                                 } else {
8613                                     checkedClientUids.add(clientUid);
8614                                 }
8615 
8616                             }
8617                         }
8618                     }
8619                 }
8620                 return null;
8621             });
8622         if (isAllowed != null) {
8623             bindFromPackage = isAllowed.second;
8624         }
8625         return bindFromPackage;
8626     }
8627 
8628     /**
8629      * Should allow the FGS to start (AKA startForeground()) or not.
8630      * The check in this method is in addition to check in
8631      * {@link #shouldAllowFgsWhileInUsePermissionLocked}
8632      * @param allowWhileInUse the return code from {@link #shouldAllowFgsWhileInUsePermissionLocked}
8633      * @param callingPackage caller app's package name.
8634      * @param callingUid caller app's uid.
8635      * @param intent intent to start/bind service.
8636      * @param r the service to start.
8637      * @return {@link ReasonCode}
8638      */
shouldAllowFgsStartForegroundWithBindingCheckLocked( @easonCode int allowWhileInUse, String callingPackage, int callingPid, int callingUid, Intent intent, ServiceRecord r, BackgroundStartPrivileges backgroundStartPrivileges, boolean isBindService)8639     private @ReasonCode int shouldAllowFgsStartForegroundWithBindingCheckLocked(
8640             @ReasonCode int allowWhileInUse, String callingPackage, int callingPid,
8641             int callingUid, Intent intent, ServiceRecord r,
8642             BackgroundStartPrivileges backgroundStartPrivileges, boolean isBindService) {
8643         ActivityManagerService.FgsTempAllowListItem tempAllowListReason =
8644                 r.mInfoTempFgsAllowListReason = mAm.isAllowlistedForFgsStartLOSP(callingUid);
8645         int ret = shouldAllowFgsStartForegroundNoBindingCheckLocked(allowWhileInUse, callingPid,
8646                 callingUid, callingPackage, r, backgroundStartPrivileges);
8647 
8648         // If an app (App 1) is bound by another app (App 2) that could start an FGS, then App 1
8649         // is also allowed to start an FGS. We check all the binding
8650         // in canBindingClientStartFgsLocked() to do this check.
8651         // (Note we won't check more than 1 level of binding.)
8652         // [bookmark: 61867f60-007c-408c-a2c4-e19e96056135] -- this code is referred to from
8653         // OomAdjuster.
8654         String bindFromPackage = null;
8655         if (ret == REASON_DENIED) {
8656             bindFromPackage = canBindingClientStartFgsLocked(callingUid);
8657             if (bindFromPackage != null) {
8658                 ret = REASON_FGS_BINDING;
8659             }
8660         }
8661 
8662         final int uidState = mAm.getUidStateLocked(callingUid);
8663         int callerTargetSdkVersion = -1;
8664         try {
8665             callerTargetSdkVersion = mAm.mContext.getPackageManager()
8666                     .getTargetSdkVersion(callingPackage);
8667         } catch (PackageManager.NameNotFoundException ignored) {
8668         }
8669         final boolean uidBfsl = (mAm.getUidProcessCapabilityLocked(callingUid)
8670                 & PROCESS_CAPABILITY_BFSL) != 0;
8671         final String debugInfo =
8672                 "[callingPackage: " + callingPackage
8673                         + "; callingUid: " + callingUid
8674                         + "; uidState: " + ProcessList.makeProcStateString(uidState)
8675                         + "; uidBFSL: " + (uidBfsl ? "[BFSL]" : "n/a")
8676                         + "; intent: " + intent
8677                         + "; code:" + reasonCodeToString(ret)
8678                         + "; tempAllowListReason:<"
8679                         + (tempAllowListReason == null ? null :
8680                                 (tempAllowListReason.mReason
8681                                         + ",reasonCode:"
8682                                         + reasonCodeToString(tempAllowListReason.mReasonCode)
8683                                         + ",duration:" + tempAllowListReason.mDuration
8684                                         + ",callingUid:" + tempAllowListReason.mCallingUid))
8685                         + ">"
8686                         + "; targetSdkVersion:" + r.appInfo.targetSdkVersion
8687                         + "; callerTargetSdkVersion:" + callerTargetSdkVersion
8688                         + "; startForegroundCount:" + r.mStartForegroundCount
8689                         + "; bindFromPackage:" + bindFromPackage
8690                         + ": isBindService:" + isBindService
8691                         + "]";
8692         if (!debugInfo.equals(r.mInfoAllowStartForeground)) {
8693             r.mLoggedInfoAllowStartForeground = false;
8694             r.mInfoAllowStartForeground = debugInfo;
8695         }
8696         return ret;
8697     }
8698 
shouldAllowFgsStartForegroundNoBindingCheckLocked( @easonCode int allowWhileInUse, int callingPid, int callingUid, String callingPackage, @Nullable ServiceRecord targetService, BackgroundStartPrivileges backgroundStartPrivileges)8699     private @ReasonCode int shouldAllowFgsStartForegroundNoBindingCheckLocked(
8700             @ReasonCode int allowWhileInUse, int callingPid, int callingUid, String callingPackage,
8701             @Nullable ServiceRecord targetService,
8702             BackgroundStartPrivileges backgroundStartPrivileges) {
8703         int ret = allowWhileInUse;
8704 
8705         if (ret == REASON_DENIED) {
8706             final int uidState = mAm.getUidStateLocked(callingUid);
8707             // Is the calling UID at PROCESS_STATE_TOP or above?
8708             if (uidState <= PROCESS_STATE_TOP) {
8709                 ret = getReasonCodeFromProcState(uidState);
8710             }
8711         }
8712 
8713         if (ret == REASON_DENIED) {
8714             final boolean uidBfsl =
8715                     (mAm.getUidProcessCapabilityLocked(callingUid) & PROCESS_CAPABILITY_BFSL) != 0;
8716             final Integer allowedType = mAm.mProcessList.searchEachLruProcessesLOSP(false, app -> {
8717                 if (app.uid == callingUid) {
8718                     final ProcessStateRecord state = app.mState;
8719                     final int procstate = state.getCurProcState();
8720                     if ((procstate <= PROCESS_STATE_BOUND_TOP)
8721                             || (uidBfsl && (procstate <= PROCESS_STATE_BOUND_FOREGROUND_SERVICE))) {
8722                         return getReasonCodeFromProcState(procstate);
8723                     } else {
8724                         final ActiveInstrumentation instr = app.getActiveInstrumentation();
8725                         if (instr != null
8726                                 && instr.mHasBackgroundForegroundServiceStartsPermission) {
8727                             return REASON_INSTR_BACKGROUND_FGS_PERMISSION;
8728                         }
8729                         final long lastInvisibleTime = app.mState.getLastInvisibleTime();
8730                         if (lastInvisibleTime > 0 && lastInvisibleTime < Long.MAX_VALUE) {
8731                             final long sinceLastInvisible = SystemClock.elapsedRealtime()
8732                                     - lastInvisibleTime;
8733                             if (sinceLastInvisible < mAm.mConstants.mFgToBgFgsGraceDuration) {
8734                                 return REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD;
8735                             }
8736                         }
8737                     }
8738                 }
8739                 return null;
8740             });
8741             if (allowedType != null) {
8742                 ret = allowedType;
8743             }
8744         }
8745 
8746         if (ret == REASON_DENIED) {
8747             if (mAm.checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid,
8748                     callingUid) == PERMISSION_GRANTED) {
8749                 ret = REASON_BACKGROUND_FGS_PERMISSION;
8750             }
8751         }
8752 
8753         if (ret == REASON_DENIED) {
8754             if (backgroundStartPrivileges.allowsBackgroundFgsStarts()) {
8755                 ret = REASON_START_ACTIVITY_FLAG;
8756             }
8757         }
8758 
8759         if (ret == REASON_DENIED) {
8760             if (mAm.mAtmInternal.hasSystemAlertWindowPermission(
8761                                     callingUid, callingPid, callingPackage)) {
8762                 // Starting from Android V, it is not enough to only have the SYSTEM_ALERT_WINDOW
8763                 // permission granted - apps must also be showing an overlay window.
8764                 if (Flags.fgsDisableSaw()
8765                         && CompatChanges.isChangeEnabled(FGS_SAW_RESTRICTIONS, callingUid)) {
8766                     final UidRecord uidRecord = mAm.mProcessList.getUidRecordLOSP(callingUid);
8767                     if (uidRecord != null) {
8768                         for (int i = uidRecord.getNumOfProcs() - 1; i >= 0; i--) {
8769                             final ProcessRecord pr = uidRecord.getProcessRecordByIndex(i);
8770                             if (pr != null && pr.mState.hasOverlayUi()) {
8771                                 ret = REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
8772                                 break;
8773                             }
8774                         }
8775                     }
8776                 } else { // pre-V logic
8777                     ret = REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
8778                 }
8779             }
8780         }
8781 
8782         // Check for CDM apps with either REQUEST_COMPANION_RUN_IN_BACKGROUND or
8783         // REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND.
8784         // Note: When a CDM app has REQUEST_COMPANION_RUN_IN_BACKGROUND, the app is also put
8785         // in the user-allowlist. However, in this case, we want to use the reason code
8786         // REASON_COMPANION_DEVICE_MANAGER, so this check needs to be before the
8787         // isAllowlistedForFgsStartLOSP check.
8788         if (ret == REASON_DENIED) {
8789             final boolean isCompanionApp = mAm.mInternal.isAssociatedCompanionApp(
8790                     UserHandle.getUserId(callingUid), callingUid);
8791             if (isCompanionApp) {
8792                 if (isPermissionGranted(
8793                         REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND,
8794                         callingPid, callingUid)
8795                         || isPermissionGranted(REQUEST_COMPANION_RUN_IN_BACKGROUND,
8796                         callingPid, callingUid)) {
8797                     ret = REASON_COMPANION_DEVICE_MANAGER;
8798                 }
8799             }
8800         }
8801 
8802         if (ret == REASON_DENIED) {
8803             ActivityManagerService.FgsTempAllowListItem item =
8804                     mAm.isAllowlistedForFgsStartLOSP(callingUid);
8805             if (item != null) {
8806                 if (item == ActivityManagerService.FAKE_TEMP_ALLOW_LIST_ITEM) {
8807                     ret = REASON_SYSTEM_ALLOW_LISTED;
8808                 } else {
8809                     ret = item.mReasonCode;
8810                 }
8811             }
8812         }
8813 
8814         if (ret == REASON_DENIED) {
8815             if (UserManager.isDeviceInDemoMode(mAm.mContext)) {
8816                 ret = REASON_DEVICE_DEMO_MODE;
8817             }
8818         }
8819 
8820         if (ret == REASON_DENIED) {
8821             // Is the calling UID a profile owner app?
8822             final boolean isProfileOwner = mAm.mInternal.isProfileOwner(callingUid);
8823             if (isProfileOwner) {
8824                 ret = REASON_PROFILE_OWNER;
8825             }
8826         }
8827 
8828         if (ret == REASON_DENIED) {
8829             final AppOpsManager appOpsManager = mAm.getAppOpsManager();
8830             if (mAm.mConstants.mFlagSystemExemptPowerRestrictionsEnabled
8831                     && appOpsManager.checkOpNoThrow(
8832                     AppOpsManager.OP_SYSTEM_EXEMPT_FROM_POWER_RESTRICTIONS, callingUid,
8833                     callingPackage) == AppOpsManager.MODE_ALLOWED) {
8834                 ret = REASON_SYSTEM_EXEMPT_APP_OP;
8835             }
8836         }
8837 
8838         if (ret == REASON_DENIED) {
8839             final AppOpsManager appOpsManager = mAm.getAppOpsManager();
8840             if (appOpsManager.checkOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, callingUid,
8841                     callingPackage) == AppOpsManager.MODE_ALLOWED) {
8842                 ret = REASON_OP_ACTIVATE_VPN;
8843             } else if (appOpsManager.checkOpNoThrow(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN,
8844                     callingUid, callingPackage) == AppOpsManager.MODE_ALLOWED) {
8845                 ret = REASON_OP_ACTIVATE_PLATFORM_VPN;
8846             }
8847         }
8848 
8849         if (ret == REASON_DENIED) {
8850             final String inputMethod =
8851                     Settings.Secure.getStringForUser(mAm.mContext.getContentResolver(),
8852                             Settings.Secure.DEFAULT_INPUT_METHOD,
8853                             UserHandle.getUserId(callingUid));
8854             if (inputMethod != null) {
8855                 final ComponentName cn = ComponentName.unflattenFromString(inputMethod);
8856                 if (cn != null && cn.getPackageName().equals(callingPackage)) {
8857                     ret = REASON_CURRENT_INPUT_METHOD;
8858                 }
8859             }
8860         }
8861 
8862         if (ret == REASON_DENIED) {
8863             if (mAm.mConstants.mFgsAllowOptOut
8864                     && targetService != null
8865                     && targetService.appInfo.hasRequestForegroundServiceExemption()) {
8866                 ret = REASON_OPT_OUT_REQUESTED;
8867             }
8868         }
8869 
8870         return ret;
8871     }
8872 
isPermissionGranted(String permission, int callingPid, int callingUid)8873     private boolean isPermissionGranted(String permission, int callingPid, int callingUid) {
8874         return mAm.checkPermission(permission, callingPid, callingUid) == PERMISSION_GRANTED;
8875     }
8876 
isFgsBgStart(@easonCode int code)8877     private static boolean isFgsBgStart(@ReasonCode int code) {
8878         return code != REASON_PROC_STATE_PERSISTENT
8879                 && code != REASON_PROC_STATE_PERSISTENT_UI
8880                 && code != REASON_PROC_STATE_TOP
8881                 && code != REASON_UID_VISIBLE;
8882     }
8883 
showFgsBgRestrictedNotificationLocked(ServiceRecord r)8884     private void showFgsBgRestrictedNotificationLocked(ServiceRecord r) {
8885         if (!mAm.mConstants.mFgsStartRestrictionNotificationEnabled /* default is false */) {
8886             return;
8887         }
8888         final Context context = mAm.mContext;
8889         final String title = "Foreground Service BG-Launch Restricted";
8890         final String content = "App restricted: " + r.mRecentCallingPackage;
8891         final long now = System.currentTimeMillis();
8892         final String bigText = DATE_FORMATTER.format(now) + " " + r.mInfoAllowStartForeground;
8893         final String groupKey = "com.android.fgs-bg-restricted";
8894         final Notification.Builder n =
8895                 new Notification.Builder(context,
8896                         SystemNotificationChannels.ALERTS)
8897                         .setGroup(groupKey)
8898                         .setSmallIcon(R.drawable.stat_sys_vitals)
8899                         .setWhen(0)
8900                         .setColor(context.getColor(
8901                                 com.android.internal.R.color.system_notification_accent_color))
8902                         .setTicker(title)
8903                         .setContentTitle(title)
8904                         .setContentText(content)
8905                         .setStyle(new Notification.BigTextStyle().bigText(bigText));
8906         context.getSystemService(NotificationManager.class).notifyAsUser(Long.toString(now),
8907                 NOTE_FOREGROUND_SERVICE_BG_LAUNCH, n.build(), UserHandle.ALL);
8908     }
8909 
isBgFgsRestrictionEnabled(ServiceRecord r, int actualCallingUid)8910     private boolean isBgFgsRestrictionEnabled(ServiceRecord r, int actualCallingUid) {
8911         // mFlagFgsStartRestrictionEnabled controls whether to enable the BG FGS restrictions:
8912         // - If true (default), BG-FGS restrictions are enabled if the service targets >= S.
8913         // - If false, BG-FGS restrictions are disabled for all apps.
8914         if (!mAm.mConstants.mFlagFgsStartRestrictionEnabled) {
8915             return false;
8916         }
8917 
8918         // If the service target below S, then don't enable the restrictions.
8919         if (!CompatChanges.isChangeEnabled(FGS_BG_START_RESTRICTION_CHANGE_ID, r.appInfo.uid)) {
8920             return false;
8921         }
8922 
8923         // mFgsStartRestrictionCheckCallerTargetSdk controls whether we take the caller's target
8924         // SDK level into account or not:
8925         // - If true (default), BG-FGS restrictions only happens if the caller _also_ targets >= S.
8926         // - If false, BG-FGS restrictions do _not_ use the caller SDK levels.
8927         if (!mAm.mConstants.mFgsStartRestrictionCheckCallerTargetSdk) {
8928             return true; // In this case, we only check the service's target SDK level.
8929         }
8930         final int callingUid;
8931         if (Flags.newFgsRestrictionLogic()) {
8932             // We always consider SYSTEM_UID to target S+, so just enable the restrictions.
8933             if (actualCallingUid == Process.SYSTEM_UID) {
8934                 return true;
8935             }
8936             callingUid = actualCallingUid;
8937         } else {
8938             // Legacy logic used mRecentCallingUid.
8939             callingUid = r.mRecentCallingUid;
8940         }
8941         if (!CompatChanges.isChangeEnabled(FGS_BG_START_RESTRICTION_CHANGE_ID, callingUid)) {
8942             return false; // If the caller targets < S, then we still disable the restrictions.
8943         }
8944 
8945         // Both the service and the caller target S+, so enable the check.
8946         return true;
8947     }
8948 
logFgsBackgroundStart(ServiceRecord r)8949     private void logFgsBackgroundStart(ServiceRecord r) {
8950         /*
8951         // Only log if FGS is started from background.
8952         if (!isFgsBgStart(r.mAllowStartForeground)) {
8953             return;
8954         }
8955         */
8956         if (!r.mLoggedInfoAllowStartForeground) {
8957             final String msg = "Background started FGS: "
8958                     + (r.isFgsAllowedStart() ? "Allowed " : "Disallowed ")
8959                     + r.mInfoAllowStartForeground
8960                     + (r.isShortFgs() ? " (Called on SHORT_SERVICE)" : "");
8961             if (r.isFgsAllowedStart()) {
8962                 if (ActivityManagerUtils.shouldSamplePackageForAtom(r.packageName,
8963                         mAm.mConstants.mFgsStartAllowedLogSampleRate)) {
8964                     Slog.wtfQuiet(TAG, msg);
8965                 }
8966                 Slog.i(TAG, msg);
8967             } else {
8968                 //if (ActivityManagerUtils.shouldSamplePackageForAtom(r.packageName,
8969                 //        mAm.mConstants.mFgsStartDeniedLogSampleRate)) {
8970                     Slog.wtfQuiet(TAG, msg);
8971                 //}
8972                 Slog.w(TAG, msg);
8973             }
8974             r.mLoggedInfoAllowStartForeground = true;
8975         }
8976     }
8977 
8978     /**
8979      * Log the statsd event for FGS.
8980      * @param r ServiceRecord
8981      * @param state one of ENTER/EXIT/DENIED event.
8982      * @param durationMs Only meaningful for EXIT event, the duration from ENTER and EXIT state.
8983      * @param fgsStopReason why was this FGS stopped.
8984      * @param fgsTypeCheckCode The FGS type policy check result.
8985      */
logFGSStateChangeLocked(ServiceRecord r, int state, int durationMs, @FgsStopReason int fgsStopReason, @ForegroundServicePolicyCheckCode int fgsTypeCheckCode, int fgsStartApi, boolean fgsRestrictionRecalculated )8986     private void logFGSStateChangeLocked(ServiceRecord r, int state, int durationMs,
8987             @FgsStopReason int fgsStopReason,
8988             @ForegroundServicePolicyCheckCode int fgsTypeCheckCode,
8989             int fgsStartApi, // from ForegroundServiceStateChanged.FgsStartApi
8990             boolean fgsRestrictionRecalculated
8991     ) {
8992         if (!ActivityManagerUtils.shouldSamplePackageForAtom(
8993                 r.packageName, mAm.mConstants.mFgsAtomSampleRate)) {
8994             return;
8995         }
8996         boolean allowWhileInUsePermissionInFgs;
8997         @PowerExemptionManager.ReasonCode int fgsStartReasonCode;
8998         if (state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER
8999                 || state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT
9000                 || state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT) {
9001             allowWhileInUsePermissionInFgs = r.mAllowWhileInUsePermissionInFgsAtEntering;
9002             fgsStartReasonCode = r.mAllowStartForegroundAtEntering;
9003         } else {
9004             // TODO: Also log "forStart"
9005             allowWhileInUsePermissionInFgs = r.isFgsAllowedWiu_forCapabilities();
9006             fgsStartReasonCode = r.getFgsAllowStart();
9007         }
9008         final int callerTargetSdkVersion = r.mRecentCallerApplicationInfo != null
9009                 ? r.mRecentCallerApplicationInfo.targetSdkVersion : 0;
9010 
9011         // TODO(short-service): Log the UID capabilities (for BFSL) too, and also the procstate?
9012         FrameworkStatsLog.write(FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
9013                 r.appInfo.uid,
9014                 r.shortInstanceName,
9015                 state,
9016                 allowWhileInUsePermissionInFgs,
9017                 fgsStartReasonCode,
9018                 r.appInfo.targetSdkVersion,
9019                 r.mRecentCallingUid,
9020                 callerTargetSdkVersion,
9021                 r.mInfoTempFgsAllowListReason != null
9022                         ? r.mInfoTempFgsAllowListReason.mCallingUid : INVALID_UID,
9023                 r.mFgsNotificationWasDeferred,
9024                 r.mFgsNotificationShown,
9025                 durationMs,
9026                 r.mStartForegroundCount,
9027                 0, // Short instance name -- no longer logging it.
9028                 r.mFgsHasNotificationPermission,
9029                 r.foregroundServiceType,
9030                 fgsTypeCheckCode,
9031                 r.mIsFgsDelegate,
9032                 r.mFgsDelegation != null ? r.mFgsDelegation.mOptions.mClientUid : INVALID_UID,
9033                 r.mFgsDelegation != null ? r.mFgsDelegation.mOptions.mDelegationService
9034                         : ForegroundServiceDelegationOptions.DELEGATION_SERVICE_DEFAULT,
9035                 0 /* api_sate */,
9036                 null /* api_type */,
9037                 null /* api_timestamp */,
9038                 mAm.getUidStateLocked(r.appInfo.uid),
9039                 mAm.getUidProcessCapabilityLocked(r.appInfo.uid),
9040                 mAm.getUidStateLocked(r.mRecentCallingUid),
9041                 mAm.getUidProcessCapabilityLocked(r.mRecentCallingUid),
9042                 0,
9043                 0,
9044                 r.mAllowWiu_noBinding,
9045                 r.mAllowWiu_inBindService,
9046                 r.mAllowWiu_byBindings,
9047                 r.mAllowStart_noBinding,
9048                 r.mAllowStart_inBindService,
9049                 r.mAllowStart_byBindings,
9050                 fgsStartApi,
9051                 fgsRestrictionRecalculated);
9052 
9053         int event = 0;
9054         if (state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER) {
9055             event = EventLogTags.AM_FOREGROUND_SERVICE_START;
9056         } else if (state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT) {
9057             event = EventLogTags.AM_FOREGROUND_SERVICE_STOP;
9058         } else if (state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED) {
9059             event = EventLogTags.AM_FOREGROUND_SERVICE_DENIED;
9060         } else if (state == FOREGROUND_SERVICE_STATE_CHANGED__STATE__TIMED_OUT) {
9061             event = EventLogTags.AM_FOREGROUND_SERVICE_TIMED_OUT;
9062         } else {
9063             // Unknown event.
9064             return;
9065         }
9066         EventLog.writeEvent(event,
9067                 r.userId,
9068                 r.shortInstanceName,
9069                 allowWhileInUsePermissionInFgs ? 1 : 0,
9070                 reasonCodeToString(fgsStartReasonCode),
9071                 r.appInfo.targetSdkVersion,
9072                 callerTargetSdkVersion,
9073                 r.mFgsNotificationWasDeferred ? 1 : 0,
9074                 r.mFgsNotificationShown ? 1 : 0,
9075                 durationMs,
9076                 r.mStartForegroundCount,
9077                 fgsStopReasonToString(fgsStopReason),
9078                 r.foregroundServiceType);
9079     }
9080 
updateNumForegroundServicesLocked()9081     private void updateNumForegroundServicesLocked() {
9082         sNumForegroundServices.set(mAm.mProcessList.getNumForegroundServices());
9083     }
9084 
canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid, String callingPackage)9085     boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid,
9086             String callingPackage) {
9087         return shouldAllowFgsWhileInUsePermissionLocked(callingPackage, callingPid, callingUid,
9088                 /* targetProcess */ null,
9089                 BackgroundStartPrivileges.NONE)
9090                 != REASON_DENIED;
9091     }
9092 
canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid, String callingPackage, @Nullable ProcessRecord targetProcess, @NonNull BackgroundStartPrivileges backgroundStartPrivileges)9093     boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid,
9094             String callingPackage, @Nullable ProcessRecord targetProcess,
9095             @NonNull BackgroundStartPrivileges backgroundStartPrivileges) {
9096         return shouldAllowFgsWhileInUsePermissionLocked(callingPackage, callingPid, callingUid,
9097                 targetProcess, backgroundStartPrivileges) != REASON_DENIED;
9098     }
9099 
9100     /**
9101      * Checks if a given packageName belongs to a given uid.
9102      * @param packageName the package of the caller
9103      * @param uid the uid of the caller
9104      * @return true or false
9105      */
verifyPackage(String packageName, int uid)9106     private boolean verifyPackage(String packageName, int uid) {
9107         if (uid == ROOT_UID || uid == SYSTEM_UID) {
9108             //System and Root are always allowed
9109             return true;
9110         }
9111         return mAm.getPackageManagerInternal().isSameApp(packageName, uid,
9112                 UserHandle.getUserId(uid));
9113     }
9114 
fgsStopReasonToString(@gsStopReason int stopReason)9115     private static String fgsStopReasonToString(@FgsStopReason int stopReason) {
9116         switch (stopReason) {
9117             case FGS_STOP_REASON_STOP_SERVICE:
9118                 return "STOP_SERVICE";
9119             case FGS_STOP_REASON_STOP_FOREGROUND:
9120                 return "STOP_FOREGROUND";
9121             default:
9122                 return "UNKNOWN";
9123         }
9124     }
9125 
9126     /**
9127      * Start a foreground service delegate. The delegate is not an actual service component, it is
9128      * merely a delegate that promotes the client process into foreground service process state.
9129      *
9130      * @param options an ForegroundServiceDelegationOptions object.
9131      * @param connection callback if the delegate is started successfully.
9132      * @return true if delegate is started, false otherwise.
9133      * @throw SecurityException if PackageManaager can not resolve
9134      *        {@link ForegroundServiceDelegationOptions#mClientPackageName} or the resolved
9135      *        package's UID is not same as {@link ForegroundServiceDelegationOptions#mClientUid}
9136      */
startForegroundServiceDelegateLocked( @onNull ForegroundServiceDelegationOptions options, @Nullable ServiceConnection connection)9137     boolean startForegroundServiceDelegateLocked(
9138             @NonNull ForegroundServiceDelegationOptions options,
9139             @Nullable ServiceConnection connection) {
9140         Slog.v(TAG, "startForegroundServiceDelegateLocked " + options.getDescription());
9141         final ComponentName cn = options.getComponentName();
9142         for (int i = mFgsDelegations.size() - 1; i >= 0; i--) {
9143             ForegroundServiceDelegation delegation = mFgsDelegations.keyAt(i);
9144             if (delegation.mOptions.isSameDelegate(options)) {
9145                 Slog.e(TAG, "startForegroundServiceDelegate " + options.getDescription()
9146                         + " already exists, multiple connections are not allowed");
9147                 return false;
9148             }
9149         }
9150         final int callingPid = options.mClientPid;
9151         final int callingUid = options.mClientUid;
9152         final int userId = UserHandle.getUserId(callingUid);
9153         final String callingPackage = options.mClientPackageName;
9154 
9155         if (!canStartForegroundServiceLocked(callingPid, callingUid, callingPackage)) {
9156             Slog.d(TAG, "startForegroundServiceDelegateLocked aborted,"
9157                     + " app is in the background");
9158             return false;
9159         }
9160 
9161         IApplicationThread caller = options.mClientAppThread;
9162         ProcessRecord callerApp;
9163         if (caller != null) {
9164             callerApp = mAm.getRecordForAppLOSP(caller);
9165         } else {
9166             synchronized (mAm.mPidsSelfLocked) {
9167                 callerApp = mAm.mPidsSelfLocked.get(callingPid);
9168                 caller = callerApp.getThread();
9169             }
9170         }
9171         if (callerApp == null) {
9172             throw new SecurityException(
9173                     "Unable to find app for caller " + caller
9174                             + " (pid=" + callingPid
9175                             + ") when startForegroundServiceDelegateLocked " + cn);
9176         }
9177 
9178         Intent intent = new Intent();
9179         intent.setComponent(cn);
9180         ServiceLookupResult res = retrieveServiceLocked(intent, null /*instanceName */,
9181                 false /* isSdkSandboxService */, INVALID_UID /* sdkSandboxClientAppUid */,
9182                 null /* sdkSandboxClientAppPackage */, null /* resolvedType */, callingPackage,
9183                 callingPid, callingUid, userId, true /* createIfNeeded */,
9184                 false /* callingFromFg */, false /* isBindExternal */, false /* allowInstant */ ,
9185                 options, false /* inSharedIsolatedProcess */,
9186                 false /*inPrivateSharedIsolatedProcess*/);
9187         if (res == null || res.record == null) {
9188             Slog.d(TAG,
9189                     "startForegroundServiceDelegateLocked retrieveServiceLocked returns null");
9190             return false;
9191         }
9192 
9193         final ServiceRecord r = res.record;
9194         r.setProcess(callerApp, caller, callingPid, null);
9195         r.mIsFgsDelegate = true;
9196         final ForegroundServiceDelegation delegation =
9197                 new ForegroundServiceDelegation(options, connection);
9198         r.mFgsDelegation = delegation;
9199         mFgsDelegations.put(delegation, r);
9200         r.isForeground = true;
9201         r.mFgsEnterTime = SystemClock.uptimeMillis();
9202         r.foregroundServiceType = options.mForegroundServiceTypes;
9203         r.updateOomAdjSeq();
9204         setFgsRestrictionLocked(callingPackage, callingPid, callingUid, intent, r, userId,
9205                 BackgroundStartPrivileges.NONE,  false /* isBindService */);
9206         final ProcessServiceRecord psr = callerApp.mServices;
9207         final boolean newService = psr.startService(r);
9208         // updateOomAdj.
9209         updateServiceForegroundLocked(psr, /* oomAdj= */ true);
9210 
9211         synchronized (mAm.mProcessStats.mLock) {
9212             final ServiceState stracker = r.getTracker();
9213             if (stracker != null) {
9214                 stracker.setForeground(true,
9215                         mAm.mProcessStats.getMemFactorLocked(),
9216                         SystemClock.uptimeMillis());
9217             }
9218         }
9219 
9220         mAm.mBatteryStatsService.noteServiceStartRunning(callingUid, callingPackage,
9221                 cn.getClassName());
9222         mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
9223                 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null,
9224                 true, false, null, false,
9225                 AppOpsManager.ATTRIBUTION_FLAGS_NONE, AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE);
9226         registerAppOpCallbackLocked(r);
9227         synchronized (mFGSLogger) {
9228             mFGSLogger.logForegroundServiceStart(r.appInfo.uid, 0, r);
9229         }
9230         logFGSStateChangeLocked(r,
9231                 FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER,
9232                 0, FGS_STOP_REASON_UNKNOWN, FGS_TYPE_POLICY_CHECK_UNKNOWN,
9233                 FOREGROUND_SERVICE_STATE_CHANGED__FGS_START_API__FGSSTARTAPI_DELEGATE,
9234                 false /* fgsRestrictionRecalculated */
9235         );
9236         // Notify the caller.
9237         if (connection != null) {
9238             mAm.mHandler.post(() -> {
9239                 connection.onServiceConnected(cn, delegation.mBinder);
9240             });
9241         }
9242         signalForegroundServiceObserversLocked(r);
9243         if (r.foregroundId != 0 && r.foregroundNoti != null) {
9244             r.foregroundNoti.flags |= Notification.FLAG_FOREGROUND_SERVICE;
9245             r.postNotification(true);
9246         }
9247         return true;
9248     }
9249 
9250     /**
9251      * Stop the foreground service delegate. This removes the process out of foreground service
9252      * process state.
9253      *
9254      * @param options an ForegroundServiceDelegationOptions object.
9255      */
stopForegroundServiceDelegateLocked(@onNull ForegroundServiceDelegationOptions options)9256     void stopForegroundServiceDelegateLocked(@NonNull ForegroundServiceDelegationOptions options) {
9257         ServiceRecord r = null;
9258         for (int i = mFgsDelegations.size() - 1; i >= 0; i--) {
9259             if (mFgsDelegations.keyAt(i).mOptions.isSameDelegate(options)) {
9260                 Slog.d(TAG, "stopForegroundServiceDelegateLocked " + options.getDescription());
9261                 r = mFgsDelegations.valueAt(i);
9262                 break;
9263             }
9264         }
9265         if (r != null) {
9266             r.updateOomAdjSeq();
9267             bringDownServiceLocked(r, false);
9268         } else {
9269             Slog.e(TAG, "stopForegroundServiceDelegateLocked delegate does not exist "
9270                     + options.getDescription());
9271         }
9272     }
9273 
9274     /**
9275      * Stop the foreground service delegate by its ServiceConnection.
9276      * This removes the process out of foreground service process state.
9277      *
9278      * @param connection an ServiceConnection object.
9279      */
stopForegroundServiceDelegateLocked(@onNull ServiceConnection connection)9280     void stopForegroundServiceDelegateLocked(@NonNull ServiceConnection connection) {
9281         ServiceRecord r = null;
9282         for (int i = mFgsDelegations.size() - 1; i >= 0; i--) {
9283             final ForegroundServiceDelegation d = mFgsDelegations.keyAt(i);
9284             if (d.mConnection == connection) {
9285                 Slog.d(TAG, "stopForegroundServiceDelegateLocked "
9286                         + d.mOptions.getDescription());
9287                 r = mFgsDelegations.valueAt(i);
9288                 break;
9289             }
9290         }
9291         if (r != null) {
9292             r.updateOomAdjSeq();
9293             bringDownServiceLocked(r, false);
9294         } else {
9295             Slog.e(TAG, "stopForegroundServiceDelegateLocked delegate does not exist");
9296         }
9297     }
9298 
getClientPackages(ServiceRecord sr, ArraySet<String> output)9299     private static void getClientPackages(ServiceRecord sr, ArraySet<String> output) {
9300         var connections = sr.getConnections();
9301         for (int conni = connections.size() - 1; conni >= 0; conni--) {
9302             var connl = connections.valueAt(conni);
9303             for (int i = 0, size = connl.size(); i < size; i++) {
9304                 var conn = connl.get(i);
9305                 if (conn.binding.client != null) {
9306                     output.add(conn.binding.client.info.packageName);
9307                 }
9308             }
9309         }
9310     }
9311 
9312     /**
9313      * Return all client package names of a service.
9314      */
getClientPackagesLocked(@onNull String servicePackageName)9315     ArraySet<String> getClientPackagesLocked(@NonNull String servicePackageName) {
9316         var results = new ArraySet<String>();
9317         int[] users = mAm.mUserController.getUsers();
9318         for (int ui = 0; ui < users.length; ui++) {
9319             ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
9320             for (int i = 0, size = alls.size(); i < size; i++) {
9321                 ServiceRecord sr = alls.valueAt(i);
9322                 if (sr.name.getPackageName().equals(servicePackageName)) {
9323                     getClientPackages(sr, results);
9324                 }
9325             }
9326         }
9327         return results;
9328     }
9329 
isDeviceProvisioningPackage(String packageName)9330     private boolean isDeviceProvisioningPackage(String packageName) {
9331         if (mCachedDeviceProvisioningPackage == null) {
9332             mCachedDeviceProvisioningPackage = mAm.mContext.getResources().getString(
9333                     com.android.internal.R.string.config_deviceProvisioningPackage);
9334         }
9335         return mCachedDeviceProvisioningPackage != null
9336                 && mCachedDeviceProvisioningPackage.equals(packageName);
9337     }
9338 
wasStopped(ServiceRecord serviceRecord)9339     private boolean wasStopped(ServiceRecord serviceRecord) {
9340         return (serviceRecord.appInfo.flags & ApplicationInfo.FLAG_STOPPED) != 0;
9341     }
9342 }
9343