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