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