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_STATE_HEAVY_WEIGHT;
24 import static android.app.ActivityManager.PROCESS_STATE_PERSISTENT_UI;
25 import static android.app.ActivityManager.PROCESS_STATE_RECEIVER;
26 import static android.app.ActivityManager.PROCESS_STATE_TOP;
27 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
28 import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST;
29 import static android.os.PowerExemptionManager.REASON_ACTIVITY_STARTER;
30 import static android.os.PowerExemptionManager.REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD;
31 import static android.os.PowerExemptionManager.REASON_ALLOWLISTED_PACKAGE;
32 import static android.os.PowerExemptionManager.REASON_BACKGROUND_ACTIVITY_PERMISSION;
33 import static android.os.PowerExemptionManager.REASON_BACKGROUND_FGS_PERMISSION;
34 import static android.os.PowerExemptionManager.REASON_COMPANION_DEVICE_MANAGER;
35 import static android.os.PowerExemptionManager.REASON_CURRENT_INPUT_METHOD;
36 import static android.os.PowerExemptionManager.REASON_DENIED;
37 import static android.os.PowerExemptionManager.REASON_DEVICE_DEMO_MODE;
38 import static android.os.PowerExemptionManager.REASON_DEVICE_OWNER;
39 import static android.os.PowerExemptionManager.REASON_FGS_BINDING;
40 import static android.os.PowerExemptionManager.REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION;
41 import static android.os.PowerExemptionManager.REASON_INSTR_BACKGROUND_FGS_PERMISSION;
42 import static android.os.PowerExemptionManager.REASON_OPT_OUT_REQUESTED;
43 import static android.os.PowerExemptionManager.REASON_OP_ACTIVATE_PLATFORM_VPN;
44 import static android.os.PowerExemptionManager.REASON_OP_ACTIVATE_VPN;
45 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT;
46 import static android.os.PowerExemptionManager.REASON_PROC_STATE_PERSISTENT_UI;
47 import static android.os.PowerExemptionManager.REASON_PROC_STATE_TOP;
48 import static android.os.PowerExemptionManager.REASON_PROFILE_OWNER;
49 import static android.os.PowerExemptionManager.REASON_SERVICE_LAUNCH;
50 import static android.os.PowerExemptionManager.REASON_START_ACTIVITY_FLAG;
51 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
52 import static android.os.PowerExemptionManager.REASON_SYSTEM_ALLOW_LISTED;
53 import static android.os.PowerExemptionManager.REASON_SYSTEM_UID;
54 import static android.os.PowerExemptionManager.REASON_TEMP_ALLOWED_WHILE_IN_USE;
55 import static android.os.PowerExemptionManager.REASON_UID_VISIBLE;
56 import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
57 import static android.os.PowerExemptionManager.getReasonCodeFromProcState;
58 import static android.os.PowerExemptionManager.reasonCodeToString;
59 import static android.os.Process.INVALID_UID;
60 import static android.os.Process.NFC_UID;
61 import static android.os.Process.ROOT_UID;
62 import static android.os.Process.SHELL_UID;
63 import static android.os.Process.SYSTEM_UID;
64 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY;
65 
66 import static com.android.internal.messages.nano.SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICE_BG_LAUNCH;
67 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_BACKGROUND_CHECK;
68 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
69 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
70 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
71 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE;
72 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SERVICE_EXECUTING;
73 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_MU;
74 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE;
75 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SERVICE_EXECUTING;
76 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
77 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
78 
79 import android.Manifest;
80 import android.annotation.NonNull;
81 import android.annotation.Nullable;
82 import android.annotation.UptimeMillisLong;
83 import android.annotation.UserIdInt;
84 import android.app.ActivityManager;
85 import android.app.ActivityManagerInternal;
86 import android.app.ActivityManagerInternal.ServiceNotificationPolicy;
87 import android.app.ActivityThread;
88 import android.app.AppGlobals;
89 import android.app.AppOpsManager;
90 import android.app.ForegroundServiceStartNotAllowedException;
91 import android.app.IApplicationThread;
92 import android.app.IServiceConnection;
93 import android.app.Notification;
94 import android.app.NotificationManager;
95 import android.app.PendingIntent;
96 import android.app.RemoteServiceException.ForegroundServiceDidNotStartInTimeException;
97 import android.app.Service;
98 import android.app.ServiceStartArgs;
99 import android.app.admin.DevicePolicyEventLogger;
100 import android.app.compat.CompatChanges;
101 import android.app.usage.UsageEvents;
102 import android.appwidget.AppWidgetManagerInternal;
103 import android.compat.annotation.ChangeId;
104 import android.compat.annotation.EnabledSince;
105 import android.compat.annotation.Overridable;
106 import android.content.ComponentName;
107 import android.content.ComponentName.WithComponentName;
108 import android.content.Context;
109 import android.content.IIntentSender;
110 import android.content.Intent;
111 import android.content.IntentSender;
112 import android.content.pm.ApplicationInfo;
113 import android.content.pm.PackageManager;
114 import android.content.pm.PackageManagerInternal;
115 import android.content.pm.ParceledListSlice;
116 import android.content.pm.ResolveInfo;
117 import android.content.pm.ServiceInfo;
118 import android.net.Uri;
119 import android.os.Binder;
120 import android.os.Build;
121 import android.os.Bundle;
122 import android.os.DeadObjectException;
123 import android.os.Handler;
124 import android.os.IBinder;
125 import android.os.Looper;
126 import android.os.Message;
127 import android.os.PowerExemptionManager;
128 import android.os.PowerExemptionManager.ReasonCode;
129 import android.os.Process;
130 import android.os.RemoteCallback;
131 import android.os.RemoteException;
132 import android.os.ServiceManager;
133 import android.os.SystemClock;
134 import android.os.SystemProperties;
135 import android.os.TransactionTooLargeException;
136 import android.os.UserHandle;
137 import android.os.UserManager;
138 import android.provider.Settings;
139 import android.stats.devicepolicy.DevicePolicyEnums;
140 import android.text.TextUtils;
141 import android.util.ArrayMap;
142 import android.util.ArraySet;
143 import android.util.EventLog;
144 import android.util.Pair;
145 import android.util.PrintWriterPrinter;
146 import android.util.Slog;
147 import android.util.SparseArray;
148 import android.util.SparseIntArray;
149 import android.util.SparseLongArray;
150 import android.util.TimeUtils;
151 import android.util.proto.ProtoOutputStream;
152 import android.webkit.WebViewZygote;
153 
154 import com.android.internal.R;
155 import com.android.internal.annotations.GuardedBy;
156 import com.android.internal.annotations.VisibleForTesting;
157 import com.android.internal.app.procstats.ServiceState;
158 import com.android.internal.messages.nano.SystemMessageProto;
159 import com.android.internal.notification.SystemNotificationChannels;
160 import com.android.internal.os.SomeArgs;
161 import com.android.internal.os.TransferPipe;
162 import com.android.internal.util.DumpUtils;
163 import com.android.internal.util.FastPrintWriter;
164 import com.android.internal.util.FrameworkStatsLog;
165 import com.android.server.AppStateTracker;
166 import com.android.server.LocalServices;
167 import com.android.server.SystemService;
168 import com.android.server.am.ActivityManagerService.ItemMatcher;
169 import com.android.server.uri.NeededUriGrants;
170 import com.android.server.wm.ActivityServiceConnectionsHolder;
171 
172 import java.io.FileDescriptor;
173 import java.io.IOException;
174 import java.io.PrintWriter;
175 import java.io.StringWriter;
176 import java.text.SimpleDateFormat;
177 import java.util.ArrayList;
178 import java.util.Comparator;
179 import java.util.List;
180 import java.util.Objects;
181 import java.util.Set;
182 import java.util.function.Predicate;
183 
184 public final class ActiveServices {
185     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
186     private static final String TAG_MU = TAG + POSTFIX_MU;
187     private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
188     private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
189 
190     private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
191     private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
192 
193     private static final boolean LOG_SERVICE_START_STOP = false;
194 
195     private static final boolean SHOW_DUNGEON_NOTIFICATION = false;
196 
197     // How long we wait for a service to finish executing.
198     static final int SERVICE_TIMEOUT = 20 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
199 
200     // How long we wait for a service to finish executing.
201     static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
202 
203     // How long the startForegroundService() grace period is to get around to
204     // calling startForeground() before we ANR + stop it.
205     static final int SERVICE_START_FOREGROUND_TIMEOUT = 10 * 1000 * Build.HW_TIMEOUT_MULTIPLIER;
206 
207     // Foreground service types that always get immediate notification display,
208     // expressed in the same bitmask format that ServiceRecord.foregroundServiceType
209     // uses.
210     static final int FGS_IMMEDIATE_DISPLAY_MASK =
211             ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
212                     | ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL
213                     | ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
214                     | ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION;
215 
216     final ActivityManagerService mAm;
217 
218     // Maximum number of services that we allow to start in the background
219     // at the same time.
220     final int mMaxStartingBackground;
221 
222     /**
223      * Master service bookkeeping, keyed by user number.
224      */
225     final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
226 
227     /**
228      * All currently bound service connections.  Keys are the IBinder of
229      * the client's IServiceConnection.
230      */
231     final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
232 
233     /**
234      * List of services that we have been asked to start,
235      * but haven't yet been able to.  It is used to hold start requests
236      * while waiting for their corresponding application thread to get
237      * going.
238      */
239     final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
240 
241     /**
242      * List of services that are scheduled to restart following a crash.
243      */
244     final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
245 
246     /**
247      * List of services that are in the process of being destroyed.
248      */
249     final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
250 
251     /**
252      * List of services for which display of the FGS notification has been deferred.
253      */
254     final ArrayList<ServiceRecord> mPendingFgsNotifications = new ArrayList<>();
255 
256     /**
257      * Whether there is a rate limit that suppresses immediate re-deferral of new FGS
258      * notifications from each app.  On by default, disabled only by shell command for
259      * test-suite purposes.  To disable the behavior more generally, use the usual
260      * DeviceConfig mechanism to set the rate limit interval to zero.
261      */
262     private boolean mFgsDeferralRateLimited = true;
263 
264     /**
265      * Uptime at which a given uid becomes eliglible again for FGS notification deferral
266      */
267     final SparseLongArray mFgsDeferralEligible = new SparseLongArray();
268 
269     /**
270      * Map of services that are asked to be brought up (start/binding) but not ready to.
271      */
272     private ArrayMap<ServiceRecord, ArrayList<Runnable>> mPendingBringups = new ArrayMap<>();
273 
274     /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
275     private ArrayList<ServiceRecord> mTmpCollectionResults = null;
276 
277     /** Mapping from uid to their foreground service AppOpCallbacks (if they have one). */
278     @GuardedBy("mAm")
279     private final SparseArray<AppOpCallback> mFgsAppOpCallbacks = new SparseArray<>();
280 
281     /**
282      * The list of packages with the service restart backoff disabled.
283      */
284     @GuardedBy("mAm")
285     private final ArraySet<String> mRestartBackoffDisabledPackages = new ArraySet<>();
286 
287     /**
288      * For keeping ActiveForegroundApps retaining state while the screen is off.
289      */
290     boolean mScreenOn = true;
291 
292     /** Amount of time to allow a last ANR message to exist before freeing the memory. */
293     static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
294 
295     String mLastAnrDump;
296 
297     AppWidgetManagerInternal mAppWidgetManagerInternal;
298 
299     // allowlisted packageName.
300     ArraySet<String> mAllowListWhileInUsePermissionInFgs = new ArraySet<>();
301 
302     // TODO: remove this after feature development is done
303     private static final SimpleDateFormat DATE_FORMATTER =
304             new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
305 
306     /**
307      * The BG-launch FGS restriction feature is going to be allowed only for apps targetSdkVersion
308      * is higher than R.
309      */
310     @ChangeId
311     @EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.S)
312     @Overridable
313     static final long FGS_BG_START_RESTRICTION_CHANGE_ID = 170668199L;
314 
315     /**
316      * If a service can not become foreground service due to BG-FGS-launch restriction or other
317      * reasons, throws an IllegalStateException.
318      */
319     @ChangeId
320     @EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.S)
321     static final long FGS_START_EXCEPTION_CHANGE_ID = 174041399L;
322 
323     final Runnable mLastAnrDumpClearer = new Runnable() {
324         @Override public void run() {
325             synchronized (mAm) {
326                 mLastAnrDump = null;
327             }
328         }
329     };
330 
331     /**
332      * Watch for apps being put into forced app standby, so we can step their fg
333      * services down.
334      */
335     class ForcedStandbyListener implements AppStateTracker.ServiceStateListener {
336         @Override
stopForegroundServicesForUidPackage(final int uid, final String packageName)337         public void stopForegroundServicesForUidPackage(final int uid, final String packageName) {
338             synchronized (mAm) {
339                 stopAllForegroundServicesLocked(uid, packageName);
340             }
341         }
342     }
343 
stopAllForegroundServicesLocked(final int uid, final String packageName)344     void stopAllForegroundServicesLocked(final int uid, final String packageName) {
345         final ServiceMap smap = getServiceMapLocked(UserHandle.getUserId(uid));
346         final int N = smap.mServicesByInstanceName.size();
347         final ArrayList<ServiceRecord> toStop = new ArrayList<>(N);
348         for (int i = 0; i < N; i++) {
349             final ServiceRecord r = smap.mServicesByInstanceName.valueAt(i);
350             if (uid == r.serviceInfo.applicationInfo.uid
351                     || packageName.equals(r.serviceInfo.packageName)) {
352                 if (r.isForeground) {
353                     toStop.add(r);
354                 }
355             }
356         }
357 
358         // Now stop them all
359         final int numToStop = toStop.size();
360         if (numToStop > 0 && DEBUG_FOREGROUND_SERVICE) {
361             Slog.i(TAG, "Package " + packageName + "/" + uid
362                     + " in FAS with foreground services");
363         }
364         for (int i = 0; i < numToStop; i++) {
365             final ServiceRecord r = toStop.get(i);
366             if (DEBUG_FOREGROUND_SERVICE) {
367                 Slog.i(TAG, "  Stopping fg for service " + r);
368             }
369             setServiceForegroundInnerLocked(r, 0, null, 0, 0);
370         }
371     }
372 
373     /**
374      * Information about an app that is currently running one or more foreground services.
375      * (This maps directly to the running apps we show in the notification.)
376      */
377     static final class ActiveForegroundApp {
378         String mPackageName;
379         int mUid;
380         CharSequence mLabel;
381         boolean mShownWhileScreenOn;
382         boolean mAppOnTop;
383         boolean mShownWhileTop;
384         long mStartTime;
385         long mStartVisibleTime;
386         long mEndTime;
387         int mNumActive;
388 
389         // Temp output of foregroundAppShownEnoughLocked
390         long mHideTime;
391     }
392 
393     /**
394      * Information about services for a single user.
395      */
396     final class ServiceMap extends Handler {
397         final int mUserId;
398         final ArrayMap<ComponentName, ServiceRecord> mServicesByInstanceName = new ArrayMap<>();
399         final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
400 
401         final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
402         /* XXX eventually I'd like to have this based on processes instead of services.
403          * That is, if we try to start two services in a row both running in the same
404          * process, this should be one entry in mStartingBackground for that one process
405          * that remains until all services in it are done.
406         final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
407                 = new ArrayMap<ProcessRecord, DelayingProcess>();
408         final ArrayList<DelayingProcess> mStartingProcessList
409                 = new ArrayList<DelayingProcess>();
410         */
411 
412         final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
413 
414         final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
415         boolean mActiveForegroundAppsChanged;
416 
417         static final int MSG_BG_START_TIMEOUT = 1;
418         static final int MSG_UPDATE_FOREGROUND_APPS = 2;
419         static final int MSG_ENSURE_NOT_START_BG = 3;
420 
ServiceMap(Looper looper, int userId)421         ServiceMap(Looper looper, int userId) {
422             super(looper);
423             mUserId = userId;
424         }
425 
426         @Override
handleMessage(Message msg)427         public void handleMessage(Message msg) {
428             switch (msg.what) {
429                 case MSG_BG_START_TIMEOUT: {
430                     synchronized (mAm) {
431                         rescheduleDelayedStartsLocked();
432                     }
433                 } break;
434                 case MSG_UPDATE_FOREGROUND_APPS: {
435                     updateForegroundApps(this);
436                 } break;
437                 case MSG_ENSURE_NOT_START_BG: {
438                     synchronized (mAm) {
439                         rescheduleDelayedStartsLocked();
440                     }
441                 } break;
442             }
443         }
444 
ensureNotStartingBackgroundLocked(ServiceRecord r)445         void ensureNotStartingBackgroundLocked(ServiceRecord r) {
446             if (mStartingBackground.remove(r)) {
447                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
448                         "No longer background starting: " + r);
449                 removeMessages(MSG_ENSURE_NOT_START_BG);
450                 Message msg = obtainMessage(MSG_ENSURE_NOT_START_BG);
451                 sendMessage(msg);
452             }
453             if (mDelayedStartList.remove(r)) {
454                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
455             }
456         }
457 
rescheduleDelayedStartsLocked()458         void rescheduleDelayedStartsLocked() {
459             removeMessages(MSG_BG_START_TIMEOUT);
460             final long now = SystemClock.uptimeMillis();
461             for (int i=0, N=mStartingBackground.size(); i<N; i++) {
462                 ServiceRecord r = mStartingBackground.get(i);
463                 if (r.startingBgTimeout <= now) {
464                     Slog.i(TAG, "Waited long enough for: " + r);
465                     mStartingBackground.remove(i);
466                     N--;
467                     i--;
468                 }
469             }
470             while (mDelayedStartList.size() > 0
471                     && mStartingBackground.size() < mMaxStartingBackground) {
472                 ServiceRecord r = mDelayedStartList.remove(0);
473                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
474                         "REM FR DELAY LIST (exec next): " + r);
475                 if (DEBUG_DELAYED_SERVICE) {
476                     if (mDelayedStartList.size() > 0) {
477                         Slog.v(TAG_SERVICE, "Remaining delayed list:");
478                         for (int i=0; i<mDelayedStartList.size(); i++) {
479                             Slog.v(TAG_SERVICE, "  #" + i + ": " + mDelayedStartList.get(i));
480                         }
481                     }
482                 }
483                 r.delayed = false;
484                 if (r.pendingStarts.size() <= 0) {
485                     Slog.wtf(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
486                             + " delayedStop=" + r.delayedStop);
487                 } else {
488                     try {
489                         startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false,
490                                 true);
491                     } catch (TransactionTooLargeException e) {
492                         // Ignore, nobody upstack cares.
493                     }
494                 }
495             }
496             if (mStartingBackground.size() > 0) {
497                 ServiceRecord next = mStartingBackground.get(0);
498                 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
499                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
500                         + ", can delay others up to " + when);
501                 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
502                 sendMessageAtTime(msg, when);
503             }
504             if (mStartingBackground.size() < mMaxStartingBackground) {
505                 mAm.backgroundServicesFinishedLocked(mUserId);
506             }
507         }
508     }
509 
ActiveServices(ActivityManagerService service)510     public ActiveServices(ActivityManagerService service) {
511         mAm = service;
512         int maxBg = 0;
513         try {
514             maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
515         } catch(RuntimeException e) {
516         }
517         mMaxStartingBackground = maxBg > 0
518                 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
519 
520         final IBinder b = ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);
521     }
522 
systemServicesReady()523     void systemServicesReady() {
524         AppStateTracker ast = LocalServices.getService(AppStateTracker.class);
525         ast.addServiceStateListener(new ForcedStandbyListener());
526         mAppWidgetManagerInternal = LocalServices.getService(AppWidgetManagerInternal.class);
527         setAllowListWhileInUsePermissionInFgs();
528     }
529 
setAllowListWhileInUsePermissionInFgs()530     private void setAllowListWhileInUsePermissionInFgs() {
531         final String attentionServicePackageName =
532                 mAm.mContext.getPackageManager().getAttentionServicePackageName();
533         if (!TextUtils.isEmpty(attentionServicePackageName)) {
534             mAllowListWhileInUsePermissionInFgs.add(attentionServicePackageName);
535         }
536         final String systemCaptionsServicePackageName =
537                 mAm.mContext.getPackageManager().getSystemCaptionsServicePackageName();
538         if (!TextUtils.isEmpty(systemCaptionsServicePackageName)) {
539             mAllowListWhileInUsePermissionInFgs.add(systemCaptionsServicePackageName);
540         }
541     }
542 
getServiceByNameLocked(ComponentName name, int callingUser)543     ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
544         // TODO: Deal with global services
545         if (DEBUG_MU)
546             Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
547         return getServiceMapLocked(callingUser).mServicesByInstanceName.get(name);
548     }
549 
hasBackgroundServicesLocked(int callingUser)550     boolean hasBackgroundServicesLocked(int callingUser) {
551         ServiceMap smap = mServiceMap.get(callingUser);
552         return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
553     }
554 
hasForegroundServiceNotificationLocked(String pkg, int userId, String channelId)555     boolean hasForegroundServiceNotificationLocked(String pkg, int userId, String channelId) {
556         final ServiceMap smap = mServiceMap.get(userId);
557         if (smap != null) {
558             for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
559                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
560                 if (sr.appInfo.packageName.equals(pkg) && sr.isForeground) {
561                     if (Objects.equals(sr.foregroundNoti.getChannelId(), channelId)) {
562                         if (DEBUG_FOREGROUND_SERVICE) {
563                             Slog.d(TAG_SERVICE, "Channel u" + userId + "/pkg=" + pkg
564                                     + "/channelId=" + channelId
565                                     + " has fg service notification");
566                         }
567                         return true;
568                     }
569                 }
570             }
571         }
572         return false;
573     }
574 
stopForegroundServicesForChannelLocked(String pkg, int userId, String channelId)575     void stopForegroundServicesForChannelLocked(String pkg, int userId, String channelId) {
576         final ServiceMap smap = mServiceMap.get(userId);
577         if (smap != null) {
578             for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
579                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
580                 if (sr.appInfo.packageName.equals(pkg) && sr.isForeground) {
581                     if (Objects.equals(sr.foregroundNoti.getChannelId(), channelId)) {
582                         if (DEBUG_FOREGROUND_SERVICE) {
583                             Slog.d(TAG_SERVICE, "Stopping FGS u" + userId + "/pkg=" + pkg
584                                     + "/channelId=" + channelId
585                                     + " for conversation channel clear");
586                         }
587                         stopServiceLocked(sr, false);
588                     }
589                 }
590             }
591         }
592     }
593 
getServiceMapLocked(int callingUser)594     private ServiceMap getServiceMapLocked(int callingUser) {
595         ServiceMap smap = mServiceMap.get(callingUser);
596         if (smap == null) {
597             smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
598             mServiceMap.put(callingUser, smap);
599         }
600         return smap;
601     }
602 
getServicesLocked(int callingUser)603     ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
604         return getServiceMapLocked(callingUser).mServicesByInstanceName;
605     }
606 
appRestrictedAnyInBackground(final int uid, final String packageName)607     private boolean appRestrictedAnyInBackground(final int uid, final String packageName) {
608         final int mode = mAm.getAppOpsManager().checkOpNoThrow(
609                 AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, uid, packageName);
610         return (mode != AppOpsManager.MODE_ALLOWED);
611     }
612 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId)613     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
614             int callingPid, int callingUid, boolean fgRequired, String callingPackage,
615             @Nullable String callingFeatureId, final int userId)
616             throws TransactionTooLargeException {
617         return startServiceLocked(caller, service, resolvedType, callingPid, callingUid, fgRequired,
618                 callingPackage, callingFeatureId, userId, false, null);
619     }
620 
startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, boolean fgRequired, String callingPackage, @Nullable String callingFeatureId, final int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)621     ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
622             int callingPid, int callingUid, boolean fgRequired,
623             String callingPackage, @Nullable String callingFeatureId, final int userId,
624             boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)
625             throws TransactionTooLargeException {
626         if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
627                 + " type=" + resolvedType + " args=" + service.getExtras());
628 
629         final boolean callerFg;
630         if (caller != null) {
631             final ProcessRecord callerApp = mAm.getRecordForAppLOSP(caller);
632             if (callerApp == null) {
633                 throw new SecurityException(
634                         "Unable to find app for caller " + caller
635                         + " (pid=" + callingPid
636                         + ") when starting service " + service);
637             }
638             callerFg = callerApp.mState.getSetSchedGroup() != ProcessList.SCHED_GROUP_BACKGROUND;
639         } else {
640             callerFg = true;
641         }
642 
643         ServiceLookupResult res =
644             retrieveServiceLocked(service, null, resolvedType, callingPackage,
645                     callingPid, callingUid, userId, true, callerFg, false, false);
646         if (res == null) {
647             return null;
648         }
649         if (res.record == null) {
650             return new ComponentName("!", res.permission != null
651                     ? res.permission : "private to package");
652         }
653 
654         ServiceRecord r = res.record;
655         setFgsRestrictionLocked(callingPackage, callingPid, callingUid, service, r, userId,
656                 allowBackgroundActivityStarts);
657 
658         if (!mAm.mUserController.exists(r.userId)) {
659             Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
660             return null;
661         }
662 
663         // If we're starting indirectly (e.g. from PendingIntent), figure out whether
664         // we're launching into an app in a background state.  This keys off of the same
665         // idleness state tracking as e.g. O+ background service start policy.
666         final boolean bgLaunch = !mAm.isUidActiveLOSP(r.appInfo.uid);
667 
668         // If the app has strict background restrictions, we treat any bg service
669         // start analogously to the legacy-app forced-restrictions case, regardless
670         // of its target SDK version.
671         boolean forcedStandby = false;
672         if (bgLaunch && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
673             if (DEBUG_FOREGROUND_SERVICE) {
674                 Slog.d(TAG, "Forcing bg-only service start only for " + r.shortInstanceName
675                         + " : bgLaunch=" + bgLaunch + " callerFg=" + callerFg);
676             }
677             forcedStandby = true;
678         }
679 
680         if (fgRequired) {
681             logFgsBackgroundStart(r);
682             if (r.mAllowStartForeground == REASON_DENIED && isBgFgsRestrictionEnabled(r)) {
683                 String msg = "startForegroundService() not allowed due to "
684                         + "mAllowStartForeground false: service "
685                         + r.shortInstanceName;
686                 Slog.w(TAG, msg);
687                 showFgsBgRestrictedNotificationLocked(r);
688                 logFGSStateChangeLocked(r,
689                         FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED,
690                         0);
691                 if (CompatChanges.isChangeEnabled(FGS_START_EXCEPTION_CHANGE_ID, callingUid)) {
692                     throw new ForegroundServiceStartNotAllowedException(msg);
693                 }
694                 return null;
695             }
696         }
697 
698         // If this is a direct-to-foreground start, make sure it is allowed as per the app op.
699         boolean forceSilentAbort = false;
700         if (fgRequired) {
701             final int mode = mAm.getAppOpsManager().checkOpNoThrow(
702                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
703             switch (mode) {
704                 case AppOpsManager.MODE_ALLOWED:
705                 case AppOpsManager.MODE_DEFAULT:
706                     // All okay.
707                     break;
708                 case AppOpsManager.MODE_IGNORED:
709                     // Not allowed, fall back to normal start service, failing siliently
710                     // if background check restricts that.
711                     Slog.w(TAG, "startForegroundService not allowed due to app op: service "
712                             + service + " to " + r.shortInstanceName
713                             + " from pid=" + callingPid + " uid=" + callingUid
714                             + " pkg=" + callingPackage);
715                     fgRequired = false;
716                     forceSilentAbort = true;
717                     break;
718                 default:
719                     return new ComponentName("!!", "foreground not allowed as per app op");
720             }
721         }
722 
723         // If this isn't a direct-to-foreground start, check our ability to kick off an
724         // arbitrary service
725         if (forcedStandby || (!r.startRequested && !fgRequired)) {
726             // Before going further -- if this app is not allowed to start services in the
727             // background, then at this point we aren't going to let it period.
728             final int allowed = mAm.getAppStartModeLOSP(r.appInfo.uid, r.packageName,
729                     r.appInfo.targetSdkVersion, callingPid, false, false, forcedStandby);
730             if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
731                 Slog.w(TAG, "Background start not allowed: service "
732                         + service + " to " + r.shortInstanceName
733                         + " from pid=" + callingPid + " uid=" + callingUid
734                         + " pkg=" + callingPackage + " startFg?=" + fgRequired);
735                 if (allowed == ActivityManager.APP_START_MODE_DELAYED || forceSilentAbort) {
736                     // In this case we are silently disabling the app, to disrupt as
737                     // little as possible existing apps.
738                     return null;
739                 }
740                 if (forcedStandby) {
741                     // This is an O+ app, but we might be here because the user has placed
742                     // it under strict background restrictions.  Don't punish the app if it's
743                     // trying to do the right thing but we're denying it for that reason.
744                     if (fgRequired) {
745                         if (DEBUG_BACKGROUND_CHECK) {
746                             Slog.v(TAG, "Silently dropping foreground service launch due to FAS");
747                         }
748                         return null;
749                     }
750                 }
751                 // This app knows it is in the new model where this operation is not
752                 // allowed, so tell it what has happened.
753                 UidRecord uidRec = mAm.mProcessList.getUidRecordLOSP(r.appInfo.uid);
754                 return new ComponentName("?", "app is in background uid " + uidRec);
755             }
756         }
757 
758         // At this point we've applied allowed-to-start policy based on whether this was
759         // an ordinary startService() or a startForegroundService().  Now, only require that
760         // the app follow through on the startForegroundService() -> startForeground()
761         // contract if it actually targets O+.
762         if (r.appInfo.targetSdkVersion < Build.VERSION_CODES.O && fgRequired) {
763             if (DEBUG_BACKGROUND_CHECK || DEBUG_FOREGROUND_SERVICE) {
764                 Slog.i(TAG, "startForegroundService() but host targets "
765                         + r.appInfo.targetSdkVersion + " - not requiring startForeground()");
766             }
767             fgRequired = false;
768         }
769 
770         // The package could be frozen (meaning it's doing surgery), defer the actual
771         // start until the package is unfrozen.
772         if (deferServiceBringupIfFrozenLocked(r, service, callingPackage, callingFeatureId,
773                 callingUid, callingPid, fgRequired, callerFg, userId, allowBackgroundActivityStarts,
774                 backgroundActivityStartsToken, false, null)) {
775             return null;
776         }
777 
778         // If permissions need a review before any of the app components can run,
779         // we do not start the service and launch a review activity if the calling app
780         // is in the foreground passing it a pending intent to start the service when
781         // review is completed.
782 
783         // XXX This is not dealing with fgRequired!
784         if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage, callingFeatureId,
785                 callingUid, service, callerFg, userId, false, null)) {
786             return null;
787         }
788 
789         return startServiceInnerLocked(r, service, callingUid, callingPid, fgRequired, callerFg,
790                 allowBackgroundActivityStarts, backgroundActivityStartsToken);
791     }
792 
startServiceInnerLocked(ServiceRecord r, Intent service, int callingUid, int callingPid, boolean fgRequired, boolean callerFg, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)793     private ComponentName startServiceInnerLocked(ServiceRecord r, Intent service,
794             int callingUid, int callingPid, boolean fgRequired, boolean callerFg,
795             boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken)
796             throws TransactionTooLargeException {
797         NeededUriGrants neededGrants = mAm.mUgmInternal.checkGrantUriPermissionFromIntent(
798                 service, callingUid, r.packageName, r.userId);
799         if (unscheduleServiceRestartLocked(r, callingUid, false)) {
800             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
801         }
802         r.lastActivity = SystemClock.uptimeMillis();
803         r.startRequested = true;
804         r.delayedStop = false;
805         r.fgRequired = fgRequired;
806         r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
807                 service, neededGrants, callingUid));
808 
809         if (fgRequired) {
810             // We are now effectively running a foreground service.
811             synchronized (mAm.mProcessStats.mLock) {
812                 final ServiceState stracker = r.getTracker();
813                 if (stracker != null) {
814                     stracker.setForeground(true, mAm.mProcessStats.getMemFactorLocked(),
815                             r.lastActivity);
816                 }
817             }
818             mAm.mAppOpsService.startOperation(AppOpsManager.getToken(mAm.mAppOpsService),
819                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null,
820                     true, false, null, false, AppOpsManager.ATTRIBUTION_FLAGS_NONE,
821                     AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE);
822         }
823 
824         final ServiceMap smap = getServiceMapLocked(r.userId);
825         boolean addToStarting = false;
826         if (!callerFg && !fgRequired && r.app == null
827                 && mAm.mUserController.hasStartedUserState(r.userId)) {
828             ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid);
829             if (proc == null || proc.mState.getCurProcState() > PROCESS_STATE_RECEIVER) {
830                 // If this is not coming from a foreground caller, then we may want
831                 // to delay the start if there are already other background services
832                 // that are starting.  This is to avoid process start spam when lots
833                 // of applications are all handling things like connectivity broadcasts.
834                 // We only do this for cached processes, because otherwise an application
835                 // can have assumptions about calling startService() for a service to run
836                 // in its own process, and for that process to not be killed before the
837                 // service is started.  This is especially the case for receivers, which
838                 // may start a service in onReceive() to do some additional work and have
839                 // initialized some global state as part of that.
840                 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
841                         + r + " in " + proc);
842                 if (r.delayed) {
843                     // This service is already scheduled for a delayed start; just leave
844                     // it still waiting.
845                     if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
846                     return r.name;
847                 }
848                 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
849                     // Something else is starting, delay!
850                     Slog.i(TAG_SERVICE, "Delaying start of: " + r);
851                     smap.mDelayedStartList.add(r);
852                     r.delayed = true;
853                     return r.name;
854                 }
855                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
856                 addToStarting = true;
857             } else if (proc.mState.getCurProcState() >= ActivityManager.PROCESS_STATE_SERVICE) {
858                 // We slightly loosen when we will enqueue this new service as a background
859                 // starting service we are waiting for, to also include processes that are
860                 // currently running other services or receivers.
861                 addToStarting = true;
862                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
863                         "Not delaying, but counting as bg: " + r);
864             } else if (DEBUG_DELAYED_STARTS) {
865                 StringBuilder sb = new StringBuilder(128);
866                 sb.append("Not potential delay (state=").append(proc.mState.getCurProcState())
867                         .append(' ').append(proc.mState.getAdjType());
868                 String reason = proc.mState.makeAdjReason();
869                 if (reason != null) {
870                     sb.append(' ');
871                     sb.append(reason);
872                 }
873                 sb.append("): ");
874                 sb.append(r.toString());
875                 Slog.v(TAG_SERVICE, sb.toString());
876             }
877         } else if (DEBUG_DELAYED_STARTS) {
878             if (callerFg || fgRequired) {
879                 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
880                         + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
881             } else if (r.app != null) {
882                 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
883             } else {
884                 Slog.v(TAG_SERVICE,
885                         "Not potential delay (user " + r.userId + " not started): " + r);
886             }
887         }
888         if (allowBackgroundActivityStarts) {
889             r.allowBgActivityStartsOnServiceStart(backgroundActivityStartsToken);
890         }
891         ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
892         return cmp;
893     }
894 
requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r, String callingPackage, @Nullable String callingFeatureId, int callingUid, Intent service, boolean callerFg, final int userId, final boolean isBinding, final IServiceConnection connection)895     private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
896             String callingPackage, @Nullable String callingFeatureId, int callingUid,
897             Intent service, boolean callerFg, final int userId,
898             final boolean isBinding, final IServiceConnection connection) {
899         if (mAm.getPackageManagerInternal().isPermissionsReviewRequired(
900                 r.packageName, r.userId)) {
901 
902             // Show a permission review UI only for starting/binding from a foreground app
903             if (!callerFg) {
904                 Slog.w(TAG, "u" + r.userId
905                         + (isBinding ? " Binding" : " Starting") + " a service in package"
906                         + r.packageName + " requires a permissions review");
907                 return false;
908             }
909 
910             final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
911             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
912                     | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
913                     | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
914             intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
915 
916             if (isBinding) {
917                 RemoteCallback callback = new RemoteCallback(
918                         new RemoteCallback.OnResultListener() {
919                             @Override
920                             public void onResult(Bundle result) {
921                                 synchronized (mAm) {
922                                     final long identity = Binder.clearCallingIdentity();
923                                     try {
924                                         if (!mPendingServices.contains(r)) {
925                                             return;
926                                         }
927                                         // If there is still a pending record, then the service
928                                         // binding request is still valid, so hook them up. We
929                                         // proceed only if the caller cleared the review requirement
930                                         // otherwise we unbind because the user didn't approve.
931                                         if (!mAm.getPackageManagerInternal()
932                                                 .isPermissionsReviewRequired(r.packageName,
933                                                     r.userId)) {
934                                             try {
935                                                 bringUpServiceLocked(r,
936                                                         service.getFlags(),
937                                                         callerFg,
938                                                         false /* whileRestarting */,
939                                                         false /* permissionsReviewRequired */,
940                                                         false /* packageFrozen */,
941                                                         true /* enqueueOomAdj */);
942                                             } catch (RemoteException e) {
943                                                 /* ignore - local call */
944                                             } finally {
945                                                 /* Will be a no-op if nothing pending */
946                                                 mAm.updateOomAdjPendingTargetsLocked(
947                                                         OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
948                                             }
949                                         } else {
950                                             unbindServiceLocked(connection);
951                                         }
952                                     } finally {
953                                         Binder.restoreCallingIdentity(identity);
954                                     }
955                                 }
956                             }
957                         });
958                 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
959             } else { // Starting a service
960                 IIntentSender target = mAm.mPendingIntentController.getIntentSender(
961                         ActivityManager.INTENT_SENDER_SERVICE, callingPackage, callingFeatureId,
962                         callingUid, userId, null, null, 0, new Intent[]{service},
963                         new String[]{service.resolveType(mAm.mContext.getContentResolver())},
964                         PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
965                         | PendingIntent.FLAG_IMMUTABLE, null);
966                 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
967             }
968 
969             if (DEBUG_PERMISSIONS_REVIEW) {
970                 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
971                         + r.packageName);
972             }
973 
974             mAm.mHandler.post(new Runnable() {
975                 @Override
976                 public void run() {
977                     mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
978                 }
979             });
980 
981             return false;
982         }
983 
984         return  true;
985     }
986 
987     /**
988      * Defer the service starting/binding until the package is unfrozen, if it's currently frozen.
989      *
990      * @return {@code true} if the binding is deferred because it's frozen.
991      */
992     @GuardedBy("mAm")
deferServiceBringupIfFrozenLocked(ServiceRecord s, Intent serviceIntent, String callingPackage, @Nullable String callingFeatureId, int callingUid, int callingPid, boolean fgRequired, boolean callerFg, int userId, boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken, boolean isBinding, IServiceConnection connection)993     private boolean deferServiceBringupIfFrozenLocked(ServiceRecord s, Intent serviceIntent,
994             String callingPackage, @Nullable String callingFeatureId,
995             int callingUid, int callingPid, boolean fgRequired, boolean callerFg, int userId,
996             boolean allowBackgroundActivityStarts, @Nullable IBinder backgroundActivityStartsToken,
997             boolean isBinding, IServiceConnection connection) {
998         final PackageManagerInternal pm = mAm.getPackageManagerInternal();
999         final boolean frozen = pm.isPackageFrozen(s.packageName, callingUid, s.userId);
1000         if (!frozen) {
1001             // Not frozen, it's okay to go
1002             return false;
1003         }
1004         ArrayList<Runnable> curPendingBringups = mPendingBringups.get(s);
1005         if (curPendingBringups == null) {
1006             curPendingBringups = new ArrayList<>();
1007             mPendingBringups.put(s, curPendingBringups);
1008         }
1009         curPendingBringups.add(new Runnable() {
1010             @Override
1011             public void run() {
1012                 synchronized (mAm) {
1013                     if (!mPendingBringups.containsKey(s)) {
1014                         return;
1015                     }
1016                     // binding request is still valid, so hook them up.
1017                     // Before doing so, check if it requires a permission review.
1018                     if (!requestStartTargetPermissionsReviewIfNeededLocked(s,
1019                                 callingPackage, callingFeatureId, callingUid,
1020                                 serviceIntent, callerFg, userId, isBinding, connection)) {
1021                         // Let's wait for the user approval.
1022                         return;
1023                     }
1024                     if (isBinding) {
1025                         try {
1026                             bringUpServiceLocked(s, serviceIntent.getFlags(), callerFg,
1027                                     false /* whileRestarting */,
1028                                     false /* permissionsReviewRequired */,
1029                                     false /* packageFrozen */,
1030                                     true /* enqueueOomAdj */);
1031                         } catch (TransactionTooLargeException e) {
1032                             /* ignore - local call */
1033                         } finally {
1034                             /* Will be a no-op if nothing pending */
1035                             mAm.updateOomAdjPendingTargetsLocked(
1036                                     OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
1037                         }
1038                     } else { // Starting a service
1039                         try {
1040                             startServiceInnerLocked(s, serviceIntent, callingUid, callingPid,
1041                                     fgRequired, callerFg, allowBackgroundActivityStarts,
1042                                     backgroundActivityStartsToken);
1043                         } catch (TransactionTooLargeException e) {
1044                             /* ignore - local call */
1045                         }
1046                     }
1047                 }
1048             }
1049         });
1050         return true;
1051     }
1052 
1053     @GuardedBy("mAm")
schedulePendingServiceStartLocked(String packageName, int userId)1054     void schedulePendingServiceStartLocked(String packageName, int userId) {
1055         int totalPendings = mPendingBringups.size();
1056         for (int i = totalPendings - 1; i >= 0 && totalPendings > 0;) {
1057             final ServiceRecord r = mPendingBringups.keyAt(i);
1058             if (r.userId != userId || !TextUtils.equals(r.packageName, packageName)) {
1059                 i--;
1060                 continue;
1061             }
1062             final ArrayList<Runnable> curPendingBringups = mPendingBringups.valueAt(i);
1063             if (curPendingBringups != null) {
1064                 for (int j = curPendingBringups.size() - 1; j >= 0; j--) {
1065                     curPendingBringups.get(j).run();
1066                 }
1067                 curPendingBringups.clear();
1068             }
1069             // Now, how many remaining ones we have after calling into above runnables
1070             final int curTotalPendings = mPendingBringups.size();
1071             // Don't call removeAt() here, as it could have been removed already by above runnables
1072             mPendingBringups.remove(r);
1073             if (totalPendings != curTotalPendings) {
1074                 // Okay, within the above Runnable.run(), the mPendingBringups is altered.
1075                 // Restart the loop, it won't call into those finished runnables
1076                 // since we've cleared the curPendingBringups above.
1077                 totalPendings = mPendingBringups.size();
1078                 i = totalPendings - 1;
1079             } else {
1080                 totalPendings = mPendingBringups.size();
1081                 i--;
1082             }
1083         }
1084     }
1085 
startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting)1086     ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
1087             boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
1088         synchronized (mAm.mProcessStats.mLock) {
1089             final ServiceState stracker = r.getTracker();
1090             if (stracker != null) {
1091                 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1092             }
1093         }
1094         r.callStart = false;
1095 
1096         final int uid = r.appInfo.uid;
1097         final String packageName = r.name.getPackageName();
1098         final String serviceName = r.name.getClassName();
1099         FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, uid, packageName,
1100                 serviceName, FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__START);
1101         mAm.mBatteryStatsService.noteServiceStartRunning(uid, packageName, serviceName);
1102         String error = bringUpServiceLocked(r, service.getFlags(), callerFg,
1103                 false /* whileRestarting */,
1104                 false /* permissionsReviewRequired */,
1105                 false /* packageFrozen */,
1106                 true /* enqueueOomAdj */);
1107         /* Will be a no-op if nothing pending */
1108         mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
1109         if (error != null) {
1110             return new ComponentName("!!", error);
1111         }
1112 
1113         if (r.startRequested && addToStarting) {
1114             boolean first = smap.mStartingBackground.size() == 0;
1115             smap.mStartingBackground.add(r);
1116             r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
1117             if (DEBUG_DELAYED_SERVICE) {
1118                 RuntimeException here = new RuntimeException("here");
1119                 here.fillInStackTrace();
1120                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
1121             } else if (DEBUG_DELAYED_STARTS) {
1122                 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
1123             }
1124             if (first) {
1125                 smap.rescheduleDelayedStartsLocked();
1126             }
1127         } else if (callerFg || r.fgRequired) {
1128             smap.ensureNotStartingBackgroundLocked(r);
1129         }
1130 
1131         return r.name;
1132     }
1133 
stopServiceLocked(ServiceRecord service, boolean enqueueOomAdj)1134     private void stopServiceLocked(ServiceRecord service, boolean enqueueOomAdj) {
1135         if (service.delayed) {
1136             // If service isn't actually running, but is being held in the
1137             // delayed list, then we need to keep it started but note that it
1138             // should be stopped once no longer delayed.
1139             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
1140             service.delayedStop = true;
1141             return;
1142         }
1143 
1144         final int uid = service.appInfo.uid;
1145         final String packageName = service.name.getPackageName();
1146         final String serviceName = service.name.getClassName();
1147         FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, uid, packageName,
1148                 serviceName, FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
1149         mAm.mBatteryStatsService.noteServiceStopRunning(uid, packageName, serviceName);
1150         service.startRequested = false;
1151         if (service.tracker != null) {
1152             synchronized (mAm.mProcessStats.mLock) {
1153                 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
1154                         SystemClock.uptimeMillis());
1155             }
1156         }
1157         service.callStart = false;
1158 
1159         bringDownServiceIfNeededLocked(service, false, false, enqueueOomAdj);
1160     }
1161 
stopServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int userId)1162     int stopServiceLocked(IApplicationThread caller, Intent service,
1163             String resolvedType, int userId) {
1164         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
1165                 + " type=" + resolvedType);
1166 
1167         final ProcessRecord callerApp = mAm.getRecordForAppLOSP(caller);
1168         if (caller != null && callerApp == null) {
1169             throw new SecurityException(
1170                     "Unable to find app for caller " + caller
1171                     + " (pid=" + Binder.getCallingPid()
1172                     + ") when stopping service " + service);
1173         }
1174 
1175         // If this service is active, make sure it is stopped.
1176         ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, null,
1177                 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false, false);
1178         if (r != null) {
1179             if (r.record != null) {
1180                 final long origId = Binder.clearCallingIdentity();
1181                 try {
1182                     stopServiceLocked(r.record, false);
1183                 } finally {
1184                     Binder.restoreCallingIdentity(origId);
1185                 }
1186                 return 1;
1187             }
1188             return -1;
1189         }
1190 
1191         return 0;
1192     }
1193 
stopInBackgroundLocked(int uid)1194     void stopInBackgroundLocked(int uid) {
1195         // Stop all services associated with this uid due to it going to the background
1196         // stopped state.
1197         ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
1198         ArrayList<ServiceRecord> stopping = null;
1199         if (services != null) {
1200             for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
1201                 ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
1202                 if (service.appInfo.uid == uid && service.startRequested) {
1203                     if (mAm.getAppStartModeLOSP(service.appInfo.uid, service.packageName,
1204                             service.appInfo.targetSdkVersion, -1, false, false, false)
1205                             != ActivityManager.APP_START_MODE_NORMAL) {
1206                         if (stopping == null) {
1207                             stopping = new ArrayList<>();
1208                         }
1209                         String compName = service.shortInstanceName;
1210                         EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
1211                         StringBuilder sb = new StringBuilder(64);
1212                         sb.append("Stopping service due to app idle: ");
1213                         UserHandle.formatUid(sb, service.appInfo.uid);
1214                         sb.append(" ");
1215                         TimeUtils.formatDuration(service.createRealTime
1216                                 - SystemClock.elapsedRealtime(), sb);
1217                         sb.append(" ");
1218                         sb.append(compName);
1219                         Slog.w(TAG, sb.toString());
1220                         stopping.add(service);
1221 
1222                         // If the app is under bg restrictions, also make sure that
1223                         // any notification is dismissed
1224                         if (appRestrictedAnyInBackground(
1225                                 service.appInfo.uid, service.packageName)) {
1226                             cancelForegroundNotificationLocked(service);
1227                         }
1228                     }
1229                 }
1230             }
1231             if (stopping != null) {
1232                 final int size = stopping.size();
1233                 for (int i = size - 1; i >= 0; i--) {
1234                     ServiceRecord service = stopping.get(i);
1235                     service.delayed = false;
1236                     services.ensureNotStartingBackgroundLocked(service);
1237                     stopServiceLocked(service, true);
1238                 }
1239                 if (size > 0) {
1240                     mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
1241                 }
1242             }
1243         }
1244     }
1245 
killMisbehavingService(ServiceRecord r, int appUid, int appPid, String localPackageName, int exceptionTypeId)1246     void killMisbehavingService(ServiceRecord r,
1247             int appUid, int appPid, String localPackageName, int exceptionTypeId) {
1248         synchronized (mAm) {
1249             if (!r.destroying) {
1250                 // This service is still alive, stop it.
1251                 stopServiceLocked(r, false);
1252             } else {
1253                 // Check if there is another instance of it being started in parallel,
1254                 // if so, stop that too to avoid spamming the system.
1255                 final ServiceMap smap = getServiceMapLocked(r.userId);
1256                 final ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
1257                 if (found != null) {
1258                     stopServiceLocked(found, false);
1259                 }
1260             }
1261             mAm.crashApplicationWithType(appUid, appPid, localPackageName, -1,
1262                     "Bad notification for startForeground", true /*force*/, exceptionTypeId);
1263         }
1264     }
1265 
peekServiceLocked(Intent service, String resolvedType, String callingPackage)1266     IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
1267         ServiceLookupResult r = retrieveServiceLocked(service, null, resolvedType, callingPackage,
1268                 Binder.getCallingPid(), Binder.getCallingUid(),
1269                 UserHandle.getCallingUserId(), false, false, false, false);
1270 
1271         IBinder ret = null;
1272         if (r != null) {
1273             // r.record is null if findServiceLocked() failed the caller permission check
1274             if (r.record == null) {
1275                 throw new SecurityException(
1276                         "Permission Denial: Accessing service"
1277                         + " from pid=" + Binder.getCallingPid()
1278                         + ", uid=" + Binder.getCallingUid()
1279                         + " requires " + r.permission);
1280             }
1281             IntentBindRecord ib = r.record.bindings.get(r.record.intent);
1282             if (ib != null) {
1283                 ret = ib.binder;
1284             }
1285         }
1286 
1287         return ret;
1288     }
1289 
stopServiceTokenLocked(ComponentName className, IBinder token, int startId)1290     boolean stopServiceTokenLocked(ComponentName className, IBinder token,
1291             int startId) {
1292         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
1293                 + " " + token + " startId=" + startId);
1294         ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
1295         if (r != null) {
1296             if (startId >= 0) {
1297                 // Asked to only stop if done with all work.  Note that
1298                 // to avoid leaks, we will take this as dropping all
1299                 // start items up to and including this one.
1300                 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
1301                 if (si != null) {
1302                     while (r.deliveredStarts.size() > 0) {
1303                         ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
1304                         cur.removeUriPermissionsLocked();
1305                         if (cur == si) {
1306                             break;
1307                         }
1308                     }
1309                 }
1310 
1311                 if (r.getLastStartId() != startId) {
1312                     return false;
1313                 }
1314 
1315                 if (r.deliveredStarts.size() > 0) {
1316                     Slog.w(TAG, "stopServiceToken startId " + startId
1317                             + " is last, but have " + r.deliveredStarts.size()
1318                             + " remaining args");
1319                 }
1320             }
1321 
1322             final int uid = r.appInfo.uid;
1323             final String packageName = r.name.getPackageName();
1324             final String serviceName = r.name.getClassName();
1325             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_STATE_CHANGED, uid, packageName,
1326                     serviceName, FrameworkStatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
1327             mAm.mBatteryStatsService.noteServiceStopRunning(uid, packageName, serviceName);
1328             r.startRequested = false;
1329             if (r.tracker != null) {
1330                 synchronized (mAm.mProcessStats.mLock) {
1331                     r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
1332                             SystemClock.uptimeMillis());
1333                 }
1334             }
1335             r.callStart = false;
1336             final long origId = Binder.clearCallingIdentity();
1337             bringDownServiceIfNeededLocked(r, false, false, false);
1338             Binder.restoreCallingIdentity(origId);
1339             return true;
1340         }
1341         return false;
1342     }
1343 
setServiceForegroundLocked(ComponentName className, IBinder token, int id, Notification notification, int flags, int foregroundServiceType)1344     public void setServiceForegroundLocked(ComponentName className, IBinder token,
1345             int id, Notification notification, int flags, int foregroundServiceType) {
1346         final int userId = UserHandle.getCallingUserId();
1347         final long origId = Binder.clearCallingIdentity();
1348         try {
1349             ServiceRecord r = findServiceLocked(className, token, userId);
1350             if (r != null) {
1351                 setServiceForegroundInnerLocked(r, id, notification, flags, foregroundServiceType);
1352             }
1353         } finally {
1354             Binder.restoreCallingIdentity(origId);
1355         }
1356     }
1357 
1358     /**
1359      * Return the current foregroundServiceType of the ServiceRecord.
1360      * @param className ComponentName of the Service class.
1361      * @param token IBinder token.
1362      * @return current foreground service type.
1363      */
getForegroundServiceTypeLocked(ComponentName className, IBinder token)1364     public int getForegroundServiceTypeLocked(ComponentName className, IBinder token) {
1365         final int userId = UserHandle.getCallingUserId();
1366         final long origId = Binder.clearCallingIdentity();
1367         int ret = ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
1368         try {
1369             ServiceRecord r = findServiceLocked(className, token, userId);
1370             if (r != null) {
1371                 ret = r.foregroundServiceType;
1372             }
1373         } finally {
1374             Binder.restoreCallingIdentity(origId);
1375         }
1376         return ret;
1377     }
1378 
foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed)1379     boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
1380         if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
1381                 + aa.mUid);
1382         boolean canRemove = false;
1383         aa.mHideTime = Long.MAX_VALUE;
1384         if (aa.mShownWhileTop) {
1385             // If the app was ever at the top of the screen while the foreground
1386             // service was running, then we can always just immediately remove it.
1387             canRemove = true;
1388             if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
1389         } else if (mScreenOn || aa.mShownWhileScreenOn) {
1390             final long minTime = aa.mStartVisibleTime
1391                     + (aa.mStartTime != aa.mStartVisibleTime
1392                             ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
1393                             : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
1394             if (nowElapsed >= minTime) {
1395                 // If shown while the screen is on, and it has been shown for
1396                 // at least the minimum show time, then we can now remove it.
1397                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
1398                 canRemove = true;
1399             } else {
1400                 // This is when we will be okay to stop telling the user.
1401                 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
1402                 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
1403                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
1404                         + " with screen on");
1405             }
1406         } else {
1407             final long minTime = aa.mEndTime
1408                     + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
1409             if (nowElapsed >= minTime) {
1410                 // If the foreground service has only run while the screen is
1411                 // off, but it has been gone now for long enough that we won't
1412                 // care to tell the user about it when the screen comes back on,
1413                 // then we can remove it now.
1414                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
1415                 canRemove = true;
1416             } else {
1417                 // This is when we won't care about this old fg service.
1418                 aa.mHideTime = minTime;
1419                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
1420                         + " with screen off");
1421             }
1422         }
1423         return canRemove;
1424     }
1425 
updateForegroundApps(ServiceMap smap)1426     void updateForegroundApps(ServiceMap smap) {
1427         // This is called from the handler without the lock held.
1428         ArrayList<ActiveForegroundApp> active = null;
1429         synchronized (mAm) {
1430             final long now = SystemClock.elapsedRealtime();
1431             long nextUpdateTime = Long.MAX_VALUE;
1432             if (smap != null) {
1433                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
1434                         + smap.mUserId);
1435                 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
1436                     ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
1437                     if (aa.mEndTime != 0) {
1438                         boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
1439                         if (canRemove) {
1440                             // This was up for longer than the timeout, so just remove immediately.
1441                             smap.mActiveForegroundApps.removeAt(i);
1442                             smap.mActiveForegroundAppsChanged = true;
1443                             continue;
1444                         }
1445                         if (aa.mHideTime < nextUpdateTime) {
1446                             nextUpdateTime = aa.mHideTime;
1447                         }
1448                     }
1449                     if (!aa.mAppOnTop) {
1450                         // Transitioning a fg-service host app out of top: if it's bg restricted,
1451                         // it loses the fg service state now.
1452                         if (!appRestrictedAnyInBackground(aa.mUid, aa.mPackageName)) {
1453                             if (active == null) {
1454                                 active = new ArrayList<>();
1455                             }
1456                             if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
1457                                     + aa.mPackageName + ", uid=" + aa.mUid);
1458                             active.add(aa);
1459                         } else {
1460                             if (DEBUG_FOREGROUND_SERVICE) {
1461                                 Slog.d(TAG, "bg-restricted app "
1462                                         + aa.mPackageName + "/" + aa.mUid
1463                                         + " exiting top; demoting fg services ");
1464                             }
1465                             stopAllForegroundServicesLocked(aa.mUid, aa.mPackageName);
1466                         }
1467                     }
1468                 }
1469                 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1470                 if (nextUpdateTime < Long.MAX_VALUE) {
1471                     if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
1472                             + (nextUpdateTime-now));
1473                     Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1474                     smap.sendMessageAtTime(msg, nextUpdateTime
1475                             + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
1476                 }
1477             }
1478             if (!smap.mActiveForegroundAppsChanged) {
1479                 return;
1480             }
1481             smap.mActiveForegroundAppsChanged = false;
1482         }
1483 
1484         if (!SHOW_DUNGEON_NOTIFICATION) {
1485             return;
1486         }
1487 
1488         final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
1489                 Context.NOTIFICATION_SERVICE);
1490         final Context context = mAm.mContext;
1491 
1492         if (active != null) {
1493             for (int i = 0; i < active.size(); i++) {
1494                 ActiveForegroundApp aa = active.get(i);
1495                 if (aa.mLabel == null) {
1496                     PackageManager pm = context.getPackageManager();
1497                     try {
1498                         ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
1499                                 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
1500                         aa.mLabel = ai.loadLabel(pm);
1501                     } catch (PackageManager.NameNotFoundException e) {
1502                         aa.mLabel = aa.mPackageName;
1503                     }
1504                 }
1505             }
1506 
1507             Intent intent;
1508             String title;
1509             String msg;
1510             String[] pkgs;
1511             final long nowElapsed = SystemClock.elapsedRealtime();
1512             long oldestStartTime = nowElapsed;
1513             if (active.size() == 1) {
1514                 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1515                 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
1516                 title = context.getString(
1517                         R.string.foreground_service_app_in_background, active.get(0).mLabel);
1518                 msg = context.getString(R.string.foreground_service_tap_for_details);
1519                 pkgs = new String[] { active.get(0).mPackageName };
1520                 oldestStartTime = active.get(0).mStartTime;
1521             } else {
1522                 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
1523                 pkgs = new String[active.size()];
1524                 for (int i = 0; i < active.size(); i++) {
1525                     pkgs[i] = active.get(i).mPackageName;
1526                     oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
1527                 }
1528                 intent.putExtra("packages", pkgs);
1529                 title = context.getString(
1530                         R.string.foreground_service_apps_in_background, active.size());
1531                 msg = active.get(0).mLabel.toString();
1532                 for (int i = 1; i < active.size(); i++) {
1533                     msg = context.getString(R.string.foreground_service_multiple_separator,
1534                             msg, active.get(i).mLabel);
1535                 }
1536             }
1537             Bundle notificationBundle = new Bundle();
1538             notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
1539             Notification.Builder n =
1540                     new Notification.Builder(context,
1541                             SystemNotificationChannels.FOREGROUND_SERVICE)
1542                             .addExtras(notificationBundle)
1543                             .setSmallIcon(R.drawable.stat_sys_vitals)
1544                             .setOngoing(true)
1545                             .setShowWhen(oldestStartTime < nowElapsed)
1546                             .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
1547                             .setColor(context.getColor(
1548                                     com.android.internal.R.color.system_notification_accent_color))
1549                             .setContentTitle(title)
1550                             .setContentText(msg)
1551                             .setContentIntent(
1552                                     PendingIntent.getActivityAsUser(context, 0, intent,
1553                                             PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE_UNAUDITED,
1554                                             null, new UserHandle(smap.mUserId)));
1555             nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1556                     n.build(), new UserHandle(smap.mUserId));
1557         } else {
1558             nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
1559                     new UserHandle(smap.mUserId));
1560         }
1561     }
1562 
requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed)1563     private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
1564         Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
1565         if (timeElapsed != 0) {
1566             smap.sendMessageAtTime(msg,
1567                     timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
1568         } else {
1569             smap.mActiveForegroundAppsChanged = true;
1570             smap.sendMessage(msg);
1571         }
1572     }
1573 
decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r)1574     private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
1575         ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1576         if (active != null) {
1577             active.mNumActive--;
1578             if (active.mNumActive <= 0) {
1579                 active.mEndTime = SystemClock.elapsedRealtime();
1580                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
1581                 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
1582                     // Have been active for long enough that we will remove it immediately.
1583                     smap.mActiveForegroundApps.remove(r.packageName);
1584                     smap.mActiveForegroundAppsChanged = true;
1585                     requestUpdateActiveForegroundAppsLocked(smap, 0);
1586                 } else if (active.mHideTime < Long.MAX_VALUE){
1587                     requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
1588                 }
1589             }
1590         }
1591     }
1592 
updateScreenStateLocked(boolean screenOn)1593     void updateScreenStateLocked(boolean screenOn) {
1594         if (mScreenOn != screenOn) {
1595             mScreenOn = screenOn;
1596 
1597             // If screen is turning on, then we now reset the start time of any foreground
1598             // services that were started while the screen was off.
1599             if (screenOn) {
1600                 final long nowElapsed = SystemClock.elapsedRealtime();
1601                 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
1602                 for (int i = mServiceMap.size()-1; i >= 0; i--) {
1603                     ServiceMap smap = mServiceMap.valueAt(i);
1604                     long nextUpdateTime = Long.MAX_VALUE;
1605                     boolean changed = false;
1606                     for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1607                         ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1608                         if (active.mEndTime == 0) {
1609                             if (!active.mShownWhileScreenOn) {
1610                                 active.mShownWhileScreenOn = true;
1611                                 active.mStartVisibleTime = nowElapsed;
1612                             }
1613                         } else {
1614                             if (!active.mShownWhileScreenOn
1615                                     && active.mStartVisibleTime == active.mStartTime) {
1616                                 // If this was never shown while the screen was on, then we will
1617                                 // count the time it started being visible as now, to tell the user
1618                                 // about it now that they have a screen to look at.
1619                                 active.mEndTime = active.mStartVisibleTime = nowElapsed;
1620                             }
1621                             if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
1622                                 // Have been active for long enough that we will remove it
1623                                 // immediately.
1624                                 smap.mActiveForegroundApps.remove(active.mPackageName);
1625                                 smap.mActiveForegroundAppsChanged = true;
1626                                 changed = true;
1627                             } else {
1628                                 if (active.mHideTime < nextUpdateTime) {
1629                                     nextUpdateTime = active.mHideTime;
1630                                 }
1631                             }
1632                         }
1633                     }
1634                     if (changed) {
1635                         // Need to immediately update.
1636                         requestUpdateActiveForegroundAppsLocked(smap, 0);
1637                     } else if (nextUpdateTime < Long.MAX_VALUE) {
1638                         requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
1639                     }
1640                 }
1641             }
1642         }
1643     }
1644 
foregroundServiceProcStateChangedLocked(UidRecord uidRec)1645     void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
1646         ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.getUid()));
1647         if (smap != null) {
1648             boolean changed = false;
1649             for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
1650                 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1651                 if (active.mUid == uidRec.getUid()) {
1652                     if (uidRec.getCurProcState() <= PROCESS_STATE_TOP) {
1653                         if (!active.mAppOnTop) {
1654                             active.mAppOnTop = true;
1655                             changed = true;
1656                         }
1657                         active.mShownWhileTop = true;
1658                     } else if (active.mAppOnTop) {
1659                         active.mAppOnTop = false;
1660                         changed = true;
1661                     }
1662                 }
1663             }
1664             if (changed) {
1665                 requestUpdateActiveForegroundAppsLocked(smap, 0);
1666             }
1667         }
1668     }
1669 
appIsTopLocked(int uid)1670     private boolean appIsTopLocked(int uid) {
1671         return mAm.getUidStateLocked(uid) <= PROCESS_STATE_TOP;
1672     }
1673 
1674     /**
1675      * @param id Notification ID.  Zero === exit foreground state for the given service.
1676      */
setServiceForegroundInnerLocked(final ServiceRecord r, int id, Notification notification, int flags, int foregroundServiceType)1677     private void setServiceForegroundInnerLocked(final ServiceRecord r, int id,
1678             Notification notification, int flags, int foregroundServiceType) {
1679         if (id != 0) {
1680             if (notification == null) {
1681                 throw new IllegalArgumentException("null notification");
1682             }
1683             // Instant apps need permission to create foreground services.
1684             if (r.appInfo.isInstantApp()) {
1685                 final int mode = mAm.getAppOpsManager().checkOpNoThrow(
1686                         AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1687                         r.appInfo.uid,
1688                         r.appInfo.packageName);
1689                 switch (mode) {
1690                     case AppOpsManager.MODE_ALLOWED:
1691                         break;
1692                     case AppOpsManager.MODE_IGNORED:
1693                         Slog.w(TAG, "Instant app " + r.appInfo.packageName
1694                                 + " does not have permission to create foreground services"
1695                                 + ", ignoring.");
1696                         return;
1697                     case AppOpsManager.MODE_ERRORED:
1698                         throw new SecurityException("Instant app " + r.appInfo.packageName
1699                                 + " does not have permission to create foreground services");
1700                     default:
1701                         mAm.enforcePermission(
1702                                 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1703                                 r.app.getPid(), r.appInfo.uid, "startForeground");
1704                 }
1705             } else {
1706                 if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
1707                     mAm.enforcePermission(
1708                             android.Manifest.permission.FOREGROUND_SERVICE,
1709                             r.app.getPid(), r.appInfo.uid, "startForeground");
1710                 }
1711 
1712                 int manifestType = r.serviceInfo.getForegroundServiceType();
1713                 // If passed in foreground service type is FOREGROUND_SERVICE_TYPE_MANIFEST,
1714                 // consider it is the same as manifest foreground service type.
1715                 if (foregroundServiceType == FOREGROUND_SERVICE_TYPE_MANIFEST) {
1716                     foregroundServiceType = manifestType;
1717                 }
1718                 // Check the passed in foreground service type flags is a subset of manifest
1719                 // foreground service type flags.
1720                 if ((foregroundServiceType & manifestType) != foregroundServiceType) {
1721                     throw new IllegalArgumentException("foregroundServiceType "
1722                         + String.format("0x%08X", foregroundServiceType)
1723                         + " is not a subset of foregroundServiceType attribute "
1724                         +  String.format("0x%08X", manifestType)
1725                         + " in service element of manifest file");
1726                 }
1727             }
1728 
1729             boolean alreadyStartedOp = false;
1730             boolean stopProcStatsOp = false;
1731             if (r.fgRequired) {
1732                 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
1733                     Slog.i(TAG, "Service called startForeground() as required: " + r);
1734                 }
1735                 r.fgRequired = false;
1736                 r.fgWaiting = false;
1737                 alreadyStartedOp = stopProcStatsOp = true;
1738                 mAm.mHandler.removeMessages(
1739                         ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1740             }
1741 
1742             final ProcessServiceRecord psr = r.app.mServices;
1743             try {
1744                 boolean ignoreForeground = false;
1745                 final int mode = mAm.getAppOpsManager().checkOpNoThrow(
1746                         AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName);
1747                 switch (mode) {
1748                     case AppOpsManager.MODE_ALLOWED:
1749                     case AppOpsManager.MODE_DEFAULT:
1750                         // All okay.
1751                         break;
1752                     case AppOpsManager.MODE_IGNORED:
1753                         // Whoops, silently ignore this.
1754                         Slog.w(TAG, "Service.startForeground() not allowed due to app op: service "
1755                                 + r.shortInstanceName);
1756                         ignoreForeground = true;
1757                         break;
1758                     default:
1759                         throw new SecurityException("Foreground not allowed as per app op");
1760                 }
1761 
1762                 // Apps that are TOP or effectively similar may call startForeground() on
1763                 // their services even if they are restricted from doing that while in bg.
1764                 if (!ignoreForeground
1765                         && !appIsTopLocked(r.appInfo.uid)
1766                         && appRestrictedAnyInBackground(r.appInfo.uid, r.packageName)) {
1767                     Slog.w(TAG,
1768                             "Service.startForeground() not allowed due to bg restriction: service "
1769                                     + r.shortInstanceName);
1770                     // Back off of any foreground expectations around this service, since we've
1771                     // just turned down its fg request.
1772                     updateServiceForegroundLocked(psr, false);
1773                     ignoreForeground = true;
1774                 }
1775 
1776                 if (!ignoreForeground) {
1777                     if (r.mStartForegroundCount == 0) {
1778                         /*
1779                         If the service was started with startService(), not
1780                         startForegroundService(), and if startForeground() isn't called within
1781                         mFgsStartForegroundTimeoutMs, then we check the state of the app
1782                         (who owns the service, which is the app that called startForeground())
1783                         again. If the app is in the foreground, or in any other cases where
1784                         FGS-starts are allowed, then we still allow the FGS to be started.
1785                         Otherwise, startForeground() would fail.
1786 
1787                         If the service was started with startForegroundService(), then the service
1788                         must call startForeground() within a timeout anyway, so we don't need this
1789                         check.
1790                         */
1791                         if (!r.fgRequired) {
1792                             final long delayMs = SystemClock.elapsedRealtime() - r.createRealTime;
1793                             if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) {
1794                                 resetFgsRestrictionLocked(r);
1795                                 setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
1796                                         r.appInfo.uid, r.intent.getIntent(), r, r.userId,false);
1797                                 final String temp = "startForegroundDelayMs:" + delayMs;
1798                                 if (r.mInfoAllowStartForeground != null) {
1799                                     r.mInfoAllowStartForeground += "; " + temp;
1800                                 } else {
1801                                     r.mInfoAllowStartForeground = temp;
1802                                 }
1803                                 r.mLoggedInfoAllowStartForeground = false;
1804                             }
1805                         }
1806                     } else if (r.mStartForegroundCount >= 1) {
1807                         // The second or later time startForeground() is called after service is
1808                         // started. Check for app state again.
1809                         final long delayMs = SystemClock.elapsedRealtime() -
1810                                 r.mLastSetFgsRestrictionTime;
1811                         if (delayMs > mAm.mConstants.mFgsStartForegroundTimeoutMs) {
1812                             setFgsRestrictionLocked(r.serviceInfo.packageName, r.app.getPid(),
1813                                     r.appInfo.uid, r.intent.getIntent(), r, r.userId,false);
1814                         }
1815                     }
1816                     // If the foreground service is not started from TOP process, do not allow it to
1817                     // have while-in-use location/camera/microphone access.
1818                     if (!r.mAllowWhileInUsePermissionInFgs) {
1819                         Slog.w(TAG,
1820                                 "Foreground service started from background can not have "
1821                                         + "location/camera/microphone access: service "
1822                                         + r.shortInstanceName);
1823                     }
1824                     logFgsBackgroundStart(r);
1825                     if (r.mAllowStartForeground == REASON_DENIED && isBgFgsRestrictionEnabled(r)) {
1826                         final String msg = "Service.startForeground() not allowed due to "
1827                                 + "mAllowStartForeground false: service "
1828                                 + r.shortInstanceName;
1829                         Slog.w(TAG, msg);
1830                         showFgsBgRestrictedNotificationLocked(r);
1831                         updateServiceForegroundLocked(psr, true);
1832                         ignoreForeground = true;
1833                         logFGSStateChangeLocked(r,
1834                                 FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__DENIED,
1835                                 0);
1836                         if (CompatChanges.isChangeEnabled(FGS_START_EXCEPTION_CHANGE_ID,
1837                                 r.appInfo.uid)) {
1838                             throw new ForegroundServiceStartNotAllowedException(msg);
1839                         }
1840                     }
1841                 }
1842 
1843                 // Apps under strict background restrictions simply don't get to have foreground
1844                 // services, so now that we've enforced the startForegroundService() contract
1845                 // we only do the machinery of making the service foreground when the app
1846                 // is not restricted.
1847                 if (!ignoreForeground) {
1848                     if (r.foregroundId != id) {
1849                         cancelForegroundNotificationLocked(r);
1850                         r.foregroundId = id;
1851                     }
1852                     notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1853                     r.foregroundNoti = notification;
1854                     r.foregroundServiceType = foregroundServiceType;
1855                     if (!r.isForeground) {
1856                         final ServiceMap smap = getServiceMapLocked(r.userId);
1857                         if (smap != null) {
1858                             ActiveForegroundApp active = smap.mActiveForegroundApps
1859                                     .get(r.packageName);
1860                             if (active == null) {
1861                                 active = new ActiveForegroundApp();
1862                                 active.mPackageName = r.packageName;
1863                                 active.mUid = r.appInfo.uid;
1864                                 active.mShownWhileScreenOn = mScreenOn;
1865                                 if (r.app != null) {
1866                                     final UidRecord uidRec = r.app.getUidRecord();
1867                                     if (uidRec != null) {
1868                                         active.mAppOnTop = active.mShownWhileTop =
1869                                                 uidRec.getCurProcState() <= PROCESS_STATE_TOP;
1870                                     }
1871                                 }
1872                                 active.mStartTime = active.mStartVisibleTime
1873                                         = SystemClock.elapsedRealtime();
1874                                 smap.mActiveForegroundApps.put(r.packageName, active);
1875                                 requestUpdateActiveForegroundAppsLocked(smap, 0);
1876                             }
1877                             active.mNumActive++;
1878                         }
1879                         r.isForeground = true;
1880                         // The logging of FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER event could
1881                         // be deferred, make a copy of mAllowStartForeground and
1882                         // mAllowWhileInUsePermissionInFgs.
1883                         r.mAllowStartForegroundAtEntering = r.mAllowStartForeground;
1884                         r.mAllowWhileInUsePermissionInFgsAtEntering =
1885                                 r.mAllowWhileInUsePermissionInFgs;
1886                         r.mStartForegroundCount++;
1887                         r.mFgsEnterTime = SystemClock.uptimeMillis();
1888                         if (!stopProcStatsOp) {
1889                             synchronized (mAm.mProcessStats.mLock) {
1890                                 final ServiceState stracker = r.getTracker();
1891                                 if (stracker != null) {
1892                                     stracker.setForeground(true,
1893                                             mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
1894                                 }
1895                             }
1896                         } else {
1897                             stopProcStatsOp = false;
1898                         }
1899 
1900                         mAm.mAppOpsService.startOperation(
1901                                 AppOpsManager.getToken(mAm.mAppOpsService),
1902                                 AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1903                                 null, true, false, "", false, AppOpsManager.ATTRIBUTION_FLAGS_NONE,
1904                                 AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE);
1905                         registerAppOpCallbackLocked(r);
1906                         mAm.updateForegroundServiceUsageStats(r.name, r.userId, true);
1907                         logFGSStateChangeLocked(r,
1908                                 FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER,
1909                                 0);
1910                     }
1911                     // Even if the service is already a FGS, we need to update the notification,
1912                     // so we need to call it again.
1913                     r.postNotification();
1914                     if (r.app != null) {
1915                         updateServiceForegroundLocked(psr, true);
1916                     }
1917                     getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1918                     mAm.notifyPackageUse(r.serviceInfo.packageName,
1919                             PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1920                 } else {
1921                     if (DEBUG_FOREGROUND_SERVICE) {
1922                         Slog.d(TAG, "Suppressing startForeground() for FAS " + r);
1923                     }
1924                 }
1925             } finally {
1926                 if (stopProcStatsOp) {
1927                     // We got through to this point with it actively being started foreground,
1928                     // and never decided we wanted to keep it like that, so drop it.
1929                     synchronized (mAm.mProcessStats.mLock) {
1930                         final ServiceState stracker = r.getTracker();
1931                         if (stracker != null) {
1932                             stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1933                                     SystemClock.uptimeMillis());
1934                         }
1935                     }
1936                 }
1937                 if (alreadyStartedOp) {
1938                     // If we had previously done a start op for direct foreground start,
1939                     // we have cleared the flag so can now drop it.
1940                     mAm.mAppOpsService.finishOperation(
1941                             AppOpsManager.getToken(mAm.mAppOpsService),
1942                             AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName,
1943                             null);
1944                 }
1945             }
1946         } else {
1947             if (r.isForeground) {
1948                 final ServiceMap smap = getServiceMapLocked(r.userId);
1949                 if (smap != null) {
1950                     decActiveForegroundAppLocked(smap, r);
1951                 }
1952 
1953                 // Adjust notification handling before setting isForeground to false, because
1954                 // that state is relevant to the notification policy side.
1955                 // Leave the time-to-display as already set: re-entering foreground mode will
1956                 // only resume the previous quiet timeout, or will display immediately if the
1957                 // deferral period had already passed.
1958                 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
1959                     cancelForegroundNotificationLocked(r);
1960                     r.foregroundId = 0;
1961                     r.foregroundNoti = null;
1962                 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1963                     // if it's been deferred, force to visibility
1964                     if (!r.mFgsNotificationShown) {
1965                         r.postNotification();
1966                     }
1967                     dropFgsNotificationStateLocked(r);
1968                     if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1969                         r.foregroundId = 0;
1970                         r.foregroundNoti = null;
1971                     }
1972                 }
1973 
1974                 r.isForeground = false;
1975                 r.mFgsExitTime = SystemClock.uptimeMillis();
1976                 synchronized (mAm.mProcessStats.mLock) {
1977                     final ServiceState stracker = r.getTracker();
1978                     if (stracker != null) {
1979                         stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(),
1980                                 SystemClock.uptimeMillis());
1981                     }
1982                 }
1983                 mAm.mAppOpsService.finishOperation(
1984                         AppOpsManager.getToken(mAm.mAppOpsService),
1985                         AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
1986                 unregisterAppOpCallbackLocked(r);
1987                 logFGSStateChangeLocked(r,
1988                         FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT,
1989                         r.mFgsExitTime > r.mFgsEnterTime
1990                                 ? (int)(r.mFgsExitTime - r.mFgsEnterTime) : 0);
1991                 r.mFgsNotificationWasDeferred = false;
1992                 resetFgsRestrictionLocked(r);
1993                 mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
1994                 if (r.app != null) {
1995                     mAm.updateLruProcessLocked(r.app, false, null);
1996                     updateServiceForegroundLocked(r.app.mServices, true);
1997                 }
1998             }
1999         }
2000     }
2001 
withinFgsDeferRateLimit(ServiceRecord sr, final long now)2002     private boolean withinFgsDeferRateLimit(ServiceRecord sr, final long now) {
2003         // If we're still within the service's deferral period, then by definition
2004         // deferral is not rate limited.
2005         if (now < sr.fgDisplayTime) {
2006             if (DEBUG_FOREGROUND_SERVICE) {
2007                 Slog.d(TAG_SERVICE, "FGS transition for " + sr
2008                         + " within deferral period, no rate limit applied");
2009             }
2010             return false;
2011         }
2012 
2013         final int uid = sr.appInfo.uid;
2014         final long eligible = mFgsDeferralEligible.get(uid, 0L);
2015         if (DEBUG_FOREGROUND_SERVICE) {
2016             if (now < eligible) {
2017                 Slog.d(TAG_SERVICE, "FGS transition for uid " + uid
2018                         + " within rate limit, showing immediately");
2019             }
2020         }
2021         return now < eligible;
2022     }
2023 
applyForegroundServiceNotificationLocked(Notification notification, final String tag, final int id, final String pkg, final int userId)2024     ServiceNotificationPolicy applyForegroundServiceNotificationLocked(Notification notification,
2025             final String tag, final int id, final String pkg, final int userId) {
2026         // By nature of the FGS API, all FGS notifications have a null tag
2027         if (tag != null) {
2028             return ServiceNotificationPolicy.NOT_FOREGROUND_SERVICE;
2029         }
2030 
2031         if (DEBUG_FOREGROUND_SERVICE) {
2032             Slog.d(TAG_SERVICE, "Evaluating FGS policy for id=" + id
2033                     + " pkg=" + pkg + " not=" + notification);
2034         }
2035 
2036         // Is there an FGS using this notification?
2037         final ServiceMap smap = mServiceMap.get(userId);
2038         if (smap == null) {
2039             // No services in this user at all
2040             return ServiceNotificationPolicy.NOT_FOREGROUND_SERVICE;
2041         }
2042 
2043         for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
2044             final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
2045             if (!sr.isForeground
2046                     || id != sr.foregroundId
2047                     || !pkg.equals(sr.appInfo.packageName)) {
2048                 // Not this one; keep looking
2049                 continue;
2050             }
2051 
2052             // Found; it is associated with an FGS.  Make sure that it's flagged:
2053             // it may have entered the bookkeeping outside of Service-related
2054             // APIs.  We also make sure to take this latest Notification as
2055             // the content to be shown (immediately or eventually).
2056             if (DEBUG_FOREGROUND_SERVICE) {
2057                 Slog.d(TAG_SERVICE, "   FOUND: notification is for " + sr);
2058             }
2059             notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
2060             sr.foregroundNoti = notification;
2061 
2062             // ...and determine immediate vs deferred display policy for it
2063             final boolean showNow = shouldShowFgsNotificationLocked(sr);
2064             if (showNow) {
2065                 if (DEBUG_FOREGROUND_SERVICE) {
2066                     Slog.d(TAG_SERVICE, "   Showing immediately due to policy");
2067                 }
2068                 sr.mFgsNotificationDeferred = false;
2069                 return ServiceNotificationPolicy.SHOW_IMMEDIATELY;
2070             }
2071 
2072             // Deferring - kick off the timer if necessary, and tell the caller
2073             // that it's to be shown only if it's an update to already-
2074             // visible content (e.g. if it's an FGS adopting a
2075             // previously-posted Notification).
2076             if (DEBUG_FOREGROUND_SERVICE) {
2077                 Slog.d(TAG_SERVICE, "   Deferring / update-only");
2078             }
2079             startFgsDeferralTimerLocked(sr);
2080             return ServiceNotificationPolicy.UPDATE_ONLY;
2081         }
2082 
2083         // None of the services in this user are FGSs
2084         return ServiceNotificationPolicy.NOT_FOREGROUND_SERVICE;
2085     }
2086 
2087     // No legacy-app behavior skew intended but there's a runtime E-stop if a need
2088     // arises, so note that
2089     @SuppressWarnings("AndroidFrameworkCompatChange")
shouldShowFgsNotificationLocked(ServiceRecord r)2090     private boolean shouldShowFgsNotificationLocked(ServiceRecord r) {
2091         final long now = SystemClock.uptimeMillis();
2092 
2093         // Is the behavior enabled at all?
2094         if (!mAm.mConstants.mFlagFgsNotificationDeferralEnabled) {
2095             return true;
2096         }
2097 
2098         // Has this service's deferral timer expired?
2099         if (r.mFgsNotificationDeferred && now >= r.fgDisplayTime) {
2100             if (DEBUG_FOREGROUND_SERVICE) {
2101                 Slog.d(TAG, "FGS reached end of deferral period: " + r);
2102             }
2103             return true;
2104         }
2105 
2106         // Did the app have another FGS notification deferred recently?
2107         if (withinFgsDeferRateLimit(r, now)) {
2108             return true;
2109         }
2110 
2111         if (mAm.mConstants.mFlagFgsNotificationDeferralApiGated) {
2112             // Legacy apps' FGS notifications are also deferred unless the relevant
2113             // DeviceConfig element has been set
2114             final boolean isLegacyApp = (r.appInfo.targetSdkVersion < Build.VERSION_CODES.S);
2115             if (isLegacyApp) {
2116                 return true;
2117             }
2118         }
2119 
2120         // did we already show it?
2121         if (r.mFgsNotificationShown) {
2122             return true;
2123         }
2124 
2125         // has the app forced deferral?
2126         if (!r.foregroundNoti.isForegroundDisplayForceDeferred()) {
2127             // is the notification such that it should show right away?
2128             if (r.foregroundNoti.shouldShowForegroundImmediately()) {
2129                 if (DEBUG_FOREGROUND_SERVICE) {
2130                     Slog.d(TAG_SERVICE, "FGS " + r
2131                             + " notification policy says show immediately");
2132                 }
2133                 return true;
2134             }
2135 
2136             // or is this an type of FGS that always shows immediately?
2137             if ((r.foregroundServiceType & FGS_IMMEDIATE_DISPLAY_MASK) != 0) {
2138                 if (DEBUG_FOREGROUND_SERVICE) {
2139                     Slog.d(TAG_SERVICE, "FGS " + r
2140                             + " type gets immediate display");
2141                 }
2142                 return true;
2143             }
2144 
2145             // fall through to return false: no policy dictates immediate display
2146         } else {
2147             if (DEBUG_FOREGROUND_SERVICE) {
2148                 Slog.d(TAG_SERVICE, "FGS " + r + " notification is app deferred");
2149             }
2150             // fall through to return false
2151         }
2152 
2153         return false;
2154     }
2155 
2156     // Target SDK consultation here is strictly for logging purposes, not
2157     // behavioral variation.
2158     @SuppressWarnings("AndroidFrameworkCompatChange")
startFgsDeferralTimerLocked(ServiceRecord r)2159     private void startFgsDeferralTimerLocked(ServiceRecord r) {
2160         final long now = SystemClock.uptimeMillis();
2161         final int uid = r.appInfo.uid;
2162 
2163         // schedule the actual notification post
2164         long when = now + mAm.mConstants.mFgsNotificationDeferralInterval;
2165         // If there are already deferred FGS notifications for this app,
2166         // inherit that deferred-show timestamp
2167         for (int i = 0; i < mPendingFgsNotifications.size(); i++) {
2168             final ServiceRecord pending = mPendingFgsNotifications.get(i);
2169             if (pending == r) {
2170                 // Already pending; no need to reschedule
2171                 if (DEBUG_FOREGROUND_SERVICE) {
2172                     Slog.d(TAG_SERVICE, "FGS " + r
2173                             + " already pending notification display");
2174                 }
2175                 return;
2176             }
2177             if (uid == pending.appInfo.uid) {
2178                 when = Math.min(when, pending.fgDisplayTime);
2179             }
2180         }
2181 
2182         if (mFgsDeferralRateLimited) {
2183             final long nextEligible = when + mAm.mConstants.mFgsNotificationDeferralExclusionTime;
2184             mFgsDeferralEligible.put(uid, nextEligible);
2185         }
2186         r.fgDisplayTime = when;
2187         r.mFgsNotificationDeferred = true;
2188         r.mFgsNotificationWasDeferred = true;
2189         r.mFgsNotificationShown = false;
2190         mPendingFgsNotifications.add(r);
2191         if (DEBUG_FOREGROUND_SERVICE) {
2192             Slog.d(TAG_SERVICE, "FGS " + r
2193                     + " notification in " + (when - now) + " ms");
2194         }
2195         final boolean isLegacyApp = (r.appInfo.targetSdkVersion < Build.VERSION_CODES.S);
2196         if (isLegacyApp) {
2197             Slog.i(TAG_SERVICE, "Deferring FGS notification in legacy app "
2198                     + r.appInfo.packageName + "/" + UserHandle.formatUid(r.appInfo.uid)
2199                     + " : " + r.foregroundNoti);
2200         }
2201         mAm.mHandler.postAtTime(mPostDeferredFGSNotifications, when);
2202     }
2203 
2204     private final Runnable mPostDeferredFGSNotifications = new Runnable() {
2205         @Override
2206         public void run() {
2207             if (DEBUG_FOREGROUND_SERVICE) {
2208                 Slog.d(TAG_SERVICE, "+++ evaluating deferred FGS notifications +++");
2209             }
2210             final long now = SystemClock.uptimeMillis();
2211             synchronized (mAm) {
2212                 // post all notifications whose time has come
2213                 for (int i = mPendingFgsNotifications.size() - 1; i >= 0; i--) {
2214                     final ServiceRecord r = mPendingFgsNotifications.get(i);
2215                     if (r.fgDisplayTime <= now) {
2216                         if (DEBUG_FOREGROUND_SERVICE) {
2217                             Slog.d(TAG_SERVICE, "FGS " + r
2218                                     + " handling deferred notification now");
2219                         }
2220                         mPendingFgsNotifications.remove(i);
2221                         // The service might have been stopped or exited foreground state
2222                         // in the interval, so we lazy check whether we still need to show
2223                         // the notification.
2224                         if (r.isForeground && r.app != null) {
2225                             r.postNotification();
2226                             r.mFgsNotificationShown = true;
2227                         } else {
2228                             if (DEBUG_FOREGROUND_SERVICE) {
2229                                 Slog.d(TAG_SERVICE, "  - service no longer running/fg, ignoring");
2230                             }
2231                         }
2232                     }
2233                 }
2234                 if (DEBUG_FOREGROUND_SERVICE) {
2235                     Slog.d(TAG_SERVICE, "Done evaluating deferred FGS notifications; "
2236                             + mPendingFgsNotifications.size() + " remaining");
2237                 }
2238             }
2239         }
2240     };
2241 
2242     /**
2243      * Suppress or reenable the rate limit on foreground service notification deferral.
2244      * Invoked from the activity manager shell command.
2245      *
2246      * @param enable false to suppress rate-limit policy; true to reenable it.
2247      */
enableFgsNotificationRateLimitLocked(final boolean enable)2248     boolean enableFgsNotificationRateLimitLocked(final boolean enable) {
2249         if (enable != mFgsDeferralRateLimited) {
2250             mFgsDeferralRateLimited = enable;
2251             if (!enable) {
2252                 // make sure to reset any active rate limiting
2253                 mFgsDeferralEligible.clear();
2254             }
2255         }
2256         return enable;
2257     }
2258 
removeServiceNotificationDeferralsLocked(String packageName, final @UserIdInt int userId)2259     private void removeServiceNotificationDeferralsLocked(String packageName,
2260             final @UserIdInt int userId) {
2261         for (int i = mPendingFgsNotifications.size() - 1; i >= 0; i--) {
2262             final ServiceRecord r = mPendingFgsNotifications.get(i);
2263             if (userId == r.userId
2264                     && r.appInfo.packageName.equals(packageName)) {
2265                 mPendingFgsNotifications.remove(i);
2266                 if (DEBUG_FOREGROUND_SERVICE) {
2267                     Slog.d(TAG_SERVICE, "Removing notification deferral for "
2268                             + r);
2269                 }
2270             }
2271         }
2272     }
2273 
2274     /**
2275      * Callback from NotificationManagerService whenever it posts a notification
2276      * associated with a foreground service.  This is the unified handling point
2277      * for the disjoint code flows that affect an FGS's notifiation content and
2278      * visibility, starting with both Service.startForeground() and
2279      * NotificationManager.notify().
2280      */
onForegroundServiceNotificationUpdateLocked(boolean shown, Notification notification, final int id, final String pkg, @UserIdInt final int userId)2281     public void onForegroundServiceNotificationUpdateLocked(boolean shown,
2282             Notification notification, final int id, final String pkg,
2283             @UserIdInt final int userId) {
2284         // If this happens to be a Notification for an FGS still in its deferral period,
2285         // drop the deferral and make sure our content bookkeeping is up to date.
2286         for (int i = mPendingFgsNotifications.size() - 1; i >= 0; i--) {
2287             final ServiceRecord sr = mPendingFgsNotifications.get(i);
2288             if (userId == sr.userId
2289                     && id == sr.foregroundId
2290                     && sr.appInfo.packageName.equals(pkg)) {
2291                 // Found it.  If 'shown' is false, it means that the notification
2292                 // subsystem will not be displaying it yet.
2293                 if (shown) {
2294                     if (DEBUG_FOREGROUND_SERVICE) {
2295                         Slog.d(TAG_SERVICE, "Notification shown; canceling deferral of "
2296                                 + sr);
2297                     }
2298                     sr.mFgsNotificationShown = true;
2299                     sr.mFgsNotificationDeferred = false;
2300                     mPendingFgsNotifications.remove(i);
2301                 } else {
2302                     if (DEBUG_FOREGROUND_SERVICE) {
2303                         Slog.d(TAG_SERVICE, "FGS notification deferred for " + sr);
2304                     }
2305                 }
2306             }
2307         }
2308         // In all cases, make sure to retain the latest notification content for the FGS
2309         ServiceMap smap = mServiceMap.get(userId);
2310         if (smap != null) {
2311             for (int i = 0; i < smap.mServicesByInstanceName.size(); i++) {
2312                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
2313                 if (sr.isForeground
2314                         && id == sr.foregroundId
2315                         && sr.appInfo.packageName.equals(pkg)) {
2316                     if (DEBUG_FOREGROUND_SERVICE) {
2317                         Slog.d(TAG_SERVICE, "Recording shown notification for "
2318                                 + sr);
2319                     }
2320                     sr.foregroundNoti = notification;
2321                 }
2322             }
2323         }
2324     }
2325 
2326     /** Registers an AppOpCallback for monitoring special AppOps for this foreground service. */
registerAppOpCallbackLocked(@onNull ServiceRecord r)2327     private void registerAppOpCallbackLocked(@NonNull ServiceRecord r) {
2328         if (r.app == null) {
2329             return;
2330         }
2331         final int uid = r.appInfo.uid;
2332         AppOpCallback callback = mFgsAppOpCallbacks.get(uid);
2333         if (callback == null) {
2334             callback = new AppOpCallback(r.app, mAm.getAppOpsManager());
2335             mFgsAppOpCallbacks.put(uid, callback);
2336         }
2337         callback.registerLocked();
2338     }
2339 
2340     /** Unregisters a foreground service's AppOpCallback. */
unregisterAppOpCallbackLocked(@onNull ServiceRecord r)2341     private void unregisterAppOpCallbackLocked(@NonNull ServiceRecord r) {
2342         final int uid = r.appInfo.uid;
2343         final AppOpCallback callback = mFgsAppOpCallbacks.get(uid);
2344         if (callback != null) {
2345             callback.unregisterLocked();
2346             if (callback.isObsoleteLocked()) {
2347                 mFgsAppOpCallbacks.remove(uid);
2348             }
2349         }
2350     }
2351 
2352     /**
2353      * For monitoring when {@link #LOGGED_AP_OPS} AppOps occur by an app while it is holding
2354      * at least one foreground service and is not also in the TOP state.
2355      * Once the uid no longer holds any foreground services, this callback becomes stale
2356      * (marked by {@link #isObsoleteLocked()}) and must no longer be used.
2357      *
2358      * Methods that end in Locked should only be called while the mAm lock is held.
2359      */
2360     private static final class AppOpCallback {
2361         /** AppOps that should be logged if they occur during a foreground service. */
2362         private static final int[] LOGGED_AP_OPS = new int[] {
2363                 AppOpsManager.OP_COARSE_LOCATION,
2364                 AppOpsManager.OP_FINE_LOCATION,
2365                 AppOpsManager.OP_RECORD_AUDIO,
2366                 AppOpsManager.OP_CAMERA
2367         };
2368 
2369         private final ProcessRecord mProcessRecord;
2370 
2371         /** Count of acceptances per appop (for LOGGED_AP_OPS) during this fgs session. */
2372         @GuardedBy("mCounterLock")
2373         private final SparseIntArray mAcceptedOps = new SparseIntArray();
2374         /** Count of rejections per appop (for LOGGED_AP_OPS) during this fgs session. */
2375         @GuardedBy("mCounterLock")
2376         private final SparseIntArray mRejectedOps = new SparseIntArray();
2377 
2378         /** Lock for the purposes of mAcceptedOps and mRejectedOps. */
2379         private final Object mCounterLock = new Object();
2380 
2381         /**
2382          * AppOp Mode (e.g. {@link AppOpsManager#MODE_ALLOWED} per op.
2383          * This currently cannot change without the process being killed, so they are constants.
2384          */
2385         private final SparseIntArray mAppOpModes = new SparseIntArray();
2386 
2387         /**
2388          * Number of foreground services currently associated with this AppOpCallback (i.e.
2389          * currently held for this uid).
2390          */
2391         @GuardedBy("mAm")
2392         private int mNumFgs = 0;
2393 
2394         /**
2395          * Indicates that this Object is stale and must not be used.
2396          * Specifically, when mNumFgs decreases down to 0, the callbacks will be unregistered and
2397          * this AppOpCallback is unusable.
2398          */
2399         @GuardedBy("mAm")
2400         private boolean mDestroyed = false;
2401 
2402         private final AppOpsManager mAppOpsManager;
2403 
AppOpCallback(@onNull ProcessRecord r, @NonNull AppOpsManager appOpsManager)2404         AppOpCallback(@NonNull ProcessRecord r, @NonNull AppOpsManager appOpsManager) {
2405             mProcessRecord = r;
2406             mAppOpsManager = appOpsManager;
2407             for (int op : LOGGED_AP_OPS) {
2408                 int mode = appOpsManager.unsafeCheckOpRawNoThrow(op, r.uid, r.info.packageName);
2409                 mAppOpModes.put(op, mode);
2410             }
2411         }
2412 
2413         private final AppOpsManager.OnOpNotedListener mOpNotedCallback =
2414                 new AppOpsManager.OnOpNotedListener() {
2415                     @Override
2416                     public void onOpNoted(int op, int uid, String pkgName,
2417                             String attributionTag, int flags, int result) {
2418                         incrementOpCountIfNeeded(op, uid, result);
2419                     }
2420         };
2421 
2422         private final AppOpsManager.OnOpStartedListener mOpStartedCallback =
2423                 new AppOpsManager.OnOpStartedListener() {
2424                     @Override
2425                     public void onOpStarted(int op, int uid, String pkgName,
2426                             String attributionTag, int flags,
2427                             int result) {
2428                         incrementOpCountIfNeeded(op, uid, result);
2429                     }
2430         };
2431 
incrementOpCountIfNeeded(int op, int uid, @AppOpsManager.Mode int result)2432         private void incrementOpCountIfNeeded(int op, int uid, @AppOpsManager.Mode int result) {
2433             if (uid == mProcessRecord.uid && isNotTop()) {
2434                 incrementOpCount(op, result == AppOpsManager.MODE_ALLOWED);
2435             }
2436         }
2437 
isNotTop()2438         private boolean isNotTop() {
2439             return mProcessRecord.mState.getCurProcState() != PROCESS_STATE_TOP;
2440         }
2441 
incrementOpCount(int op, boolean allowed)2442         private void incrementOpCount(int op, boolean allowed) {
2443             synchronized (mCounterLock) {
2444                 final SparseIntArray counter = allowed ? mAcceptedOps : mRejectedOps;
2445                 final int index = counter.indexOfKey(op);
2446                 if (index < 0) {
2447                     counter.put(op, 1);
2448                 } else {
2449                     counter.setValueAt(index, counter.valueAt(index) + 1);
2450                 }
2451             }
2452         }
2453 
registerLocked()2454         void registerLocked() {
2455             if (isObsoleteLocked()) {
2456                 Slog.wtf(TAG, "Trying to register on a stale AppOpCallback.");
2457                 return;
2458             }
2459             mNumFgs++;
2460             if (mNumFgs == 1) {
2461                 mAppOpsManager.startWatchingNoted(LOGGED_AP_OPS, mOpNotedCallback);
2462                 mAppOpsManager.startWatchingStarted(LOGGED_AP_OPS, mOpStartedCallback);
2463             }
2464         }
2465 
unregisterLocked()2466         void unregisterLocked() {
2467             mNumFgs--;
2468             if (mNumFgs <= 0) {
2469                 mDestroyed = true;
2470                 logFinalValues();
2471                 mAppOpsManager.stopWatchingNoted(mOpNotedCallback);
2472                 mAppOpsManager.stopWatchingStarted(mOpStartedCallback);
2473             }
2474         }
2475 
2476         /**
2477          * Indicates that all foreground services for this uid are now over and the callback is
2478          * stale and must never be used again.
2479          */
isObsoleteLocked()2480         boolean isObsoleteLocked() {
2481             return mDestroyed;
2482         }
2483 
logFinalValues()2484         private void logFinalValues() {
2485             synchronized (mCounterLock) {
2486                 for (int op : LOGGED_AP_OPS) {
2487                     final int acceptances = mAcceptedOps.get(op);
2488                     final int rejections = mRejectedOps.get(op);
2489                     if (acceptances > 0 ||  rejections > 0) {
2490                         FrameworkStatsLog.write(
2491                                 FrameworkStatsLog.FOREGROUND_SERVICE_APP_OP_SESSION_ENDED,
2492                                 mProcessRecord.uid, op,
2493                                 modeToEnum(mAppOpModes.get(op)),
2494                                 acceptances, rejections
2495                         );
2496                     }
2497                 }
2498             }
2499         }
2500 
2501         /** Maps AppOp mode to atoms.proto enum. */
modeToEnum(int mode)2502         private static int modeToEnum(int mode) {
2503             switch (mode) {
2504                 case AppOpsManager.MODE_ALLOWED: return FrameworkStatsLog
2505                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_ALLOWED;
2506                 case AppOpsManager.MODE_IGNORED: return FrameworkStatsLog
2507                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_IGNORED;
2508                 case AppOpsManager.MODE_FOREGROUND: return FrameworkStatsLog
2509                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_FOREGROUND;
2510                 default: return FrameworkStatsLog
2511                         .FOREGROUND_SERVICE_APP_OP_SESSION_ENDED__APP_OP_MODE__MODE_UNKNOWN;
2512             }
2513         }
2514     }
2515 
cancelForegroundNotificationLocked(ServiceRecord r)2516     private void cancelForegroundNotificationLocked(ServiceRecord r) {
2517         if (r.foregroundNoti != null) {
2518             // First check to see if this app has any other active foreground services
2519             // with the same notification ID.  If so, we shouldn't actually cancel it,
2520             // because that would wipe away the notification that still needs to be shown
2521             // due the other service.
2522             ServiceMap sm = getServiceMapLocked(r.userId);
2523             if (sm != null) {
2524                 for (int i = sm.mServicesByInstanceName.size() - 1; i >= 0; i--) {
2525                     ServiceRecord other = sm.mServicesByInstanceName.valueAt(i);
2526                     if (other != r
2527                             && other.isForeground
2528                             && other.foregroundId == r.foregroundId
2529                             && other.packageName.equals(r.packageName)) {
2530                         if (DEBUG_FOREGROUND_SERVICE) {
2531                             Slog.i(TAG_SERVICE, "FGS notification for " + r
2532                                     + " shared by " + other
2533                                     + " (isForeground=" + other.isForeground + ")"
2534                                     + " - NOT cancelling");
2535                         }
2536                         return;
2537                     }
2538                 }
2539             }
2540             r.cancelNotification();
2541         }
2542     }
2543 
updateServiceForegroundLocked(ProcessServiceRecord psr, boolean oomAdj)2544     private void updateServiceForegroundLocked(ProcessServiceRecord psr, boolean oomAdj) {
2545         boolean anyForeground = false;
2546         int fgServiceTypes = 0;
2547         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
2548             ServiceRecord sr = psr.getRunningServiceAt(i);
2549             if (sr.isForeground || sr.fgRequired) {
2550                 anyForeground = true;
2551                 fgServiceTypes |= sr.foregroundServiceType;
2552             }
2553         }
2554         mAm.updateProcessForegroundLocked(psr.mApp, anyForeground, fgServiceTypes, oomAdj);
2555     }
2556 
updateAllowlistManagerLocked(ProcessServiceRecord psr)2557     private void updateAllowlistManagerLocked(ProcessServiceRecord psr) {
2558         psr.mAllowlistManager = false;
2559         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
2560             ServiceRecord sr = psr.getRunningServiceAt(i);
2561             if (sr.allowlistManager) {
2562                 psr.mAllowlistManager = true;
2563                 break;
2564             }
2565         }
2566     }
2567 
stopServiceAndUpdateAllowlistManagerLocked(ServiceRecord service)2568     private void stopServiceAndUpdateAllowlistManagerLocked(ServiceRecord service) {
2569         final ProcessServiceRecord psr = service.app.mServices;
2570         psr.stopService(service);
2571         psr.updateBoundClientUids();
2572         if (service.allowlistManager) {
2573             updateAllowlistManagerLocked(psr);
2574         }
2575     }
2576 
updateServiceConnectionActivitiesLocked(ProcessServiceRecord clientPsr)2577     void updateServiceConnectionActivitiesLocked(ProcessServiceRecord clientPsr) {
2578         ArraySet<ProcessRecord> updatedProcesses = null;
2579         for (int i = 0; i < clientPsr.numberOfConnections(); i++) {
2580             final ConnectionRecord conn = clientPsr.getConnectionAt(i);
2581             final ProcessRecord proc = conn.binding.service.app;
2582             if (proc == null || proc == clientPsr.mApp) {
2583                 continue;
2584             } else if (updatedProcesses == null) {
2585                 updatedProcesses = new ArraySet<>();
2586             } else if (updatedProcesses.contains(proc)) {
2587                 continue;
2588             }
2589             updatedProcesses.add(proc);
2590             updateServiceClientActivitiesLocked(proc.mServices, null, false);
2591         }
2592     }
2593 
updateServiceClientActivitiesLocked(ProcessServiceRecord psr, ConnectionRecord modCr, boolean updateLru)2594     private boolean updateServiceClientActivitiesLocked(ProcessServiceRecord psr,
2595             ConnectionRecord modCr, boolean updateLru) {
2596         if (modCr != null && modCr.binding.client != null) {
2597             if (!modCr.binding.client.hasActivities()) {
2598                 // This connection is from a client without activities, so adding
2599                 // and removing is not interesting.
2600                 return false;
2601             }
2602         }
2603 
2604         boolean anyClientActivities = false;
2605         for (int i = psr.numberOfRunningServices() - 1; i >= 0 && !anyClientActivities; i--) {
2606             ServiceRecord sr = psr.getRunningServiceAt(i);
2607             ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = sr.getConnections();
2608             for (int conni = connections.size() - 1; conni >= 0 && !anyClientActivities; conni--) {
2609                 ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
2610                 for (int cri=clist.size()-1; cri>=0; cri--) {
2611                     ConnectionRecord cr = clist.get(cri);
2612                     if (cr.binding.client == null || cr.binding.client == psr.mApp) {
2613                         // Binding to ourself is not interesting.
2614                         continue;
2615                     }
2616                     if (cr.binding.client.hasActivities()) {
2617                         anyClientActivities = true;
2618                         break;
2619                     }
2620                 }
2621             }
2622         }
2623         if (anyClientActivities != psr.hasClientActivities()) {
2624             psr.setHasClientActivities(anyClientActivities);
2625             if (updateLru) {
2626                 mAm.updateLruProcessLocked(psr.mApp, anyClientActivities, null);
2627             }
2628             return true;
2629         }
2630         return false;
2631     }
2632 
bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType, final IServiceConnection connection, int flags, String instanceName, String callingPackage, final int userId)2633     int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
2634             String resolvedType, final IServiceConnection connection, int flags,
2635             String instanceName, String callingPackage, final int userId)
2636             throws TransactionTooLargeException {
2637         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
2638                 + " type=" + resolvedType + " conn=" + connection.asBinder()
2639                 + " flags=0x" + Integer.toHexString(flags));
2640         final int callingPid = Binder.getCallingPid();
2641         final int callingUid = Binder.getCallingUid();
2642         final ProcessRecord callerApp = mAm.getRecordForAppLOSP(caller);
2643         if (callerApp == null) {
2644             throw new SecurityException(
2645                     "Unable to find app for caller " + caller
2646                     + " (pid=" + callingPid
2647                     + ") when binding service " + service);
2648         }
2649 
2650         ActivityServiceConnectionsHolder<ConnectionRecord> activity = null;
2651         if (token != null) {
2652             activity = mAm.mAtmInternal.getServiceConnectionsHolder(token);
2653             if (activity == null) {
2654                 Slog.w(TAG, "Binding with unknown activity: " + token);
2655                 return 0;
2656             }
2657         }
2658 
2659         int clientLabel = 0;
2660         PendingIntent clientIntent = null;
2661         final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
2662 
2663         if (isCallerSystem) {
2664             // Hacky kind of thing -- allow system stuff to tell us
2665             // what they are, so we can report this elsewhere for
2666             // others to know why certain services are running.
2667             service.setDefusable(true);
2668             clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
2669             if (clientIntent != null) {
2670                 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
2671                 if (clientLabel != 0) {
2672                     // There are no useful extras in the intent, trash them.
2673                     // System code calling with this stuff just needs to know
2674                     // this will happen.
2675                     service = service.cloneFilter();
2676                 }
2677             }
2678         }
2679 
2680         if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
2681             mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_TASKS,
2682                     "BIND_TREAT_LIKE_ACTIVITY");
2683         }
2684 
2685         if ((flags & Context.BIND_SCHEDULE_LIKE_TOP_APP) != 0 && !isCallerSystem) {
2686             throw new SecurityException("Non-system caller (pid=" + callingPid
2687                     + ") set BIND_SCHEDULE_LIKE_TOP_APP when binding service " + service);
2688         }
2689 
2690         if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
2691             throw new SecurityException(
2692                     "Non-system caller " + caller + " (pid=" + callingPid
2693                     + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
2694         }
2695 
2696         if ((flags & Context.BIND_ALLOW_INSTANT) != 0 && !isCallerSystem) {
2697             throw new SecurityException(
2698                     "Non-system caller " + caller + " (pid=" + callingPid
2699                             + ") set BIND_ALLOW_INSTANT when binding service " + service);
2700         }
2701 
2702         if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
2703             mAm.enforceCallingPermission(
2704                     android.Manifest.permission.START_ACTIVITIES_FROM_BACKGROUND,
2705                     "BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS");
2706         }
2707 
2708         if ((flags & Context.BIND_ALLOW_FOREGROUND_SERVICE_STARTS_FROM_BACKGROUND) != 0) {
2709             mAm.enforceCallingPermission(
2710                     android.Manifest.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND,
2711                     "BIND_ALLOW_FOREGROUND_SERVICE_STARTS_FROM_BACKGROUND");
2712         }
2713 
2714         final boolean callerFg = callerApp.mState.getSetSchedGroup()
2715                 != ProcessList.SCHED_GROUP_BACKGROUND;
2716         final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
2717         final boolean allowInstant = (flags & Context.BIND_ALLOW_INSTANT) != 0;
2718 
2719         ServiceLookupResult res =
2720             retrieveServiceLocked(service, instanceName, resolvedType, callingPackage,
2721                     callingPid, callingUid, userId, true,
2722                     callerFg, isBindExternal, allowInstant);
2723         if (res == null) {
2724             return 0;
2725         }
2726         if (res.record == null) {
2727             return -1;
2728         }
2729         ServiceRecord s = res.record;
2730 
2731         // The package could be frozen (meaning it's doing surgery), defer the actual
2732         // binding until the package is unfrozen.
2733         boolean packageFrozen = deferServiceBringupIfFrozenLocked(s, service, callingPackage, null,
2734                 callingUid, callingPid, false, callerFg, userId, false, null, true, connection);
2735 
2736         // If permissions need a review before any of the app components can run,
2737         // we schedule binding to the service but do not start its process, then
2738         // we launch a review activity to which is passed a callback to invoke
2739         // when done to start the bound service's process to completing the binding.
2740         boolean permissionsReviewRequired = !packageFrozen
2741                 && !requestStartTargetPermissionsReviewIfNeededLocked(s, callingPackage, null,
2742                         callingUid, service, callerFg, userId, true, connection);
2743 
2744         final long origId = Binder.clearCallingIdentity();
2745 
2746         try {
2747             if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
2748                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
2749                         + s);
2750             }
2751 
2752             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
2753                 s.lastActivity = SystemClock.uptimeMillis();
2754                 if (!s.hasAutoCreateConnections()) {
2755                     // This is the first binding, let the tracker know.
2756                     synchronized (mAm.mProcessStats.mLock) {
2757                         final ServiceState stracker = s.getTracker();
2758                         if (stracker != null) {
2759                             stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
2760                                     s.lastActivity);
2761                         }
2762                     }
2763                 }
2764             }
2765 
2766             if ((flags & Context.BIND_RESTRICT_ASSOCIATIONS) != 0) {
2767                 mAm.requireAllowedAssociationsLocked(s.appInfo.packageName);
2768             }
2769 
2770             mAm.startAssociationLocked(callerApp.uid, callerApp.processName,
2771                     callerApp.mState.getCurProcState(), s.appInfo.uid, s.appInfo.longVersionCode,
2772                     s.instanceName, s.processName);
2773             // Once the apps have become associated, if one of them is caller is ephemeral
2774             // the target app should now be able to see the calling app
2775             mAm.grantImplicitAccess(callerApp.userId, service,
2776                     callerApp.uid, UserHandle.getAppId(s.appInfo.uid));
2777 
2778             AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
2779             ConnectionRecord c = new ConnectionRecord(b, activity,
2780                     connection, flags, clientLabel, clientIntent,
2781                     callerApp.uid, callerApp.processName, callingPackage);
2782 
2783             IBinder binder = connection.asBinder();
2784             s.addConnection(binder, c);
2785             b.connections.add(c);
2786             if (activity != null) {
2787                 activity.addConnection(c);
2788             }
2789             final ProcessServiceRecord clientPsr = b.client.mServices;
2790             clientPsr.addConnection(c);
2791             c.startAssociationIfNeeded();
2792             if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2793                 clientPsr.setHasAboveClient(true);
2794             }
2795             if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2796                 s.allowlistManager = true;
2797             }
2798             if ((flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
2799                 s.setAllowedBgActivityStartsByBinding(true);
2800             }
2801 
2802             if ((flags & Context.BIND_NOT_APP_COMPONENT_USAGE) != 0) {
2803                 s.isNotAppComponentUsage = true;
2804             }
2805 
2806             if (s.app != null) {
2807                 updateServiceClientActivitiesLocked(s.app.mServices, c, true);
2808             }
2809             ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
2810             if (clist == null) {
2811                 clist = new ArrayList<>();
2812                 mServiceConnections.put(binder, clist);
2813             }
2814             clist.add(c);
2815 
2816             boolean needOomAdj = false;
2817             if ((flags&Context.BIND_AUTO_CREATE) != 0) {
2818                 s.lastActivity = SystemClock.uptimeMillis();
2819                 needOomAdj = true;
2820                 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
2821                         permissionsReviewRequired, packageFrozen, true) != null) {
2822                     mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_BIND_SERVICE);
2823                     return 0;
2824                 }
2825             }
2826             setFgsRestrictionLocked(callingPackage, callingPid, callingUid, service, s, userId,
2827                     false);
2828 
2829             if (s.app != null) {
2830                 ProcessServiceRecord servicePsr = s.app.mServices;
2831                 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
2832                     servicePsr.setTreatLikeActivity(true);
2833                 }
2834                 if (s.allowlistManager) {
2835                     servicePsr.mAllowlistManager = true;
2836                 }
2837                 // This could have made the service more important.
2838                 mAm.updateLruProcessLocked(s.app, (callerApp.hasActivitiesOrRecentTasks()
2839                             && servicePsr.hasClientActivities())
2840                         || (callerApp.mState.getCurProcState() <= PROCESS_STATE_TOP
2841                             && (flags & Context.BIND_TREAT_LIKE_ACTIVITY) != 0),
2842                         b.client);
2843                 needOomAdj = true;
2844                 mAm.enqueueOomAdjTargetLocked(s.app);
2845             }
2846             if (needOomAdj) {
2847                 mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_BIND_SERVICE);
2848             }
2849 
2850             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
2851                     + ": received=" + b.intent.received
2852                     + " apps=" + b.intent.apps.size()
2853                     + " doRebind=" + b.intent.doRebind);
2854 
2855             if (s.app != null && b.intent.received) {
2856                 // Service is already running, so we can immediately
2857                 // publish the connection.
2858                 try {
2859                     c.conn.connected(s.name, b.intent.binder, false);
2860                 } catch (Exception e) {
2861                     Slog.w(TAG, "Failure sending service " + s.shortInstanceName
2862                             + " to connection " + c.conn.asBinder()
2863                             + " (in " + c.binding.client.processName + ")", e);
2864                 }
2865 
2866                 // If this is the first app connected back to this binding,
2867                 // and the service had previously asked to be told when
2868                 // rebound, then do so.
2869                 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
2870                     requestServiceBindingLocked(s, b.intent, callerFg, true);
2871                 }
2872             } else if (!b.intent.requested) {
2873                 requestServiceBindingLocked(s, b.intent, callerFg, false);
2874             }
2875 
2876             maybeLogBindCrossProfileService(userId, callingPackage, callerApp.info.uid);
2877 
2878             getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
2879 
2880         } finally {
2881             Binder.restoreCallingIdentity(origId);
2882         }
2883 
2884         return 1;
2885     }
2886 
maybeLogBindCrossProfileService( int userId, String callingPackage, int callingUid)2887     private void maybeLogBindCrossProfileService(
2888             int userId, String callingPackage, int callingUid) {
2889         if (UserHandle.isCore(callingUid)) {
2890             return;
2891         }
2892         final int callingUserId = UserHandle.getCallingUserId();
2893         if (callingUserId == userId
2894                 || !mAm.mUserController.isSameProfileGroup(callingUserId, userId)) {
2895             return;
2896         }
2897         DevicePolicyEventLogger.createEvent(DevicePolicyEnums.BIND_CROSS_PROFILE_SERVICE)
2898                 .setStrings(callingPackage)
2899                 .write();
2900     }
2901 
publishServiceLocked(ServiceRecord r, Intent intent, IBinder service)2902     void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
2903         final long origId = Binder.clearCallingIdentity();
2904         try {
2905             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
2906                     + " " + intent + ": " + service);
2907             if (r != null) {
2908                 Intent.FilterComparison filter
2909                         = new Intent.FilterComparison(intent);
2910                 IntentBindRecord b = r.bindings.get(filter);
2911                 if (b != null && !b.received) {
2912                     b.binder = service;
2913                     b.requested = true;
2914                     b.received = true;
2915                     ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
2916                     for (int conni = connections.size() - 1; conni >= 0; conni--) {
2917                         ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
2918                         for (int i=0; i<clist.size(); i++) {
2919                             ConnectionRecord c = clist.get(i);
2920                             if (!filter.equals(c.binding.intent.intent)) {
2921                                 if (DEBUG_SERVICE) Slog.v(
2922                                         TAG_SERVICE, "Not publishing to: " + c);
2923                                 if (DEBUG_SERVICE) Slog.v(
2924                                         TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
2925                                 if (DEBUG_SERVICE) Slog.v(
2926                                         TAG_SERVICE, "Published intent: " + intent);
2927                                 continue;
2928                             }
2929                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
2930                             try {
2931                                 c.conn.connected(r.name, service, false);
2932                             } catch (Exception e) {
2933                                 Slog.w(TAG, "Failure sending service " + r.shortInstanceName
2934                                       + " to connection " + c.conn.asBinder()
2935                                       + " (in " + c.binding.client.processName + ")", e);
2936                             }
2937                         }
2938                     }
2939                 }
2940 
2941                 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false, false);
2942             }
2943         } finally {
2944             Binder.restoreCallingIdentity(origId);
2945         }
2946     }
2947 
updateServiceGroupLocked(IServiceConnection connection, int group, int importance)2948     void updateServiceGroupLocked(IServiceConnection connection, int group, int importance) {
2949         final IBinder binder = connection.asBinder();
2950         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "updateServiceGroup: conn=" + binder);
2951         final ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
2952         if (clist == null) {
2953             throw new IllegalArgumentException("Could not find connection for "
2954                     + connection.asBinder());
2955         }
2956         for (int i = clist.size() - 1; i >= 0; i--) {
2957             final ConnectionRecord crec = clist.get(i);
2958             final ServiceRecord srec = crec.binding.service;
2959             if (srec != null && (srec.serviceInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
2960                 if (srec.app != null) {
2961                     final ProcessServiceRecord psr = srec.app.mServices;
2962                     if (group > 0) {
2963                         psr.setConnectionService(srec);
2964                         psr.setConnectionGroup(group);
2965                         psr.setConnectionImportance(importance);
2966                     } else {
2967                         psr.setConnectionService(null);
2968                         psr.setConnectionGroup(0);
2969                         psr.setConnectionImportance(0);
2970                     }
2971                 } else {
2972                     if (group > 0) {
2973                         srec.pendingConnectionGroup = group;
2974                         srec.pendingConnectionImportance = importance;
2975                     } else {
2976                         srec.pendingConnectionGroup = 0;
2977                         srec.pendingConnectionImportance = 0;
2978                     }
2979                 }
2980             }
2981         }
2982     }
2983 
unbindServiceLocked(IServiceConnection connection)2984     boolean unbindServiceLocked(IServiceConnection connection) {
2985         IBinder binder = connection.asBinder();
2986         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
2987         ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
2988         if (clist == null) {
2989             Slog.w(TAG, "Unbind failed: could not find connection for "
2990                   + connection.asBinder());
2991             return false;
2992         }
2993 
2994         final long origId = Binder.clearCallingIdentity();
2995         try {
2996             while (clist.size() > 0) {
2997                 ConnectionRecord r = clist.get(0);
2998                 removeConnectionLocked(r, null, null, true);
2999                 if (clist.size() > 0 && clist.get(0) == r) {
3000                     // In case it didn't get removed above, do it now.
3001                     Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
3002                     clist.remove(0);
3003                 }
3004 
3005                 final ProcessRecord app = r.binding.service.app;
3006                 if (app != null) {
3007                     final ProcessServiceRecord psr = app.mServices;
3008                     if (psr.mAllowlistManager) {
3009                         updateAllowlistManagerLocked(psr);
3010                     }
3011                     // This could have made the service less important.
3012                     if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
3013                         psr.setTreatLikeActivity(true);
3014                         mAm.updateLruProcessLocked(app, true, null);
3015                     }
3016                     mAm.enqueueOomAdjTargetLocked(app);
3017                 }
3018             }
3019 
3020             mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
3021 
3022         } finally {
3023             Binder.restoreCallingIdentity(origId);
3024         }
3025 
3026         return true;
3027     }
3028 
unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind)3029     void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
3030         final long origId = Binder.clearCallingIdentity();
3031         try {
3032             if (r != null) {
3033                 Intent.FilterComparison filter
3034                         = new Intent.FilterComparison(intent);
3035                 IntentBindRecord b = r.bindings.get(filter);
3036                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
3037                         + " at " + b + ": apps="
3038                         + (b != null ? b.apps.size() : 0));
3039 
3040                 boolean inDestroying = mDestroyingServices.contains(r);
3041                 if (b != null) {
3042                     if (b.apps.size() > 0 && !inDestroying) {
3043                         // Applications have already bound since the last
3044                         // unbind, so just rebind right here.
3045                         boolean inFg = false;
3046                         for (int i=b.apps.size()-1; i>=0; i--) {
3047                             ProcessRecord client = b.apps.valueAt(i).client;
3048                             if (client != null && client.mState.getSetSchedGroup()
3049                                     != ProcessList.SCHED_GROUP_BACKGROUND) {
3050                                 inFg = true;
3051                                 break;
3052                             }
3053                         }
3054                         try {
3055                             requestServiceBindingLocked(r, b, inFg, true);
3056                         } catch (TransactionTooLargeException e) {
3057                             // Don't pass this back to ActivityThread, it's unrelated.
3058                         }
3059                     } else {
3060                         // Note to tell the service the next time there is
3061                         // a new client.
3062                         b.doRebind = true;
3063                     }
3064                 }
3065 
3066                 serviceDoneExecutingLocked(r, inDestroying, false, false);
3067             }
3068         } finally {
3069             Binder.restoreCallingIdentity(origId);
3070         }
3071     }
3072 
findServiceLocked(ComponentName name, IBinder token, int userId)3073     private final ServiceRecord findServiceLocked(ComponentName name,
3074             IBinder token, int userId) {
3075         ServiceRecord r = getServiceByNameLocked(name, userId);
3076         return r == token ? r : null;
3077     }
3078 
3079     private final class ServiceLookupResult {
3080         final ServiceRecord record;
3081         final String permission;
3082 
ServiceLookupResult(ServiceRecord _record, String _permission)3083         ServiceLookupResult(ServiceRecord _record, String _permission) {
3084             record = _record;
3085             permission = _permission;
3086         }
3087     }
3088 
3089     private class ServiceRestarter implements Runnable {
3090         private ServiceRecord mService;
3091 
setService(ServiceRecord service)3092         void setService(ServiceRecord service) {
3093             mService = service;
3094         }
3095 
run()3096         public void run() {
3097             synchronized(mAm) {
3098                 performServiceRestartLocked(mService);
3099             }
3100         }
3101     }
3102 
retrieveServiceLocked(Intent service, String instanceName, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal, boolean allowInstant)3103     private ServiceLookupResult retrieveServiceLocked(Intent service,
3104             String instanceName, String resolvedType, String callingPackage,
3105             int callingPid, int callingUid, int userId,
3106             boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal,
3107             boolean allowInstant) {
3108         ServiceRecord r = null;
3109         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
3110                 + " type=" + resolvedType + " callingUid=" + callingUid);
3111 
3112         userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId,
3113                 /* allowAll= */false, getAllowMode(service, callingPackage),
3114                 /* name= */ "service", callingPackage);
3115 
3116         ServiceMap smap = getServiceMapLocked(userId);
3117         final ComponentName comp;
3118         if (instanceName == null) {
3119             comp = service.getComponent();
3120         } else {
3121             final ComponentName realComp = service.getComponent();
3122             if (realComp == null) {
3123                 throw new IllegalArgumentException("Can't use custom instance name '" + instanceName
3124                         + "' without expicit component in Intent");
3125             }
3126             comp = new ComponentName(realComp.getPackageName(),
3127                     realComp.getClassName() + ":" + instanceName);
3128         }
3129         if (comp != null) {
3130             r = smap.mServicesByInstanceName.get(comp);
3131             if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
3132         }
3133         if (r == null && !isBindExternal && instanceName == null) {
3134             Intent.FilterComparison filter = new Intent.FilterComparison(service);
3135             r = smap.mServicesByIntent.get(filter);
3136             if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
3137         }
3138         if (r != null) {
3139             // Compared to resolveService below, the ServiceRecord here is retrieved from
3140             // ServiceMap so the package visibility doesn't apply to it. We need to filter it.
3141             if (mAm.getPackageManagerInternal().filterAppAccess(r.packageName, callingUid,
3142                     userId)) {
3143                 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId
3144                         + ": not found");
3145                 return null;
3146             }
3147             if ((r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
3148                     && !callingPackage.equals(r.packageName)) {
3149                 // If an external service is running within its own package, other packages
3150                 // should not bind to that instance.
3151                 r = null;
3152                 if (DEBUG_SERVICE) {
3153                     Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
3154                 }
3155             }
3156         }
3157         if (r == null) {
3158             try {
3159                 int flags = ActivityManagerService.STOCK_PM_FLAGS
3160                         | PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3161                 if (allowInstant) {
3162                     flags |= PackageManager.MATCH_INSTANT;
3163                 }
3164                 // TODO: come back and remove this assumption to triage all services
3165                 ResolveInfo rInfo = mAm.getPackageManagerInternal().resolveService(service,
3166                         resolvedType, flags, userId, callingUid);
3167                 ServiceInfo sInfo = rInfo != null ? rInfo.serviceInfo : null;
3168                 if (sInfo == null) {
3169                     Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
3170                           ": not found");
3171                     return null;
3172                 }
3173                 if (instanceName != null
3174                         && (sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
3175                     throw new IllegalArgumentException("Can't use instance name '" + instanceName
3176                             + "' with non-isolated service '" + sInfo.name + "'");
3177                 }
3178                 ComponentName className = new ComponentName(
3179                         sInfo.applicationInfo.packageName, sInfo.name);
3180                 ComponentName name = comp != null ? comp : className;
3181                 if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid,
3182                         name.getPackageName(), sInfo.applicationInfo.uid)) {
3183                     String msg = "association not allowed between packages "
3184                             + callingPackage + " and " + name.getPackageName();
3185                     Slog.w(TAG, "Service lookup failed: " + msg);
3186                     return new ServiceLookupResult(null, msg);
3187                 }
3188 
3189                 // Store the defining packageName and uid, as they might be changed in
3190                 // the ApplicationInfo for external services (which run with the package name
3191                 // and uid of the caller).
3192                 String definingPackageName = sInfo.applicationInfo.packageName;
3193                 int definingUid = sInfo.applicationInfo.uid;
3194                 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
3195                     if (isBindExternal) {
3196                         if (!sInfo.exported) {
3197                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
3198                                     + className + " is not exported");
3199                         }
3200                         if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
3201                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, "
3202                                     + className + " is not an isolatedProcess");
3203                         }
3204                         // Run the service under the calling package's application.
3205                         ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
3206                                 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
3207                         if (aInfo == null) {
3208                             throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
3209                                     "could not resolve client package " + callingPackage);
3210                         }
3211                         sInfo = new ServiceInfo(sInfo);
3212                         sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
3213                         sInfo.applicationInfo.packageName = aInfo.packageName;
3214                         sInfo.applicationInfo.uid = aInfo.uid;
3215                         name = new ComponentName(aInfo.packageName, name.getClassName());
3216                         className = new ComponentName(aInfo.packageName,
3217                                 instanceName == null ? className.getClassName()
3218                                         : (className.getClassName() + ":" + instanceName));
3219                         service.setComponent(name);
3220                     } else {
3221                         throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
3222                                 name);
3223                     }
3224                 } else if (isBindExternal) {
3225                     throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
3226                             " is not an externalService");
3227                 }
3228                 if (userId > 0) {
3229                     if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
3230                             sInfo.name, sInfo.flags)
3231                             && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
3232                         userId = 0;
3233                         smap = getServiceMapLocked(0);
3234                         // Bypass INTERACT_ACROSS_USERS permission check
3235                         final long token = Binder.clearCallingIdentity();
3236                         try {
3237                             ResolveInfo rInfoForUserId0 =
3238                                     mAm.getPackageManagerInternal().resolveService(service,
3239                                             resolvedType, flags, userId, callingUid);
3240                             if (rInfoForUserId0 == null) {
3241                                 Slog.w(TAG_SERVICE,
3242                                         "Unable to resolve service " + service + " U=" + userId
3243                                                 + ": not found");
3244                                 return null;
3245                             }
3246                             sInfo = rInfoForUserId0.serviceInfo;
3247                         } finally {
3248                             Binder.restoreCallingIdentity(token);
3249                         }
3250                     }
3251                     sInfo = new ServiceInfo(sInfo);
3252                     sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
3253                 }
3254                 r = smap.mServicesByInstanceName.get(name);
3255                 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
3256                         "Retrieved via pm by intent: " + r);
3257                 if (r == null && createIfNeeded) {
3258                     final Intent.FilterComparison filter
3259                             = new Intent.FilterComparison(service.cloneFilter());
3260                     final ServiceRestarter res = new ServiceRestarter();
3261                     r = new ServiceRecord(mAm, className, name, definingPackageName,
3262                             definingUid, filter, sInfo, callingFromFg, res);
3263                     res.setService(r);
3264                     smap.mServicesByInstanceName.put(name, r);
3265                     smap.mServicesByIntent.put(filter, r);
3266 
3267                     // Make sure this component isn't in the pending list.
3268                     for (int i=mPendingServices.size()-1; i>=0; i--) {
3269                         final ServiceRecord pr = mPendingServices.get(i);
3270                         if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
3271                                 && pr.instanceName.equals(name)) {
3272                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
3273                             mPendingServices.remove(i);
3274                         }
3275                     }
3276                     for (int i = mPendingBringups.size() - 1; i >= 0; i--) {
3277                         final ServiceRecord pr = mPendingBringups.keyAt(i);
3278                         if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
3279                                 && pr.instanceName.equals(name)) {
3280                             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending bringup: " + pr);
3281                             mPendingBringups.removeAt(i);
3282                         }
3283                     }
3284                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
3285                 }
3286             } catch (RemoteException ex) {
3287                 // pm is in same process, this will never happen.
3288             }
3289         }
3290         if (r != null) {
3291             r.mRecentCallingPackage = callingPackage;
3292             r.mRecentCallingUid = callingUid;
3293             try {
3294                 r.mRecentCallerApplicationInfo =
3295                         mAm.mContext.getPackageManager().getApplicationInfoAsUser(callingPackage,
3296                                 0, UserHandle.getUserId(callingUid));
3297             } catch (PackageManager.NameNotFoundException e) {
3298             }
3299             if (!mAm.validateAssociationAllowedLocked(callingPackage, callingUid, r.packageName,
3300                     r.appInfo.uid)) {
3301                 String msg = "association not allowed between packages "
3302                         + callingPackage + " and " + r.packageName;
3303                 Slog.w(TAG, "Service lookup failed: " + msg);
3304                 return new ServiceLookupResult(null, msg);
3305             }
3306             if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
3307                     resolvedType, r.appInfo)) {
3308                 return new ServiceLookupResult(null, "blocked by firewall");
3309             }
3310             if (mAm.checkComponentPermission(r.permission,
3311                     callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
3312                 if (!r.exported) {
3313                     Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
3314                             + " from pid=" + callingPid
3315                             + ", uid=" + callingUid
3316                             + " that is not exported from uid " + r.appInfo.uid);
3317                     return new ServiceLookupResult(null, "not exported from uid "
3318                             + r.appInfo.uid);
3319                 }
3320                 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
3321                         + " from pid=" + callingPid
3322                         + ", uid=" + callingUid
3323                         + " requires " + r.permission);
3324                 return new ServiceLookupResult(null, r.permission);
3325             } else if (Manifest.permission.BIND_HOTWORD_DETECTION_SERVICE.equals(r.permission)
3326                     && callingUid != Process.SYSTEM_UID) {
3327                 // Hotword detection must run in its own sandbox, and we don't even trust
3328                 // its enclosing application to bind to it - only the system.
3329                 // TODO(b/185746653) remove this special case and generalize
3330                 Slog.w(TAG, "Permission Denial: Accessing service " + r.shortInstanceName
3331                         + " from pid=" + callingPid
3332                         + ", uid=" + callingUid
3333                         + " requiring permission " + r.permission
3334                         + " can only be bound to from the system.");
3335                 return new ServiceLookupResult(null, "can only be bound to "
3336                         + "by the system.");
3337             } else if (r.permission != null && callingPackage != null) {
3338                 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
3339                 if (opCode != AppOpsManager.OP_NONE && mAm.getAppOpsManager().checkOpNoThrow(
3340                         opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
3341                     Slog.w(TAG, "Appop Denial: Accessing service " + r.shortInstanceName
3342                             + " from pid=" + callingPid
3343                             + ", uid=" + callingUid
3344                             + " requires appop " + AppOpsManager.opToName(opCode));
3345                     return null;
3346                 }
3347             }
3348             return new ServiceLookupResult(r, null);
3349         }
3350         return null;
3351     }
3352 
getAllowMode(Intent service, @Nullable String callingPackage)3353     private int getAllowMode(Intent service, @Nullable String callingPackage) {
3354         if (callingPackage == null || service.getComponent() == null) {
3355             return ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
3356         }
3357         if (callingPackage.equals(service.getComponent().getPackageName())) {
3358             return ActivityManagerInternal.ALLOW_ALL_PROFILE_PERMISSIONS_IN_PROFILE;
3359         } else {
3360             return ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
3361         }
3362     }
3363 
3364     /**
3365      * Bump the given service record into executing state.
3366      * @param oomAdjReason The caller requests it to perform the oomAdjUpdate if it's not null.
3367      * @return {@code true} if it performed oomAdjUpdate.
3368      */
bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why, @Nullable String oomAdjReason)3369     private boolean bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why,
3370             @Nullable String oomAdjReason) {
3371         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
3372                 + why + " of " + r + " in app " + r.app);
3373         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
3374                 + why + " of " + r.shortInstanceName);
3375 
3376         // For b/34123235: Services within the system server won't start until SystemServer
3377         // does Looper.loop(), so we shouldn't try to start/bind to them too early in the boot
3378         // process. However, since there's a little point of showing the ANR dialog in that case,
3379         // let's suppress the timeout until PHASE_THIRD_PARTY_APPS_CAN_START.
3380         //
3381         // (Note there are multiple services start at PHASE_THIRD_PARTY_APPS_CAN_START too,
3382         // which technically could also trigger this timeout if there's a system server
3383         // that takes a long time to handle PHASE_THIRD_PARTY_APPS_CAN_START, but that shouldn't
3384         // happen.)
3385         boolean timeoutNeeded = true;
3386         if ((mAm.mBootPhase < SystemService.PHASE_THIRD_PARTY_APPS_CAN_START)
3387                 && (r.app != null) && (r.app.getPid() == ActivityManagerService.MY_PID)) {
3388 
3389             Slog.w(TAG, "Too early to start/bind service in system_server: Phase=" + mAm.mBootPhase
3390                     + " " + r.getComponentName());
3391             timeoutNeeded = false;
3392         }
3393 
3394         long now = SystemClock.uptimeMillis();
3395         ProcessServiceRecord psr;
3396         if (r.executeNesting == 0) {
3397             r.executeFg = fg;
3398             synchronized (mAm.mProcessStats.mLock) {
3399                 final ServiceState stracker = r.getTracker();
3400                 if (stracker != null) {
3401                     stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
3402                 }
3403             }
3404             if (r.app != null) {
3405                 psr = r.app.mServices;
3406                 psr.startExecutingService(r);
3407                 psr.setExecServicesFg(psr.shouldExecServicesFg() || fg);
3408                 if (timeoutNeeded && psr.numberOfExecutingServices() == 1) {
3409                     scheduleServiceTimeoutLocked(r.app);
3410                 }
3411             }
3412         } else if (r.app != null && fg) {
3413             psr = r.app.mServices;
3414             if (!psr.shouldExecServicesFg()) {
3415                 psr.setExecServicesFg(true);
3416                 if (timeoutNeeded) {
3417                     scheduleServiceTimeoutLocked(r.app);
3418                 }
3419             }
3420         }
3421         boolean oomAdjusted = false;
3422         if (oomAdjReason != null && r.app != null
3423                 && r.app.mState.getCurProcState() > ActivityManager.PROCESS_STATE_SERVICE) {
3424             // Force an immediate oomAdjUpdate, so the client app could be in the correct process
3425             // state before doing any service related transactions
3426             mAm.enqueueOomAdjTargetLocked(r.app);
3427             mAm.updateOomAdjPendingTargetsLocked(oomAdjReason);
3428             oomAdjusted = true;
3429         }
3430         r.executeFg |= fg;
3431         r.executeNesting++;
3432         r.executingStart = now;
3433         return oomAdjusted;
3434     }
3435 
requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind)3436     private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
3437             boolean execInFg, boolean rebind) throws TransactionTooLargeException {
3438         if (r.app == null || r.app.getThread() == null) {
3439             // If service is not currently running, can't yet bind.
3440             return false;
3441         }
3442         if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
3443                 + " rebind=" + rebind);
3444         if ((!i.requested || rebind) && i.apps.size() > 0) {
3445             try {
3446                 bumpServiceExecutingLocked(r, execInFg, "bind",
3447                         OomAdjuster.OOM_ADJ_REASON_BIND_SERVICE);
3448                 r.app.getThread().scheduleBindService(r, i.intent.getIntent(), rebind,
3449                         r.app.mState.getReportedProcState());
3450                 if (!rebind) {
3451                     i.requested = true;
3452                 }
3453                 i.hasBound = true;
3454                 i.doRebind = false;
3455             } catch (TransactionTooLargeException e) {
3456                 // Keep the executeNesting count accurate.
3457                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
3458                 final boolean inDestroying = mDestroyingServices.contains(r);
3459                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, false);
3460                 throw e;
3461             } catch (RemoteException e) {
3462                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
3463                 // Keep the executeNesting count accurate.
3464                 final boolean inDestroying = mDestroyingServices.contains(r);
3465                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, false);
3466                 return false;
3467             }
3468         }
3469         return true;
3470     }
3471 
3472     /** @return {@code true} if the restart is scheduled. */
scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel)3473     private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
3474         if (mAm.mAtmInternal.isShuttingDown()) {
3475             Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortInstanceName
3476                     + " - system is shutting down");
3477             return false;
3478         }
3479 
3480         ServiceMap smap = getServiceMapLocked(r.userId);
3481         if (smap.mServicesByInstanceName.get(r.instanceName) != r) {
3482             ServiceRecord cur = smap.mServicesByInstanceName.get(r.instanceName);
3483             Slog.wtf(TAG, "Attempting to schedule restart of " + r
3484                     + " when found in map: " + cur);
3485             return false;
3486         }
3487 
3488         final long now = SystemClock.uptimeMillis();
3489 
3490         final String reason;
3491         if ((r.serviceInfo.applicationInfo.flags
3492                 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
3493             long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
3494             long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
3495             boolean canceled = false;
3496 
3497             // Any delivered but not yet finished starts should be put back
3498             // on the pending list.
3499             final int N = r.deliveredStarts.size();
3500             if (N > 0) {
3501                 for (int i=N-1; i>=0; i--) {
3502                     ServiceRecord.StartItem si = r.deliveredStarts.get(i);
3503                     si.removeUriPermissionsLocked();
3504                     if (si.intent == null) {
3505                         // We'll generate this again if needed.
3506                     } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
3507                             && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
3508                         r.pendingStarts.add(0, si);
3509                         long dur = SystemClock.uptimeMillis() - si.deliveredTime;
3510                         dur *= 2;
3511                         if (minDuration < dur) minDuration = dur;
3512                         if (resetTime < dur) resetTime = dur;
3513                     } else {
3514                         Slog.w(TAG, "Canceling start item " + si.intent + " in service "
3515                                 + r.shortInstanceName);
3516                         canceled = true;
3517                     }
3518                 }
3519                 r.deliveredStarts.clear();
3520             }
3521 
3522             if (allowCancel) {
3523                 final boolean shouldStop = r.canStopIfKilled(canceled);
3524                 if (shouldStop && !r.hasAutoCreateConnections()) {
3525                     // Nothing to restart.
3526                     return false;
3527                 }
3528                 reason = (r.startRequested && !shouldStop) ? "start-requested" : "connection";
3529             } else {
3530                 reason = "always";
3531             }
3532 
3533             r.totalRestartCount++;
3534             if (r.restartDelay == 0) {
3535                 r.restartCount++;
3536                 r.restartDelay = minDuration;
3537             } else if (r.crashCount > 1) {
3538                 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
3539                         * (r.crashCount - 1);
3540             } else {
3541                 // If it has been a "reasonably long time" since the service
3542                 // was started, then reset our restart duration back to
3543                 // the beginning, so we don't infinitely increase the duration
3544                 // on a service that just occasionally gets killed (which is
3545                 // a normal case, due to process being killed to reclaim memory).
3546                 if (now > (r.restartTime+resetTime)) {
3547                     r.restartCount = 1;
3548                     r.restartDelay = minDuration;
3549                 } else {
3550                     r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
3551                     if (r.restartDelay < minDuration) {
3552                         r.restartDelay = minDuration;
3553                     }
3554                 }
3555             }
3556 
3557             if (isServiceRestartBackoffEnabledLocked(r.packageName)) {
3558                 r.nextRestartTime = now + r.restartDelay;
3559 
3560                 // Make sure that we don't end up restarting a bunch of services
3561                 // all at the same time.
3562                 boolean repeat;
3563                 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
3564                 do {
3565                     repeat = false;
3566                     for (int i = mRestartingServices.size() - 1; i >= 0; i--) {
3567                         final ServiceRecord r2 = mRestartingServices.get(i);
3568                         if (r2 != r
3569                                 && r.nextRestartTime >= (r2.nextRestartTime - restartTimeBetween)
3570                                 && r.nextRestartTime < (r2.nextRestartTime + restartTimeBetween)) {
3571                             r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
3572                             r.restartDelay = r.nextRestartTime - now;
3573                             repeat = true;
3574                             break;
3575                         }
3576                     }
3577                 } while (repeat);
3578             } else {
3579                 // It's been forced to ignore the restart backoff, fix the delay here.
3580                 r.restartDelay = mAm.mConstants.SERVICE_RESTART_DURATION;
3581                 r.nextRestartTime = now + r.restartDelay;
3582             }
3583 
3584         } else {
3585             // Persistent processes are immediately restarted, so there is no
3586             // reason to hold of on restarting their services.
3587             r.totalRestartCount++;
3588             r.restartCount = 0;
3589             r.restartDelay = 0;
3590             r.nextRestartTime = now;
3591             reason = "persistent";
3592         }
3593 
3594         if (!mRestartingServices.contains(r)) {
3595             r.createdFromFg = false;
3596             mRestartingServices.add(r);
3597             synchronized (mAm.mProcessStats.mLock) {
3598                 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
3599             }
3600         }
3601 
3602         cancelForegroundNotificationLocked(r);
3603 
3604         performScheduleRestartLocked(r, "Scheduling", reason, SystemClock.uptimeMillis());
3605 
3606         return true;
3607     }
3608 
3609     @VisibleForTesting
3610     @GuardedBy("mAm")
performScheduleRestartLocked(ServiceRecord r, @NonNull String scheduling, @NonNull String reason, @UptimeMillisLong long now)3611     void performScheduleRestartLocked(ServiceRecord r, @NonNull String scheduling,
3612             @NonNull String reason, @UptimeMillisLong long now) {
3613         mAm.mHandler.removeCallbacks(r.restarter);
3614         mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
3615         r.nextRestartTime = now + r.restartDelay;
3616         Slog.w(TAG, scheduling + " restart of crashed service "
3617                 + r.shortInstanceName + " in " + r.restartDelay + "ms for " + reason);
3618         EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
3619                 r.userId, r.shortInstanceName, r.restartDelay);
3620     }
3621 
performServiceRestartLocked(ServiceRecord r)3622     final void performServiceRestartLocked(ServiceRecord r) {
3623         if (!mRestartingServices.contains(r)) {
3624             return;
3625         }
3626         if (!isServiceNeededLocked(r, false, false)) {
3627             // Paranoia: is this service actually needed?  In theory a service that is not
3628             // needed should never remain on the restart list.  In practice...  well, there
3629             // have been bugs where this happens, and bad things happen because the process
3630             // ends up just being cached, so quickly killed, then restarted again and again.
3631             // Let's not let that happen.
3632             Slog.wtf(TAG, "Restarting service that is not needed: " + r);
3633             return;
3634         }
3635         try {
3636             bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false,
3637                     false, true);
3638         } catch (TransactionTooLargeException e) {
3639             // Ignore, it's been logged and nothing upstack cares.
3640         } finally {
3641             /* Will be a no-op if nothing pending */
3642             mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
3643         }
3644     }
3645 
unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, boolean force)3646     private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
3647             boolean force) {
3648         if (!force && r.restartDelay == 0) {
3649             return false;
3650         }
3651         // Remove from the restarting list; if the service is currently on the
3652         // restarting list, or the call is coming from another app, then this
3653         // service has become of much more interest so we reset the restart interval.
3654         boolean removed = mRestartingServices.remove(r);
3655         if (removed || callingUid != r.appInfo.uid) {
3656             r.resetRestartCounter();
3657         }
3658         if (removed) {
3659             clearRestartingIfNeededLocked(r);
3660         }
3661         mAm.mHandler.removeCallbacks(r.restarter);
3662         return true;
3663     }
3664 
clearRestartingIfNeededLocked(ServiceRecord r)3665     private void clearRestartingIfNeededLocked(ServiceRecord r) {
3666         if (r.restartTracker != null) {
3667             // If this is the last restarting record with this tracker, then clear
3668             // the tracker's restarting state.
3669             boolean stillTracking = false;
3670             for (int i=mRestartingServices.size()-1; i>=0; i--) {
3671                 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
3672                     stillTracking = true;
3673                     break;
3674                 }
3675             }
3676             if (!stillTracking) {
3677                 synchronized (mAm.mProcessStats.mLock) {
3678                     r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
3679                             SystemClock.uptimeMillis());
3680                 }
3681                 r.restartTracker = null;
3682             }
3683         }
3684     }
3685 
3686     /**
3687      * Toggle service restart backoff policy, used by {@link ActivityManagerShellCommand}.
3688      */
3689     @GuardedBy("mAm")
setServiceRestartBackoffEnabledLocked(@onNull String packageName, boolean enable, @NonNull String reason)3690     void setServiceRestartBackoffEnabledLocked(@NonNull String packageName, boolean enable,
3691             @NonNull String reason) {
3692         if (!enable) {
3693             if (mRestartBackoffDisabledPackages.contains(packageName)) {
3694                 // Already disabled, do nothing.
3695                 return;
3696             }
3697             mRestartBackoffDisabledPackages.add(packageName);
3698 
3699             final long now = SystemClock.uptimeMillis();
3700             for (int i = 0, size = mRestartingServices.size(); i < size; i++) {
3701                 final ServiceRecord r = mRestartingServices.get(i);
3702                 if (TextUtils.equals(r.packageName, packageName)) {
3703                     final long remaining = r.nextRestartTime - now;
3704                     if (remaining > mAm.mConstants.SERVICE_RESTART_DURATION) {
3705                         r.restartDelay = mAm.mConstants.SERVICE_RESTART_DURATION;
3706                         r.nextRestartTime = now + r.restartDelay;
3707                         performScheduleRestartLocked(r, "Rescheduling", reason, now);
3708                     }
3709                 }
3710             }
3711         } else {
3712             removeServiceRestartBackoffEnabledLocked(packageName);
3713             // For the simplicity, we are not going to reschedule its pending restarts
3714             // when we turn the backoff policy back on.
3715         }
3716     }
3717 
3718     @GuardedBy("mAm")
removeServiceRestartBackoffEnabledLocked(@onNull String packageName)3719     private void removeServiceRestartBackoffEnabledLocked(@NonNull String packageName) {
3720         mRestartBackoffDisabledPackages.remove(packageName);
3721     }
3722 
3723     /**
3724      * @return {@code false} if the given package has been disable from enforcing the service
3725      * restart backoff policy, used by {@link ActivityManagerShellCommand}.
3726      */
3727     @GuardedBy("mAm")
isServiceRestartBackoffEnabledLocked(@onNull String packageName)3728     boolean isServiceRestartBackoffEnabledLocked(@NonNull String packageName) {
3729         return !mRestartBackoffDisabledPackages.contains(packageName);
3730     }
3731 
bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen, boolean enqueueOomAdj)3732     private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
3733             boolean whileRestarting, boolean permissionsReviewRequired, boolean packageFrozen,
3734             boolean enqueueOomAdj)
3735             throws TransactionTooLargeException {
3736         if (r.app != null && r.app.getThread() != null) {
3737             sendServiceArgsLocked(r, execInFg, false);
3738             return null;
3739         }
3740 
3741         if (!whileRestarting && mRestartingServices.contains(r)) {
3742             // If waiting for a restart, then do nothing.
3743             return null;
3744         }
3745 
3746         if (DEBUG_SERVICE) {
3747             Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
3748         }
3749 
3750         // We are now bringing the service up, so no longer in the
3751         // restarting state.
3752         if (mRestartingServices.remove(r)) {
3753             clearRestartingIfNeededLocked(r);
3754         }
3755 
3756         // Make sure this service is no longer considered delayed, we are starting it now.
3757         if (r.delayed) {
3758             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
3759             getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
3760             r.delayed = false;
3761         }
3762 
3763         // Make sure that the user who owns this service is started.  If not,
3764         // we don't want to allow it to run.
3765         if (!mAm.mUserController.hasStartedUserState(r.userId)) {
3766             String msg = "Unable to launch app "
3767                     + r.appInfo.packageName + "/"
3768                     + r.appInfo.uid + " for service "
3769                     + r.intent.getIntent() + ": user " + r.userId + " is stopped";
3770             Slog.w(TAG, msg);
3771             bringDownServiceLocked(r, enqueueOomAdj);
3772             return msg;
3773         }
3774 
3775         // Report usage if binding is from a different package except for explicitly exempted
3776         // bindings
3777         if (!r.appInfo.packageName.equals(r.mRecentCallingPackage)
3778                 && !r.isNotAppComponentUsage) {
3779             mAm.mUsageStatsService.reportEvent(
3780                     r.packageName, r.userId, UsageEvents.Event.APP_COMPONENT_USED);
3781         }
3782 
3783         // Service is now being launched, its package can't be stopped.
3784         try {
3785             AppGlobals.getPackageManager().setPackageStoppedState(
3786                     r.packageName, false, r.userId);
3787         } catch (RemoteException e) {
3788         } catch (IllegalArgumentException e) {
3789             Slog.w(TAG, "Failed trying to unstop package "
3790                     + r.packageName + ": " + e);
3791         }
3792 
3793         final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
3794         final String procName = r.processName;
3795         HostingRecord hostingRecord = new HostingRecord("service", r.instanceName);
3796         ProcessRecord app;
3797 
3798         if (!isolated) {
3799             app = mAm.getProcessRecordLocked(procName, r.appInfo.uid);
3800             if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
3801                         + " app=" + app);
3802             if (app != null) {
3803                 final IApplicationThread thread = app.getThread();
3804                 final int pid = app.getPid();
3805                 final UidRecord uidRecord = app.getUidRecord();
3806                 if (thread != null) {
3807                     try {
3808                         app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode,
3809                                 mAm.mProcessStats);
3810                         realStartServiceLocked(r, app, thread, pid, uidRecord, execInFg,
3811                                 enqueueOomAdj);
3812                         return null;
3813                     } catch (TransactionTooLargeException e) {
3814                         throw e;
3815                     } catch (RemoteException e) {
3816                         Slog.w(TAG, "Exception when starting service " + r.shortInstanceName, e);
3817                     }
3818 
3819                     // If a dead object exception was thrown -- fall through to
3820                     // restart the application.
3821                 }
3822             }
3823         } else {
3824             // If this service runs in an isolated process, then each time
3825             // we call startProcessLocked() we will get a new isolated
3826             // process, starting another process if we are currently waiting
3827             // for a previous process to come up.  To deal with this, we store
3828             // in the service any current isolated process it is running in or
3829             // waiting to have come up.
3830             app = r.isolatedProc;
3831             if (WebViewZygote.isMultiprocessEnabled()
3832                     && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
3833                 hostingRecord = HostingRecord.byWebviewZygote(r.instanceName);
3834             }
3835             if ((r.serviceInfo.flags & ServiceInfo.FLAG_USE_APP_ZYGOTE) != 0) {
3836                 hostingRecord = HostingRecord.byAppZygote(r.instanceName, r.definingPackageName,
3837                         r.definingUid);
3838             }
3839         }
3840 
3841         // Not running -- get it started, and enqueue this service record
3842         // to be executed when the app comes up.
3843         if (app == null && !permissionsReviewRequired && !packageFrozen) {
3844             // TODO (chriswailes): Change the Zygote policy flags based on if the launch-for-service
3845             //  was initiated from a notification tap or not.
3846             if ((app = mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
3847                         hostingRecord, ZYGOTE_POLICY_FLAG_EMPTY, false, isolated)) == null) {
3848                 String msg = "Unable to launch app "
3849                         + r.appInfo.packageName + "/"
3850                         + r.appInfo.uid + " for service "
3851                         + r.intent.getIntent() + ": process is bad";
3852                 Slog.w(TAG, msg);
3853                 bringDownServiceLocked(r, enqueueOomAdj);
3854                 return msg;
3855             }
3856             if (isolated) {
3857                 r.isolatedProc = app;
3858             }
3859         }
3860 
3861         if (r.fgRequired) {
3862             if (DEBUG_FOREGROUND_SERVICE) {
3863                 Slog.v(TAG, "Allowlisting " + UserHandle.formatUid(r.appInfo.uid)
3864                         + " for fg-service launch");
3865             }
3866             mAm.tempAllowlistUidLocked(r.appInfo.uid,
3867                     SERVICE_START_FOREGROUND_TIMEOUT, REASON_SERVICE_LAUNCH,
3868                     "fg-service-launch",
3869                     TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED,
3870                     r.mRecentCallingUid);
3871         }
3872 
3873         if (!mPendingServices.contains(r)) {
3874             mPendingServices.add(r);
3875         }
3876 
3877         if (r.delayedStop) {
3878             // Oh and hey we've already been asked to stop!
3879             r.delayedStop = false;
3880             if (r.startRequested) {
3881                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
3882                         "Applying delayed stop (in bring up): " + r);
3883                 stopServiceLocked(r, enqueueOomAdj);
3884             }
3885         }
3886 
3887         return null;
3888     }
3889 
requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)3890     private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
3891             throws TransactionTooLargeException {
3892         for (int i=r.bindings.size()-1; i>=0; i--) {
3893             IntentBindRecord ibr = r.bindings.valueAt(i);
3894             if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
3895                 break;
3896             }
3897         }
3898     }
3899 
3900     /**
3901      * Note the name of this method should not be confused with the started services concept.
3902      * The "start" here means bring up the instance in the client, and this method is called
3903      * from bindService() as well.
3904      */
realStartServiceLocked(ServiceRecord r, ProcessRecord app, IApplicationThread thread, int pid, UidRecord uidRecord, boolean execInFg, boolean enqueueOomAdj)3905     private void realStartServiceLocked(ServiceRecord r, ProcessRecord app,
3906             IApplicationThread thread, int pid, UidRecord uidRecord, boolean execInFg,
3907             boolean enqueueOomAdj) throws RemoteException {
3908         if (thread == null) {
3909             throw new RemoteException();
3910         }
3911         if (DEBUG_MU)
3912             Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
3913                     + ", ProcessRecord.uid = " + app.uid);
3914         r.setProcess(app, thread, pid, uidRecord);
3915         r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
3916 
3917         final ProcessServiceRecord psr = app.mServices;
3918         final boolean newService = psr.startService(r);
3919         bumpServiceExecutingLocked(r, execInFg, "create", null /* oomAdjReason */);
3920         mAm.updateLruProcessLocked(app, false, null);
3921         updateServiceForegroundLocked(psr, /* oomAdj= */ false);
3922         // Force an immediate oomAdjUpdate, so the client app could be in the correct process state
3923         // before doing any service related transactions
3924         mAm.enqueueOomAdjTargetLocked(app);
3925         mAm.updateOomAdjLocked(app, OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
3926 
3927         boolean created = false;
3928         try {
3929             if (LOG_SERVICE_START_STOP) {
3930                 String nameTerm;
3931                 int lastPeriod = r.shortInstanceName.lastIndexOf('.');
3932                 nameTerm = lastPeriod >= 0 ? r.shortInstanceName.substring(lastPeriod)
3933                         : r.shortInstanceName;
3934                 EventLogTags.writeAmCreateService(
3935                         r.userId, System.identityHashCode(r), nameTerm, r.app.uid, pid);
3936             }
3937 
3938             final int uid = r.appInfo.uid;
3939             final String packageName = r.name.getPackageName();
3940             final String serviceName = r.name.getClassName();
3941             FrameworkStatsLog.write(FrameworkStatsLog.SERVICE_LAUNCH_REPORTED, uid, packageName,
3942                     serviceName);
3943             mAm.mBatteryStatsService.noteServiceStartLaunch(uid, packageName, serviceName);
3944             mAm.notifyPackageUse(r.serviceInfo.packageName,
3945                                  PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
3946             thread.scheduleCreateService(r, r.serviceInfo,
3947                     mAm.compatibilityInfoForPackage(r.serviceInfo.applicationInfo),
3948                     app.mState.getReportedProcState());
3949             r.postNotification();
3950             created = true;
3951         } catch (DeadObjectException e) {
3952             Slog.w(TAG, "Application dead when creating service " + r);
3953             mAm.appDiedLocked(app, "Died when creating service");
3954             throw e;
3955         } finally {
3956             if (!created) {
3957                 // Keep the executeNesting count accurate.
3958                 final boolean inDestroying = mDestroyingServices.contains(r);
3959                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, false);
3960 
3961                 // Cleanup.
3962                 if (newService) {
3963                     psr.stopService(r);
3964                     r.setProcess(null, null, 0, null);
3965                 }
3966 
3967                 // Retry.
3968                 if (!inDestroying) {
3969                     scheduleServiceRestartLocked(r, false);
3970                 }
3971             }
3972         }
3973 
3974         if (r.allowlistManager) {
3975             psr.mAllowlistManager = true;
3976         }
3977 
3978         requestServiceBindingsLocked(r, execInFg);
3979 
3980         updateServiceClientActivitiesLocked(psr, null, true);
3981 
3982         if (newService && created) {
3983             psr.addBoundClientUidsOfNewService(r);
3984         }
3985 
3986         // If the service is in the started state, and there are no
3987         // pending arguments, then fake up one so its onStartCommand() will
3988         // be called.
3989         if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
3990             r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
3991                     null, null, 0));
3992         }
3993 
3994         sendServiceArgsLocked(r, execInFg, true);
3995 
3996         if (r.delayed) {
3997             if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
3998             getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
3999             r.delayed = false;
4000         }
4001 
4002         if (r.delayedStop) {
4003             // Oh and hey we've already been asked to stop!
4004             r.delayedStop = false;
4005             if (r.startRequested) {
4006                 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
4007                         "Applying delayed stop (from start): " + r);
4008                 stopServiceLocked(r, enqueueOomAdj);
4009             }
4010         }
4011     }
4012 
sendServiceArgsLocked(ServiceRecord r, boolean execInFg, boolean oomAdjusted)4013     private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
4014             boolean oomAdjusted) throws TransactionTooLargeException {
4015         final int N = r.pendingStarts.size();
4016         if (N == 0) {
4017             return;
4018         }
4019 
4020         ArrayList<ServiceStartArgs> args = new ArrayList<>();
4021 
4022         while (r.pendingStarts.size() > 0) {
4023             ServiceRecord.StartItem si = r.pendingStarts.remove(0);
4024             if (DEBUG_SERVICE) {
4025                 Slog.v(TAG_SERVICE, "Sending arguments to: "
4026                         + r + " " + r.intent + " args=" + si.intent);
4027             }
4028             if (si.intent == null && N > 1) {
4029                 // If somehow we got a dummy null intent in the middle,
4030                 // then skip it.  DO NOT skip a null intent when it is
4031                 // the only one in the list -- this is to support the
4032                 // onStartCommand(null) case.
4033                 continue;
4034             }
4035             si.deliveredTime = SystemClock.uptimeMillis();
4036             r.deliveredStarts.add(si);
4037             si.deliveryCount++;
4038             if (si.neededGrants != null) {
4039                 mAm.mUgmInternal.grantUriPermissionUncheckedFromIntent(si.neededGrants,
4040                         si.getUriPermissionsLocked());
4041             }
4042             mAm.grantImplicitAccess(r.userId, si.intent, si.callingId,
4043                     UserHandle.getAppId(r.appInfo.uid)
4044             );
4045             bumpServiceExecutingLocked(r, execInFg, "start", null /* oomAdjReason */);
4046             if (r.fgRequired && !r.fgWaiting) {
4047                 if (!r.isForeground) {
4048                     if (DEBUG_BACKGROUND_CHECK) {
4049                         Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
4050                     }
4051                     scheduleServiceForegroundTransitionTimeoutLocked(r);
4052                 } else {
4053                     if (DEBUG_BACKGROUND_CHECK) {
4054                         Slog.i(TAG, "Service already foreground; no new timeout: " + r);
4055                     }
4056                     r.fgRequired = false;
4057                 }
4058             }
4059             int flags = 0;
4060             if (si.deliveryCount > 1) {
4061                 flags |= Service.START_FLAG_RETRY;
4062             }
4063             if (si.doneExecutingCount > 0) {
4064                 flags |= Service.START_FLAG_REDELIVERY;
4065             }
4066             args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
4067         }
4068 
4069         if (!oomAdjusted) {
4070             mAm.enqueueOomAdjTargetLocked(r.app);
4071             mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
4072         }
4073         ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
4074         slice.setInlineCountLimit(4);
4075         Exception caughtException = null;
4076         try {
4077             r.app.getThread().scheduleServiceArgs(r, slice);
4078         } catch (TransactionTooLargeException e) {
4079             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
4080                     + " args, first: " + args.get(0).args);
4081             Slog.w(TAG, "Failed delivering service starts", e);
4082             caughtException = e;
4083         } catch (RemoteException e) {
4084             // Remote process gone...  we'll let the normal cleanup take care of this.
4085             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
4086             Slog.w(TAG, "Failed delivering service starts", e);
4087             caughtException = e;
4088         } catch (Exception e) {
4089             Slog.w(TAG, "Unexpected exception", e);
4090             caughtException = e;
4091         }
4092 
4093         if (caughtException != null) {
4094             // Keep nesting count correct
4095             final boolean inDestroying = mDestroyingServices.contains(r);
4096             for (int i = 0, size = args.size(); i < size; i++) {
4097                 serviceDoneExecutingLocked(r, inDestroying, inDestroying, true);
4098             }
4099             /* Will be a no-op if nothing pending */
4100             mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4101             if (caughtException instanceof TransactionTooLargeException) {
4102                 throw (TransactionTooLargeException)caughtException;
4103             }
4104         }
4105     }
4106 
isServiceNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)4107     private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
4108             boolean hasConn) {
4109         // Are we still explicitly being asked to run?
4110         if (r.startRequested) {
4111             return true;
4112         }
4113 
4114         // Is someone still bound to us keeping us running?
4115         if (!knowConn) {
4116             hasConn = r.hasAutoCreateConnections();
4117         }
4118         if (hasConn) {
4119             return true;
4120         }
4121 
4122         return false;
4123     }
4124 
bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn, boolean enqueueOomAdj)4125     private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
4126             boolean hasConn, boolean enqueueOomAdj) {
4127         //Slog.i(TAG, "Bring down service:");
4128         //r.dump("  ");
4129 
4130         if (isServiceNeededLocked(r, knowConn, hasConn)) {
4131             return;
4132         }
4133 
4134         // Are we in the process of launching?
4135         if (mPendingServices.contains(r)) {
4136             return;
4137         }
4138 
4139         bringDownServiceLocked(r, enqueueOomAdj);
4140     }
4141 
bringDownServiceLocked(ServiceRecord r, boolean enqueueOomAdj)4142     private void bringDownServiceLocked(ServiceRecord r, boolean enqueueOomAdj) {
4143         //Slog.i(TAG, "Bring down service:");
4144         //r.dump("  ");
4145 
4146         // Report to all of the connections that the service is no longer
4147         // available.
4148         ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4149         for (int conni = connections.size() - 1; conni >= 0; conni--) {
4150             ArrayList<ConnectionRecord> c = connections.valueAt(conni);
4151             for (int i=0; i<c.size(); i++) {
4152                 ConnectionRecord cr = c.get(i);
4153                 // There is still a connection to the service that is
4154                 // being brought down.  Mark it as dead.
4155                 cr.serviceDead = true;
4156                 cr.stopAssociation();
4157                 try {
4158                     cr.conn.connected(r.name, null, true);
4159                 } catch (Exception e) {
4160                     Slog.w(TAG, "Failure disconnecting service " + r.shortInstanceName
4161                           + " to connection " + c.get(i).conn.asBinder()
4162                           + " (in " + c.get(i).binding.client.processName + ")", e);
4163                 }
4164             }
4165         }
4166 
4167         boolean oomAdjusted = false;
4168         // Tell the service that it has been unbound.
4169         if (r.app != null && r.app.getThread() != null) {
4170             for (int i = r.bindings.size() - 1; i >= 0; i--) {
4171                 IntentBindRecord ibr = r.bindings.valueAt(i);
4172                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
4173                         + ": hasBound=" + ibr.hasBound);
4174                 if (ibr.hasBound) {
4175                     try {
4176                         oomAdjusted |= bumpServiceExecutingLocked(r, false, "bring down unbind",
4177                                 OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4178                         ibr.hasBound = false;
4179                         ibr.requested = false;
4180                         r.app.getThread().scheduleUnbindService(r,
4181                                 ibr.intent.getIntent());
4182                     } catch (Exception e) {
4183                         Slog.w(TAG, "Exception when unbinding service "
4184                                 + r.shortInstanceName, e);
4185                         serviceProcessGoneLocked(r, enqueueOomAdj);
4186                         break;
4187                     }
4188                 }
4189             }
4190         }
4191 
4192         final long now = SystemClock.uptimeMillis();
4193         // Check to see if the service had been started as foreground, but being
4194         // brought down before actually showing a notification.  That is not allowed.
4195         if (r.fgRequired) {
4196             Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
4197                     + r);
4198             r.fgRequired = false;
4199             r.fgWaiting = false;
4200             synchronized (mAm.mProcessStats.mLock) {
4201                 ServiceState stracker = r.getTracker();
4202                 if (stracker != null) {
4203                     stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), now);
4204                 }
4205             }
4206             mAm.mAppOpsService.finishOperation(AppOpsManager.getToken(mAm.mAppOpsService),
4207                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
4208             mAm.mHandler.removeMessages(
4209                     ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
4210             if (r.app != null) {
4211                 Message msg = mAm.mHandler.obtainMessage(
4212                         ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
4213                 SomeArgs args = SomeArgs.obtain();
4214                 args.arg1 = r.app;
4215                 args.arg2 = r.toString();
4216                 args.arg3 = r.getComponentName();
4217 
4218                 msg.obj = args;
4219                 mAm.mHandler.sendMessage(msg);
4220             }
4221         }
4222 
4223         if (DEBUG_SERVICE) {
4224             RuntimeException here = new RuntimeException();
4225             here.fillInStackTrace();
4226             Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
4227         }
4228         r.destroyTime = SystemClock.uptimeMillis();
4229         if (LOG_SERVICE_START_STOP) {
4230             EventLogTags.writeAmDestroyService(
4231                     r.userId, System.identityHashCode(r), (r.app != null) ? r.app.getPid() : -1);
4232         }
4233 
4234         final ServiceMap smap = getServiceMapLocked(r.userId);
4235         ServiceRecord found = smap.mServicesByInstanceName.remove(r.instanceName);
4236 
4237         // Note when this method is called by bringUpServiceLocked(), the service is not found
4238         // in mServicesByInstanceName and found will be null.
4239         if (found != null && found != r) {
4240             // This is not actually the service we think is running...  this should not happen,
4241             // but if it does, fail hard.
4242             smap.mServicesByInstanceName.put(r.instanceName, found);
4243             throw new IllegalStateException("Bringing down " + r + " but actually running "
4244                     + found);
4245         }
4246         smap.mServicesByIntent.remove(r.intent);
4247         r.totalRestartCount = 0;
4248         unscheduleServiceRestartLocked(r, 0, true);
4249 
4250         // Also make sure it is not on the pending list.
4251         for (int i=mPendingServices.size()-1; i>=0; i--) {
4252             if (mPendingServices.get(i) == r) {
4253                 mPendingServices.remove(i);
4254                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
4255             }
4256         }
4257         if (mPendingBringups.remove(r) != null) {
4258             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending bringup: " + r);
4259         }
4260 
4261         cancelForegroundNotificationLocked(r);
4262         if (r.isForeground) {
4263             decActiveForegroundAppLocked(smap, r);
4264             synchronized (mAm.mProcessStats.mLock) {
4265                 ServiceState stracker = r.getTracker();
4266                 if (stracker != null) {
4267                     stracker.setForeground(false, mAm.mProcessStats.getMemFactorLocked(), now);
4268                 }
4269             }
4270             mAm.mAppOpsService.finishOperation(
4271                     AppOpsManager.getToken(mAm.mAppOpsService),
4272                     AppOpsManager.OP_START_FOREGROUND, r.appInfo.uid, r.packageName, null);
4273             unregisterAppOpCallbackLocked(r);
4274             r.mFgsExitTime = SystemClock.uptimeMillis();
4275             logFGSStateChangeLocked(r,
4276                     FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT,
4277                     r.mFgsExitTime > r.mFgsEnterTime
4278                             ? (int)(r.mFgsExitTime - r.mFgsEnterTime) : 0);
4279             mAm.updateForegroundServiceUsageStats(r.name, r.userId, false);
4280         }
4281 
4282         r.isForeground = false;
4283         r.mFgsNotificationWasDeferred = false;
4284         dropFgsNotificationStateLocked(r);
4285         r.foregroundId = 0;
4286         r.foregroundNoti = null;
4287         resetFgsRestrictionLocked(r);
4288 
4289         // Clear start entries.
4290         r.clearDeliveredStartsLocked();
4291         r.pendingStarts.clear();
4292         smap.mDelayedStartList.remove(r);
4293 
4294         if (r.app != null) {
4295             mAm.mBatteryStatsService.noteServiceStopLaunch(r.appInfo.uid, r.name.getPackageName(),
4296                     r.name.getClassName());
4297             stopServiceAndUpdateAllowlistManagerLocked(r);
4298             if (r.app.getThread() != null) {
4299                 // Bump the process to the top of LRU list
4300                 mAm.updateLruProcessLocked(r.app, false, null);
4301                 updateServiceForegroundLocked(r.app.mServices, false);
4302                 try {
4303                     oomAdjusted |= bumpServiceExecutingLocked(r, false, "destroy",
4304                             oomAdjusted ? null : OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4305                     mDestroyingServices.add(r);
4306                     r.destroying = true;
4307                     r.app.getThread().scheduleStopService(r);
4308                 } catch (Exception e) {
4309                     Slog.w(TAG, "Exception when destroying service "
4310                             + r.shortInstanceName, e);
4311                     serviceProcessGoneLocked(r, enqueueOomAdj);
4312                 }
4313             } else {
4314                 if (DEBUG_SERVICE) Slog.v(
4315                     TAG_SERVICE, "Removed service that has no process: " + r);
4316             }
4317         } else {
4318             if (DEBUG_SERVICE) Slog.v(
4319                 TAG_SERVICE, "Removed service that is not running: " + r);
4320         }
4321 
4322         if (!oomAdjusted) {
4323             mAm.enqueueOomAdjTargetLocked(r.app);
4324             if (!enqueueOomAdj) {
4325                 mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4326             }
4327         }
4328         if (r.bindings.size() > 0) {
4329             r.bindings.clear();
4330         }
4331 
4332         if (r.restarter instanceof ServiceRestarter) {
4333            ((ServiceRestarter)r.restarter).setService(null);
4334         }
4335 
4336         synchronized (mAm.mProcessStats.mLock) {
4337             final int memFactor = mAm.mProcessStats.getMemFactorLocked();
4338             if (r.tracker != null) {
4339                 r.tracker.setStarted(false, memFactor, now);
4340                 r.tracker.setBound(false, memFactor, now);
4341                 if (r.executeNesting == 0) {
4342                     r.tracker.clearCurrentOwner(r, false);
4343                     r.tracker = null;
4344                 }
4345             }
4346         }
4347 
4348         smap.ensureNotStartingBackgroundLocked(r);
4349     }
4350 
dropFgsNotificationStateLocked(ServiceRecord r)4351     private void dropFgsNotificationStateLocked(ServiceRecord r) {
4352         if (r.foregroundNoti == null) {
4353             return;
4354         }
4355 
4356         // If this is the only FGS using this notification, clear its FGS flag
4357         boolean shared = false;
4358         final ServiceMap smap = mServiceMap.get(r.userId);
4359         if (smap != null) {
4360             // Is any other FGS using this notification?
4361             final int numServices = smap.mServicesByInstanceName.size();
4362             for (int i = 0; i < numServices; i++) {
4363                 final ServiceRecord sr = smap.mServicesByInstanceName.valueAt(i);
4364                 if (sr == r) {
4365                     continue;
4366                 }
4367                 if (sr.isForeground
4368                         && r.foregroundId == sr.foregroundId
4369                         && r.appInfo.packageName.equals(sr.appInfo.packageName)) {
4370                     shared = true;
4371                     break;
4372                 }
4373             }
4374         } else {
4375             Slog.wtf(TAG, "FGS " + r + " not found!");
4376         }
4377 
4378         // No other FGS is sharing this notification, so we're done with it
4379         if (!shared) {
4380             r.stripForegroundServiceFlagFromNotification();
4381         }
4382     }
4383 
removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp, ActivityServiceConnectionsHolder skipAct, boolean enqueueOomAdj)4384     void removeConnectionLocked(ConnectionRecord c, ProcessRecord skipApp,
4385             ActivityServiceConnectionsHolder skipAct, boolean enqueueOomAdj) {
4386         IBinder binder = c.conn.asBinder();
4387         AppBindRecord b = c.binding;
4388         ServiceRecord s = b.service;
4389         ArrayList<ConnectionRecord> clist = s.getConnections().get(binder);
4390         if (clist != null) {
4391             clist.remove(c);
4392             if (clist.size() == 0) {
4393                 s.removeConnection(binder);
4394             }
4395         }
4396         b.connections.remove(c);
4397         c.stopAssociation();
4398         if (c.activity != null && c.activity != skipAct) {
4399             c.activity.removeConnection(c);
4400         }
4401         if (b.client != skipApp) {
4402             final ProcessServiceRecord psr = b.client.mServices;
4403             psr.removeConnection(c);
4404             if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
4405                 psr.updateHasAboveClientLocked();
4406             }
4407             // If this connection requested allowlist management, see if we should
4408             // now clear that state.
4409             if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
4410                 s.updateAllowlistManager();
4411                 if (!s.allowlistManager && s.app != null) {
4412                     updateAllowlistManagerLocked(s.app.mServices);
4413                 }
4414             }
4415             // And do the same for bg activity starts ability.
4416             if ((c.flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
4417                 s.updateIsAllowedBgActivityStartsByBinding();
4418             }
4419             if (s.app != null) {
4420                 updateServiceClientActivitiesLocked(s.app.mServices, c, true);
4421             }
4422         }
4423         clist = mServiceConnections.get(binder);
4424         if (clist != null) {
4425             clist.remove(c);
4426             if (clist.size() == 0) {
4427                 mServiceConnections.remove(binder);
4428             }
4429         }
4430 
4431         mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid,
4432                 s.appInfo.longVersionCode, s.instanceName, s.processName);
4433 
4434         if (b.connections.size() == 0) {
4435             b.intent.apps.remove(b.client);
4436         }
4437 
4438         if (!c.serviceDead) {
4439             if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
4440                     + ": shouldUnbind=" + b.intent.hasBound);
4441             if (s.app != null && s.app.getThread() != null && b.intent.apps.size() == 0
4442                     && b.intent.hasBound) {
4443                 try {
4444                     bumpServiceExecutingLocked(s, false, "unbind",
4445                             OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4446                     if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
4447                             && s.app.mState.getSetProcState() <= PROCESS_STATE_HEAVY_WEIGHT) {
4448                         // If this service's process is not already in the cached list,
4449                         // then update it in the LRU list here because this may be causing
4450                         // it to go down there and we want it to start out near the top.
4451                         mAm.updateLruProcessLocked(s.app, false, null);
4452                     }
4453                     b.intent.hasBound = false;
4454                     // Assume the client doesn't want to know about a rebind;
4455                     // we will deal with that later if it asks for one.
4456                     b.intent.doRebind = false;
4457                     s.app.getThread().scheduleUnbindService(s, b.intent.intent.getIntent());
4458                 } catch (Exception e) {
4459                     Slog.w(TAG, "Exception when unbinding service " + s.shortInstanceName, e);
4460                     serviceProcessGoneLocked(s, enqueueOomAdj);
4461                 }
4462             }
4463 
4464             // If unbound while waiting to start and there is no connection left in this service,
4465             // remove the pending service
4466             if (s.getConnections().isEmpty()) {
4467                 mPendingServices.remove(s);
4468                 mPendingBringups.remove(s);
4469             }
4470 
4471             if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
4472                 boolean hasAutoCreate = s.hasAutoCreateConnections();
4473                 if (!hasAutoCreate) {
4474                     if (s.tracker != null) {
4475                         synchronized (mAm.mProcessStats.mLock) {
4476                             s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
4477                                     SystemClock.uptimeMillis());
4478                         }
4479                     }
4480                 }
4481                 bringDownServiceIfNeededLocked(s, true, hasAutoCreate, enqueueOomAdj);
4482             }
4483         }
4484     }
4485 
serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res, boolean enqueueOomAdj)4486     void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res,
4487             boolean enqueueOomAdj) {
4488         boolean inDestroying = mDestroyingServices.contains(r);
4489         if (r != null) {
4490             if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
4491                 // This is a call from a service start...  take care of
4492                 // book-keeping.
4493                 r.callStart = true;
4494                 switch (res) {
4495                     case Service.START_STICKY_COMPATIBILITY:
4496                     case Service.START_STICKY: {
4497                         // We are done with the associated start arguments.
4498                         r.findDeliveredStart(startId, false, true);
4499                         // Don't stop if killed.
4500                         r.stopIfKilled = false;
4501                         break;
4502                     }
4503                     case Service.START_NOT_STICKY: {
4504                         // We are done with the associated start arguments.
4505                         r.findDeliveredStart(startId, false, true);
4506                         if (r.getLastStartId() == startId) {
4507                             // There is no more work, and this service
4508                             // doesn't want to hang around if killed.
4509                             r.stopIfKilled = true;
4510                         }
4511                         break;
4512                     }
4513                     case Service.START_REDELIVER_INTENT: {
4514                         // We'll keep this item until they explicitly
4515                         // call stop for it, but keep track of the fact
4516                         // that it was delivered.
4517                         ServiceRecord.StartItem si = r.findDeliveredStart(startId, false, false);
4518                         if (si != null) {
4519                             si.deliveryCount = 0;
4520                             si.doneExecutingCount++;
4521                             // Don't stop if killed.
4522                             r.stopIfKilled = true;
4523                         }
4524                         break;
4525                     }
4526                     case Service.START_TASK_REMOVED_COMPLETE: {
4527                         // Special processing for onTaskRemoved().  Don't
4528                         // impact normal onStartCommand() processing.
4529                         r.findDeliveredStart(startId, true, true);
4530                         break;
4531                     }
4532                     default:
4533                         throw new IllegalArgumentException(
4534                                 "Unknown service start result: " + res);
4535                 }
4536                 if (res == Service.START_STICKY_COMPATIBILITY) {
4537                     r.callStart = false;
4538                 }
4539             } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
4540                 // This is the final call from destroying the service...  we should
4541                 // actually be getting rid of the service at this point.  Do some
4542                 // validation of its state, and ensure it will be fully removed.
4543                 if (!inDestroying) {
4544                     // Not sure what else to do with this...  if it is not actually in the
4545                     // destroying list, we don't need to make sure to remove it from it.
4546                     // If the app is null, then it was probably removed because the process died,
4547                     // otherwise wtf
4548                     if (r.app != null) {
4549                         Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
4550                                 + r + ", app=" + r.app);
4551                     }
4552                 } else if (r.executeNesting != 1) {
4553                     Slog.w(TAG, "Service done with onDestroy, but executeNesting="
4554                             + r.executeNesting + ": " + r);
4555                     // Fake it to keep from ANR due to orphaned entry.
4556                     r.executeNesting = 1;
4557                 }
4558             }
4559             final long origId = Binder.clearCallingIdentity();
4560             serviceDoneExecutingLocked(r, inDestroying, inDestroying, enqueueOomAdj);
4561             Binder.restoreCallingIdentity(origId);
4562         } else {
4563             Slog.w(TAG, "Done executing unknown service from pid "
4564                     + Binder.getCallingPid());
4565         }
4566     }
4567 
serviceProcessGoneLocked(ServiceRecord r, boolean enqueueOomAdj)4568     private void serviceProcessGoneLocked(ServiceRecord r, boolean enqueueOomAdj) {
4569         if (r.tracker != null) {
4570             synchronized (mAm.mProcessStats.mLock) {
4571                 final int memFactor = mAm.mProcessStats.getMemFactorLocked();
4572                 final long now = SystemClock.uptimeMillis();
4573                 r.tracker.setExecuting(false, memFactor, now);
4574                 r.tracker.setForeground(false, memFactor, now);
4575                 r.tracker.setBound(false, memFactor, now);
4576                 r.tracker.setStarted(false, memFactor, now);
4577             }
4578         }
4579         serviceDoneExecutingLocked(r, true, true, enqueueOomAdj);
4580     }
4581 
serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, boolean finishing, boolean enqueueOomAdj)4582     private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
4583             boolean finishing, boolean enqueueOomAdj) {
4584         if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
4585                 + ": nesting=" + r.executeNesting
4586                 + ", inDestroying=" + inDestroying + ", app=" + r.app);
4587         else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
4588                 "<<< DONE EXECUTING " + r.shortInstanceName);
4589         r.executeNesting--;
4590         if (r.executeNesting <= 0) {
4591             if (r.app != null) {
4592                 final ProcessServiceRecord psr = r.app.mServices;
4593                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
4594                         "Nesting at 0 of " + r.shortInstanceName);
4595                 psr.setExecServicesFg(false);
4596                 psr.stopExecutingService(r);
4597                 if (psr.numberOfExecutingServices() == 0) {
4598                     if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
4599                             "No more executingServices of " + r.shortInstanceName);
4600                     mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
4601                 } else if (r.executeFg) {
4602                     // Need to re-evaluate whether the app still needs to be in the foreground.
4603                     for (int i = psr.numberOfExecutingServices() - 1; i >= 0; i--) {
4604                         if (psr.getExecutingServiceAt(i).executeFg) {
4605                             psr.setExecServicesFg(true);
4606                             break;
4607                         }
4608                     }
4609                 }
4610                 if (inDestroying) {
4611                     if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
4612                             "doneExecuting remove destroying " + r);
4613                     mDestroyingServices.remove(r);
4614                     r.bindings.clear();
4615                 }
4616                 if (enqueueOomAdj) {
4617                     mAm.enqueueOomAdjTargetLocked(r.app);
4618                 } else {
4619                     mAm.updateOomAdjLocked(r.app, OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4620                 }
4621             }
4622             r.executeFg = false;
4623             if (r.tracker != null) {
4624                 synchronized (mAm.mProcessStats.mLock) {
4625                     final int memFactor = mAm.mProcessStats.getMemFactorLocked();
4626                     final long now = SystemClock.uptimeMillis();
4627                     r.tracker.setExecuting(false, memFactor, now);
4628                     r.tracker.setForeground(false, memFactor, now);
4629                     if (finishing) {
4630                         r.tracker.clearCurrentOwner(r, false);
4631                         r.tracker = null;
4632                     }
4633                 }
4634             }
4635             if (finishing) {
4636                 if (r.app != null && !r.app.isPersistent()) {
4637                     stopServiceAndUpdateAllowlistManagerLocked(r);
4638                 }
4639                 r.setProcess(null, null, 0, null);
4640             }
4641         }
4642     }
4643 
attachApplicationLocked(ProcessRecord proc, String processName)4644     boolean attachApplicationLocked(ProcessRecord proc, String processName)
4645             throws RemoteException {
4646         boolean didSomething = false;
4647         // Collect any services that are waiting for this process to come up.
4648         if (mPendingServices.size() > 0) {
4649             ServiceRecord sr = null;
4650             try {
4651                 for (int i=0; i<mPendingServices.size(); i++) {
4652                     sr = mPendingServices.get(i);
4653                     if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
4654                             || !processName.equals(sr.processName))) {
4655                         continue;
4656                     }
4657 
4658                     final IApplicationThread thread = proc.getThread();
4659                     final int pid = proc.getPid();
4660                     final UidRecord uidRecord = proc.getUidRecord();
4661                     mPendingServices.remove(i);
4662                     i--;
4663                     proc.addPackage(sr.appInfo.packageName, sr.appInfo.longVersionCode,
4664                             mAm.mProcessStats);
4665                     realStartServiceLocked(sr, proc, thread, pid, uidRecord, sr.createdFromFg,
4666                             true);
4667                     didSomething = true;
4668                     if (!isServiceNeededLocked(sr, false, false)) {
4669                         // We were waiting for this service to start, but it is actually no
4670                         // longer needed.  This could happen because bringDownServiceIfNeeded
4671                         // won't bring down a service that is pending...  so now the pending
4672                         // is done, so let's drop it.
4673                         bringDownServiceLocked(sr, true);
4674                     }
4675                     /* Will be a no-op if nothing pending */
4676                     mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_START_SERVICE);
4677                 }
4678             } catch (RemoteException e) {
4679                 Slog.w(TAG, "Exception in new application when starting service "
4680                         + sr.shortInstanceName, e);
4681                 throw e;
4682             }
4683         }
4684         // Also, if there are any services that are waiting to restart and
4685         // would run in this process, now is a good time to start them.  It would
4686         // be weird to bring up the process but arbitrarily not let the services
4687         // run at this point just because their restart time hasn't come up.
4688         if (mRestartingServices.size() > 0) {
4689             ServiceRecord sr;
4690             for (int i=0; i<mRestartingServices.size(); i++) {
4691                 sr = mRestartingServices.get(i);
4692                 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
4693                         || !processName.equals(sr.processName))) {
4694                     continue;
4695                 }
4696                 mAm.mHandler.removeCallbacks(sr.restarter);
4697                 mAm.mHandler.post(sr.restarter);
4698             }
4699         }
4700         return didSomething;
4701     }
4702 
processStartTimedOutLocked(ProcessRecord proc)4703     void processStartTimedOutLocked(ProcessRecord proc) {
4704         boolean needOomAdj = false;
4705         for (int i = 0, size = mPendingServices.size(); i < size; i++) {
4706             ServiceRecord sr = mPendingServices.get(i);
4707             if ((proc.uid == sr.appInfo.uid
4708                     && proc.processName.equals(sr.processName))
4709                     || sr.isolatedProc == proc) {
4710                 Slog.w(TAG, "Forcing bringing down service: " + sr);
4711                 sr.isolatedProc = null;
4712                 mPendingServices.remove(i);
4713                 size = mPendingServices.size();
4714                 i--;
4715                 needOomAdj = true;
4716                 bringDownServiceLocked(sr, true);
4717             }
4718         }
4719         if (needOomAdj) {
4720             mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4721         }
4722     }
4723 
collectPackageServicesLocked(String packageName, Set<String> filterByClasses, boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services)4724     private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
4725             boolean evenPersistent, boolean doit, ArrayMap<ComponentName, ServiceRecord> services) {
4726         boolean didSomething = false;
4727         for (int i = services.size() - 1; i >= 0; i--) {
4728             ServiceRecord service = services.valueAt(i);
4729             final boolean sameComponent = packageName == null
4730                     || (service.packageName.equals(packageName)
4731                         && (filterByClasses == null
4732                             || filterByClasses.contains(service.name.getClassName())));
4733             if (sameComponent
4734                     && (service.app == null || evenPersistent || !service.app.isPersistent())) {
4735                 if (!doit) {
4736                     return true;
4737                 }
4738                 didSomething = true;
4739                 Slog.i(TAG, "  Force stopping service " + service);
4740                 if (service.app != null && !service.app.isPersistent()) {
4741                     stopServiceAndUpdateAllowlistManagerLocked(service);
4742                 }
4743                 service.setProcess(null, null, 0, null);
4744                 service.isolatedProc = null;
4745                 if (mTmpCollectionResults == null) {
4746                     mTmpCollectionResults = new ArrayList<>();
4747                 }
4748                 mTmpCollectionResults.add(service);
4749             }
4750         }
4751         return didSomething;
4752     }
4753 
bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, int userId, boolean evenPersistent, boolean doit)4754     boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
4755             int userId, boolean evenPersistent, boolean doit) {
4756         boolean didSomething = false;
4757 
4758         if (mTmpCollectionResults != null) {
4759             mTmpCollectionResults.clear();
4760         }
4761 
4762         if (userId == UserHandle.USER_ALL) {
4763             for (int i = mServiceMap.size() - 1; i >= 0; i--) {
4764                 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
4765                         evenPersistent, doit, mServiceMap.valueAt(i).mServicesByInstanceName);
4766                 if (!doit && didSomething) {
4767                     return true;
4768                 }
4769                 if (doit && filterByClasses == null) {
4770                     forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
4771                 }
4772             }
4773         } else {
4774             ServiceMap smap = mServiceMap.get(userId);
4775             if (smap != null) {
4776                 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByInstanceName;
4777                 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
4778                         evenPersistent, doit, items);
4779             }
4780             if (doit && filterByClasses == null) {
4781                 forceStopPackageLocked(packageName, userId);
4782             }
4783         }
4784 
4785         if (mTmpCollectionResults != null) {
4786             final int size = mTmpCollectionResults.size();
4787             for (int i = size - 1; i >= 0; i--) {
4788                 bringDownServiceLocked(mTmpCollectionResults.get(i), true);
4789             }
4790             if (size > 0) {
4791                 mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4792             }
4793             mTmpCollectionResults.clear();
4794         }
4795 
4796         return didSomething;
4797     }
4798 
forceStopPackageLocked(String packageName, int userId)4799     void forceStopPackageLocked(String packageName, int userId) {
4800         ServiceMap smap = mServiceMap.get(userId);
4801         if (smap != null && smap.mActiveForegroundApps.size() > 0) {
4802             for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
4803                 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
4804                 if (aa.mPackageName.equals(packageName)) {
4805                     smap.mActiveForegroundApps.removeAt(i);
4806                     smap.mActiveForegroundAppsChanged = true;
4807                 }
4808             }
4809             if (smap.mActiveForegroundAppsChanged) {
4810                 requestUpdateActiveForegroundAppsLocked(smap, 0);
4811             }
4812         }
4813         for (int i = mPendingBringups.size() - 1; i >= 0; i--) {
4814             ServiceRecord r = mPendingBringups.keyAt(i);
4815             if (TextUtils.equals(r.packageName, packageName) && r.userId == userId) {
4816                 mPendingBringups.removeAt(i);
4817             }
4818         }
4819         removeServiceRestartBackoffEnabledLocked(packageName);
4820         removeServiceNotificationDeferralsLocked(packageName, userId);
4821     }
4822 
cleanUpServices(int userId, ComponentName component, Intent baseIntent)4823     void cleanUpServices(int userId, ComponentName component, Intent baseIntent) {
4824         ArrayList<ServiceRecord> services = new ArrayList<>();
4825         ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
4826         for (int i = alls.size() - 1; i >= 0; i--) {
4827             ServiceRecord sr = alls.valueAt(i);
4828             if (sr.packageName.equals(component.getPackageName())) {
4829                 services.add(sr);
4830             }
4831         }
4832 
4833         // Take care of any running services associated with the app.
4834         boolean needOomAdj = false;
4835         for (int i = services.size() - 1; i >= 0; i--) {
4836             ServiceRecord sr = services.get(i);
4837             if (sr.startRequested) {
4838                 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
4839                     Slog.i(TAG, "Stopping service " + sr.shortInstanceName + ": remove task");
4840                     needOomAdj = true;
4841                     stopServiceLocked(sr, true);
4842                 } else {
4843                     sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
4844                             sr.getLastStartId(), baseIntent, null, 0));
4845                     if (sr.app != null && sr.app.getThread() != null) {
4846                         // We always run in the foreground, since this is called as
4847                         // part of the "remove task" UI operation.
4848                         try {
4849                             sendServiceArgsLocked(sr, true, false);
4850                         } catch (TransactionTooLargeException e) {
4851                             // Ignore, keep going.
4852                         }
4853                     }
4854                 }
4855             }
4856         }
4857         if (needOomAdj) {
4858             mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
4859         }
4860     }
4861 
killServicesLocked(ProcessRecord app, boolean allowRestart)4862     final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
4863         final ProcessServiceRecord psr = app.mServices;
4864         // Report disconnected services.
4865         if (false) {
4866             // XXX we are letting the client link to the service for
4867             // death notifications.
4868             int numberOfRunningServices = psr.numberOfRunningServices();
4869             for (int sIndex = 0; sIndex < numberOfRunningServices; sIndex++) {
4870                 ServiceRecord r = psr.getRunningServiceAt(sIndex);
4871                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
4872                 for (int conni = connections.size() - 1; conni >= 0; conni--) {
4873                     ArrayList<ConnectionRecord> cl = connections.valueAt(conni);
4874                     for (int i = 0; i < cl.size(); i++) {
4875                         ConnectionRecord c = cl.get(i);
4876                         if (c.binding.client != app) {
4877                             try {
4878                                 //c.conn.connected(r.className, null);
4879                             } catch (Exception e) {
4880                                 // todo: this should be asynchronous!
4881                                 Slog.w(TAG, "Exception thrown disconnected servce "
4882                                         + r.shortInstanceName
4883                                         + " from app " + app.processName, e);
4884                             }
4885                         }
4886                     }
4887                 }
4888             }
4889         }
4890 
4891         // Clean up any connections this application has to other services.
4892         for (int i = psr.numberOfConnections() - 1; i >= 0; i--) {
4893             ConnectionRecord r = psr.getConnectionAt(i);
4894             removeConnectionLocked(r, app, null, true);
4895         }
4896         updateServiceConnectionActivitiesLocked(psr);
4897         psr.removeAllConnections();
4898 
4899         psr.mAllowlistManager = false;
4900 
4901         // Clear app state from services.
4902         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
4903             ServiceRecord sr = psr.getRunningServiceAt(i);
4904             mAm.mBatteryStatsService.noteServiceStopLaunch(sr.appInfo.uid, sr.name.getPackageName(),
4905                     sr.name.getClassName());
4906             if (sr.app != app && sr.app != null && !sr.app.isPersistent()) {
4907                 sr.app.mServices.stopService(sr);
4908                 sr.app.mServices.updateBoundClientUids();
4909             }
4910             sr.setProcess(null, null, 0, null);
4911             sr.isolatedProc = null;
4912             sr.executeNesting = 0;
4913             sr.forceClearTracker();
4914             if (mDestroyingServices.remove(sr)) {
4915                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
4916             }
4917 
4918             final int numClients = sr.bindings.size();
4919             for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
4920                 IntentBindRecord b = sr.bindings.valueAt(bindingi);
4921                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
4922                         + ": shouldUnbind=" + b.hasBound);
4923                 b.binder = null;
4924                 b.requested = b.received = b.hasBound = false;
4925                 // If this binding is coming from a cached process and is asking to keep
4926                 // the service created, then we'll kill the cached process as well -- we
4927                 // don't want to be thrashing around restarting processes that are only
4928                 // there to be cached.
4929                 for (int appi=b.apps.size()-1; appi>=0; appi--) {
4930                     final ProcessRecord proc = b.apps.keyAt(appi);
4931                     // If the process is already gone, skip it.
4932                     if (proc.isKilledByAm() || proc.getThread() == null) {
4933                         continue;
4934                     }
4935                     // Only do this for processes that have an auto-create binding;
4936                     // otherwise the binding can be left, because it won't cause the
4937                     // service to restart.
4938                     final AppBindRecord abind = b.apps.valueAt(appi);
4939                     boolean hasCreate = false;
4940                     for (int conni = abind.connections.size() - 1; conni >= 0; conni--) {
4941                         ConnectionRecord conn = abind.connections.valueAt(conni);
4942                         if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
4943                                 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
4944                             hasCreate = true;
4945                             break;
4946                         }
4947                     }
4948                     if (!hasCreate) {
4949                         continue;
4950                     }
4951                     // XXX turned off for now until we have more time to get a better policy.
4952                     /*
4953                     if (false && proc != null && !proc.isPersistent() && proc.getThread() != null
4954                             && proc.getPid() != 0 && proc.getPid() != ActivityManagerService.MY_PID
4955                             && proc.mState.getSetProcState() >= PROCESS_STATE_LAST_ACTIVITY) {
4956                         proc.killLocked("bound to service " + sr.shortInstanceName
4957                                 + " in dying proc " + (app != null ? app.processName : "??"),
4958                                 ApplicationExitInfo.REASON_OTHER, true);
4959                     }
4960                     */
4961                 }
4962             }
4963         }
4964 
4965         ServiceMap smap = getServiceMapLocked(app.userId);
4966 
4967         // Now do remaining service cleanup.
4968         for (int i = psr.numberOfRunningServices() - 1; i >= 0; i--) {
4969             ServiceRecord sr = psr.getRunningServiceAt(i);
4970 
4971             // Unless the process is persistent, this process record is going away,
4972             // so make sure the service is cleaned out of it.
4973             if (!app.isPersistent()) {
4974                 psr.stopService(sr);
4975                 psr.updateBoundClientUids();
4976             }
4977 
4978             // Sanity check: if the service listed for the app is not one
4979             // we actually are maintaining, just let it drop.
4980             final ServiceRecord curRec = smap.mServicesByInstanceName.get(sr.instanceName);
4981             if (curRec != sr) {
4982                 if (curRec != null) {
4983                     Slog.wtf(TAG, "Service " + sr + " in process " + app
4984                             + " not same as in map: " + curRec);
4985                 }
4986                 continue;
4987             }
4988 
4989             // Any services running in the application may need to be placed
4990             // back in the pending list.
4991             if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
4992                     && (sr.serviceInfo.applicationInfo.flags
4993                         &ApplicationInfo.FLAG_PERSISTENT) == 0) {
4994                 Slog.w(TAG, "Service crashed " + sr.crashCount
4995                         + " times, stopping: " + sr);
4996                 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
4997                         sr.userId, sr.crashCount, sr.shortInstanceName,
4998                         sr.app != null ? sr.app.getPid() : -1);
4999                 bringDownServiceLocked(sr, true);
5000             } else if (!allowRestart
5001                     || !mAm.mUserController.isUserRunning(sr.userId, 0)) {
5002                 bringDownServiceLocked(sr, true);
5003             } else {
5004                 final boolean scheduled = scheduleServiceRestartLocked(sr, true /* allowCancel */);
5005 
5006                 // Should the service remain running?  Note that in the
5007                 // extreme case of so many attempts to deliver a command
5008                 // that it failed we also will stop it here.
5009                 if (!scheduled) {
5010                     bringDownServiceLocked(sr, true);
5011                 } else if (sr.canStopIfKilled(false /* isStartCanceled */)) {
5012                     // Update to stopped state because the explicit start is gone. The service is
5013                     // scheduled to restart for other reason (e.g. connections) so we don't bring
5014                     // down it.
5015                     sr.startRequested = false;
5016                     if (sr.tracker != null) {
5017                         synchronized (mAm.mProcessStats.mLock) {
5018                             sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
5019                                     SystemClock.uptimeMillis());
5020                         }
5021                     }
5022                 }
5023             }
5024         }
5025 
5026         mAm.updateOomAdjPendingTargetsLocked(OomAdjuster.OOM_ADJ_REASON_UNBIND_SERVICE);
5027 
5028         if (!allowRestart) {
5029             psr.stopAllServices();
5030             psr.clearBoundClientUids();
5031 
5032             // Make sure there are no more restarting services for this process.
5033             for (int i=mRestartingServices.size()-1; i>=0; i--) {
5034                 ServiceRecord r = mRestartingServices.get(i);
5035                 if (r.processName.equals(app.processName) &&
5036                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
5037                     mRestartingServices.remove(i);
5038                     clearRestartingIfNeededLocked(r);
5039                 }
5040             }
5041             for (int i=mPendingServices.size()-1; i>=0; i--) {
5042                 ServiceRecord r = mPendingServices.get(i);
5043                 if (r.processName.equals(app.processName) &&
5044                         r.serviceInfo.applicationInfo.uid == app.info.uid) {
5045                     mPendingServices.remove(i);
5046                 }
5047             }
5048             for (int i = mPendingBringups.size() - 1; i >= 0; i--) {
5049                 ServiceRecord r = mPendingBringups.keyAt(i);
5050                 if (r.processName.equals(app.processName)
5051                         && r.serviceInfo.applicationInfo.uid == app.info.uid) {
5052                     mPendingBringups.removeAt(i);
5053                 }
5054             }
5055         }
5056 
5057         // Make sure we have no more records on the stopping list.
5058         int i = mDestroyingServices.size();
5059         while (i > 0) {
5060             i--;
5061             ServiceRecord sr = mDestroyingServices.get(i);
5062             if (sr.app == app) {
5063                 sr.forceClearTracker();
5064                 mDestroyingServices.remove(i);
5065                 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
5066             }
5067         }
5068 
5069         psr.stopAllExecutingServices();
5070     }
5071 
makeRunningServiceInfoLocked(ServiceRecord r)5072     ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
5073         ActivityManager.RunningServiceInfo info =
5074             new ActivityManager.RunningServiceInfo();
5075         info.service = r.name;
5076         if (r.app != null) {
5077             info.pid = r.app.getPid();
5078         }
5079         info.uid = r.appInfo.uid;
5080         info.process = r.processName;
5081         info.foreground = r.isForeground;
5082         info.activeSince = r.createRealTime;
5083         info.started = r.startRequested;
5084         info.clientCount = r.getConnections().size();
5085         info.crashCount = r.crashCount;
5086         info.lastActivityTime = r.lastActivity;
5087         if (r.isForeground) {
5088             info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
5089         }
5090         if (r.startRequested) {
5091             info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
5092         }
5093         if (r.app != null && r.app.getPid() == ActivityManagerService.MY_PID) {
5094             info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
5095         }
5096         if (r.app != null && r.app.isPersistent()) {
5097             info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
5098         }
5099 
5100         ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
5101         for (int conni = connections.size() - 1; conni >= 0; conni--) {
5102             ArrayList<ConnectionRecord> connl = connections.valueAt(conni);
5103             for (int i=0; i<connl.size(); i++) {
5104                 ConnectionRecord conn = connl.get(i);
5105                 if (conn.clientLabel != 0) {
5106                     info.clientPackage = conn.binding.client.info.packageName;
5107                     info.clientLabel = conn.clientLabel;
5108                     return info;
5109                 }
5110             }
5111         }
5112         return info;
5113     }
5114 
getRunningServiceInfoLocked(int maxNum, int flags, int callingUid, boolean allowed, boolean canInteractAcrossUsers)5115     List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
5116         int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
5117         ArrayList<ActivityManager.RunningServiceInfo> res
5118                 = new ArrayList<ActivityManager.RunningServiceInfo>();
5119 
5120         final long ident = Binder.clearCallingIdentity();
5121         try {
5122             if (canInteractAcrossUsers) {
5123                 int[] users = mAm.mUserController.getUsers();
5124                 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
5125                     ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
5126                     for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
5127                         ServiceRecord sr = alls.valueAt(i);
5128                         res.add(makeRunningServiceInfoLocked(sr));
5129                     }
5130                 }
5131 
5132                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
5133                     ServiceRecord r = mRestartingServices.get(i);
5134                     ActivityManager.RunningServiceInfo info =
5135                             makeRunningServiceInfoLocked(r);
5136                     info.restarting = r.nextRestartTime;
5137                     res.add(info);
5138                 }
5139             } else {
5140                 int userId = UserHandle.getUserId(callingUid);
5141                 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
5142                 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
5143                     ServiceRecord sr = alls.valueAt(i);
5144 
5145                     if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
5146                         res.add(makeRunningServiceInfoLocked(sr));
5147                     }
5148                 }
5149 
5150                 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
5151                     ServiceRecord r = mRestartingServices.get(i);
5152                     if (r.userId == userId
5153                         && (allowed || (r.app != null && r.app.uid == callingUid))) {
5154                         ActivityManager.RunningServiceInfo info =
5155                                 makeRunningServiceInfoLocked(r);
5156                         info.restarting = r.nextRestartTime;
5157                         res.add(info);
5158                     }
5159                 }
5160             }
5161         } finally {
5162             Binder.restoreCallingIdentity(ident);
5163         }
5164 
5165         return res;
5166     }
5167 
getRunningServiceControlPanelLocked(ComponentName name)5168     public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
5169         int userId = UserHandle.getUserId(Binder.getCallingUid());
5170         ServiceRecord r = getServiceByNameLocked(name, userId);
5171         if (r != null) {
5172             ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
5173             for (int conni = connections.size() - 1; conni >= 0; conni--) {
5174                 ArrayList<ConnectionRecord> conn = connections.valueAt(conni);
5175                 for (int i=0; i<conn.size(); i++) {
5176                     if (conn.get(i).clientIntent != null) {
5177                         return conn.get(i).clientIntent;
5178                     }
5179                 }
5180             }
5181         }
5182         return null;
5183     }
5184 
serviceTimeout(ProcessRecord proc)5185     void serviceTimeout(ProcessRecord proc) {
5186         String anrMessage = null;
5187         synchronized(mAm) {
5188             if (proc.isDebugging()) {
5189                 // The app's being debugged, ignore timeout.
5190                 return;
5191             }
5192             final ProcessServiceRecord psr = proc.mServices;
5193             if (psr.numberOfExecutingServices() == 0 || proc.getThread() == null) {
5194                 return;
5195             }
5196             final long now = SystemClock.uptimeMillis();
5197             final long maxTime =  now -
5198                     (psr.shouldExecServicesFg() ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
5199             ServiceRecord timeout = null;
5200             long nextTime = 0;
5201             for (int i = psr.numberOfExecutingServices() - 1; i >= 0; i--) {
5202                 ServiceRecord sr = psr.getExecutingServiceAt(i);
5203                 if (sr.executingStart < maxTime) {
5204                     timeout = sr;
5205                     break;
5206                 }
5207                 if (sr.executingStart > nextTime) {
5208                     nextTime = sr.executingStart;
5209                 }
5210             }
5211             if (timeout != null && mAm.mProcessList.isInLruListLOSP(proc)) {
5212                 Slog.w(TAG, "Timeout executing service: " + timeout);
5213                 StringWriter sw = new StringWriter();
5214                 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
5215                 pw.println(timeout);
5216                 timeout.dump(pw, "    ");
5217                 pw.close();
5218                 mLastAnrDump = sw.toString();
5219                 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
5220                 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
5221                 anrMessage = "executing service " + timeout.shortInstanceName;
5222             } else {
5223                 Message msg = mAm.mHandler.obtainMessage(
5224                         ActivityManagerService.SERVICE_TIMEOUT_MSG);
5225                 msg.obj = proc;
5226                 mAm.mHandler.sendMessageAtTime(msg, psr.shouldExecServicesFg()
5227                         ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
5228             }
5229         }
5230 
5231         if (anrMessage != null) {
5232             mAm.mAnrHelper.appNotResponding(proc, anrMessage);
5233         }
5234     }
5235 
serviceForegroundTimeout(ServiceRecord r)5236     void serviceForegroundTimeout(ServiceRecord r) {
5237         ProcessRecord app;
5238         synchronized (mAm) {
5239             if (!r.fgRequired || r.destroying) {
5240                 return;
5241             }
5242 
5243             app = r.app;
5244             if (app != null && app.isDebugging()) {
5245                 // The app's being debugged; let it ride
5246                 return;
5247             }
5248 
5249             if (DEBUG_BACKGROUND_CHECK) {
5250                 Slog.i(TAG, "Service foreground-required timeout for " + r);
5251             }
5252             r.fgWaiting = false;
5253             stopServiceLocked(r, false);
5254         }
5255 
5256         if (app != null) {
5257             mAm.mAnrHelper.appNotResponding(app,
5258                     "Context.startForegroundService() did not then call Service.startForeground(): "
5259                         + r);
5260         }
5261     }
5262 
updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo)5263     public void updateServiceApplicationInfoLocked(ApplicationInfo applicationInfo) {
5264         final int userId = UserHandle.getUserId(applicationInfo.uid);
5265         ServiceMap serviceMap = mServiceMap.get(userId);
5266         if (serviceMap != null) {
5267             ArrayMap<ComponentName, ServiceRecord> servicesByName
5268                     = serviceMap.mServicesByInstanceName;
5269             for (int j = servicesByName.size() - 1; j >= 0; j--) {
5270                 ServiceRecord serviceRecord = servicesByName.valueAt(j);
5271                 if (applicationInfo.packageName.equals(serviceRecord.appInfo.packageName)) {
5272                     serviceRecord.appInfo = applicationInfo;
5273                     serviceRecord.serviceInfo.applicationInfo = applicationInfo;
5274                 }
5275             }
5276         }
5277     }
5278 
serviceForegroundCrash(ProcessRecord app, String serviceRecord, ComponentName service)5279     void serviceForegroundCrash(ProcessRecord app, String serviceRecord,
5280             ComponentName service) {
5281         mAm.crashApplicationWithTypeWithExtras(
5282                 app.uid, app.getPid(), app.info.packageName, app.userId,
5283                 "Context.startForegroundService() did not then call Service.startForeground(): "
5284                     + serviceRecord, false /*force*/,
5285                 ForegroundServiceDidNotStartInTimeException.TYPE_ID,
5286                 ForegroundServiceDidNotStartInTimeException.createExtrasForService(service));
5287     }
5288 
scheduleServiceTimeoutLocked(ProcessRecord proc)5289     void scheduleServiceTimeoutLocked(ProcessRecord proc) {
5290         if (proc.mServices.numberOfExecutingServices() == 0 || proc.getThread() == null) {
5291             return;
5292         }
5293         Message msg = mAm.mHandler.obtainMessage(
5294                 ActivityManagerService.SERVICE_TIMEOUT_MSG);
5295         msg.obj = proc;
5296         mAm.mHandler.sendMessageDelayed(msg, proc.mServices.shouldExecServicesFg()
5297                 ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
5298     }
5299 
scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r)5300     void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
5301         if (r.app.mServices.numberOfExecutingServices() == 0 || r.app.getThread() == null) {
5302             return;
5303         }
5304         Message msg = mAm.mHandler.obtainMessage(
5305                 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
5306         msg.obj = r;
5307         r.fgWaiting = true;
5308         mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
5309     }
5310 
5311     final class ServiceDumper {
5312         private final FileDescriptor fd;
5313         private final PrintWriter pw;
5314         private final String[] args;
5315         private final boolean dumpAll;
5316         private final String dumpPackage;
5317         private final ItemMatcher matcher;
5318         private final ArrayList<ServiceRecord> services = new ArrayList<>();
5319 
5320         private final long nowReal = SystemClock.elapsedRealtime();
5321 
5322         private boolean needSep = false;
5323         private boolean printedAnything = false;
5324         private boolean printed = false;
5325 
5326         /**
5327          * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
5328          * must be called with the lock held).
5329          */
ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)5330         ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
5331                 int opti, boolean dumpAll, String dumpPackage) {
5332             this.fd = fd;
5333             this.pw = pw;
5334             this.args = args;
5335             this.dumpAll = dumpAll;
5336             this.dumpPackage = dumpPackage;
5337             matcher = new ItemMatcher();
5338             matcher.build(args, opti);
5339 
5340             final int[] users = mAm.mUserController.getUsers();
5341             for (int user : users) {
5342                 ServiceMap smap = getServiceMapLocked(user);
5343                 if (smap.mServicesByInstanceName.size() > 0) {
5344                     for (int si=0; si<smap.mServicesByInstanceName.size(); si++) {
5345                         ServiceRecord r = smap.mServicesByInstanceName.valueAt(si);
5346                         if (!matcher.match(r, r.name)) {
5347                             continue;
5348                         }
5349                         if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
5350                             continue;
5351                         }
5352                         services.add(r);
5353                     }
5354                 }
5355             }
5356         }
5357 
dumpHeaderLocked()5358         private void dumpHeaderLocked() {
5359             pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
5360             if (mLastAnrDump != null) {
5361                 pw.println("  Last ANR service:");
5362                 pw.print(mLastAnrDump);
5363                 pw.println();
5364             }
5365         }
5366 
dumpLocked()5367         void dumpLocked() {
5368             dumpHeaderLocked();
5369 
5370             try {
5371                 int[] users = mAm.mUserController.getUsers();
5372                 for (int user : users) {
5373                     // Find the first service for this user.
5374                     int serviceIdx = 0;
5375                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
5376                         serviceIdx++;
5377                     }
5378                     printed = false;
5379                     if (serviceIdx < services.size()) {
5380                         needSep = false;
5381                         while (serviceIdx < services.size()) {
5382                             ServiceRecord r = services.get(serviceIdx);
5383                             serviceIdx++;
5384                             if (r.userId != user) {
5385                                 break;
5386                             }
5387                             dumpServiceLocalLocked(r);
5388                         }
5389                         needSep |= printed;
5390                     }
5391 
5392                     dumpUserRemainsLocked(user);
5393                 }
5394             } catch (Exception e) {
5395                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
5396             }
5397 
5398             dumpRemainsLocked();
5399         }
5400 
dumpWithClient()5401         void dumpWithClient() {
5402             synchronized(mAm) {
5403                 dumpHeaderLocked();
5404             }
5405 
5406             try {
5407                 int[] users = mAm.mUserController.getUsers();
5408                 for (int user : users) {
5409                     // Find the first service for this user.
5410                     int serviceIdx = 0;
5411                     while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
5412                         serviceIdx++;
5413                     }
5414                     printed = false;
5415                     if (serviceIdx < services.size()) {
5416                         needSep = false;
5417                         while (serviceIdx < services.size()) {
5418                             ServiceRecord r = services.get(serviceIdx);
5419                             serviceIdx++;
5420                             if (r.userId != user) {
5421                                 break;
5422                             }
5423                             synchronized(mAm) {
5424                                 dumpServiceLocalLocked(r);
5425                             }
5426                             dumpServiceClient(r);
5427                         }
5428                         needSep |= printed;
5429                     }
5430 
5431                     synchronized(mAm) {
5432                         dumpUserRemainsLocked(user);
5433                     }
5434                 }
5435             } catch (Exception e) {
5436                 Slog.w(TAG, "Exception in dumpServicesLocked", e);
5437             }
5438 
5439             synchronized(mAm) {
5440                 dumpRemainsLocked();
5441             }
5442         }
5443 
dumpUserHeaderLocked(int user)5444         private void dumpUserHeaderLocked(int user) {
5445             if (!printed) {
5446                 if (printedAnything) {
5447                     pw.println();
5448                 }
5449                 pw.println("  User " + user + " active services:");
5450                 printed = true;
5451             }
5452             printedAnything = true;
5453             if (needSep) {
5454                 pw.println();
5455             }
5456         }
5457 
dumpServiceLocalLocked(ServiceRecord r)5458         private void dumpServiceLocalLocked(ServiceRecord r) {
5459             dumpUserHeaderLocked(r.userId);
5460             pw.print("  * ");
5461             pw.println(r);
5462             if (dumpAll) {
5463                 r.dump(pw, "    ");
5464                 needSep = true;
5465             } else {
5466                 pw.print("    app=");
5467                 pw.println(r.app);
5468                 pw.print("    created=");
5469                 TimeUtils.formatDuration(r.createRealTime, nowReal, pw);
5470                 pw.print(" started=");
5471                 pw.print(r.startRequested);
5472                 pw.print(" connections=");
5473                 ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections = r.getConnections();
5474                 pw.println(connections.size());
5475                 if (connections.size() > 0) {
5476                     pw.println("    Connections:");
5477                     for (int conni = 0; conni < connections.size(); conni++) {
5478                         ArrayList<ConnectionRecord> clist = connections.valueAt(conni);
5479                         for (int i = 0; i < clist.size(); i++) {
5480                             ConnectionRecord conn = clist.get(i);
5481                             pw.print("      ");
5482                             pw.print(conn.binding.intent.intent.getIntent()
5483                                     .toShortString(false, false, false, false));
5484                             pw.print(" -> ");
5485                             ProcessRecord proc = conn.binding.client;
5486                             pw.println(proc != null ? proc.toShortString() : "null");
5487                         }
5488                     }
5489                 }
5490             }
5491         }
5492 
dumpServiceClient(ServiceRecord r)5493         private void dumpServiceClient(ServiceRecord r) {
5494             final ProcessRecord proc = r.app;
5495             if (proc == null) {
5496                 return;
5497             }
5498             final IApplicationThread thread = proc.getThread();
5499             if (thread == null) {
5500                 return;
5501             }
5502             pw.println("    Client:");
5503             pw.flush();
5504             try {
5505                 TransferPipe tp = new TransferPipe();
5506                 try {
5507                     thread.dumpService(tp.getWriteFd(), r, args);
5508                     tp.setBufferPrefix("      ");
5509                     // Short timeout, since blocking here can
5510                     // deadlock with the application.
5511                     tp.go(fd, 2000);
5512                 } finally {
5513                     tp.kill();
5514                 }
5515             } catch (IOException e) {
5516                 pw.println("      Failure while dumping the service: " + e);
5517             } catch (RemoteException e) {
5518                 pw.println("      Got a RemoteException while dumping the service");
5519             }
5520             needSep = true;
5521         }
5522 
dumpUserRemainsLocked(int user)5523         private void dumpUserRemainsLocked(int user) {
5524             ServiceMap smap = getServiceMapLocked(user);
5525             printed = false;
5526             for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
5527                 ServiceRecord r = smap.mDelayedStartList.get(si);
5528                 if (!matcher.match(r, r.name)) {
5529                     continue;
5530                 }
5531                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
5532                     continue;
5533                 }
5534                 if (!printed) {
5535                     if (printedAnything) {
5536                         pw.println();
5537                     }
5538                     pw.println("  User " + user + " delayed start services:");
5539                     printed = true;
5540                 }
5541                 printedAnything = true;
5542                 pw.print("  * Delayed start "); pw.println(r);
5543             }
5544             printed = false;
5545             for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
5546                 ServiceRecord r = smap.mStartingBackground.get(si);
5547                 if (!matcher.match(r, r.name)) {
5548                     continue;
5549                 }
5550                 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
5551                     continue;
5552                 }
5553                 if (!printed) {
5554                     if (printedAnything) {
5555                         pw.println();
5556                     }
5557                     pw.println("  User " + user + " starting in background:");
5558                     printed = true;
5559                 }
5560                 printedAnything = true;
5561                 pw.print("  * Starting bg "); pw.println(r);
5562             }
5563         }
5564 
dumpRemainsLocked()5565         private void dumpRemainsLocked() {
5566             if (mPendingServices.size() > 0) {
5567                 printed = false;
5568                 for (int i=0; i<mPendingServices.size(); i++) {
5569                     ServiceRecord r = mPendingServices.get(i);
5570                     if (!matcher.match(r, r.name)) {
5571                         continue;
5572                     }
5573                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
5574                         continue;
5575                     }
5576                     printedAnything = true;
5577                     if (!printed) {
5578                         if (needSep) pw.println();
5579                         needSep = true;
5580                         pw.println("  Pending services:");
5581                         printed = true;
5582                     }
5583                     pw.print("  * Pending "); pw.println(r);
5584                     r.dump(pw, "    ");
5585                 }
5586                 needSep = true;
5587             }
5588 
5589             if (mRestartingServices.size() > 0) {
5590                 printed = false;
5591                 for (int i=0; i<mRestartingServices.size(); i++) {
5592                     ServiceRecord r = mRestartingServices.get(i);
5593                     if (!matcher.match(r, r.name)) {
5594                         continue;
5595                     }
5596                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
5597                         continue;
5598                     }
5599                     printedAnything = true;
5600                     if (!printed) {
5601                         if (needSep) pw.println();
5602                         needSep = true;
5603                         pw.println("  Restarting services:");
5604                         printed = true;
5605                     }
5606                     pw.print("  * Restarting "); pw.println(r);
5607                     r.dump(pw, "    ");
5608                 }
5609                 needSep = true;
5610             }
5611 
5612             if (mDestroyingServices.size() > 0) {
5613                 printed = false;
5614                 for (int i=0; i< mDestroyingServices.size(); i++) {
5615                     ServiceRecord r = mDestroyingServices.get(i);
5616                     if (!matcher.match(r, r.name)) {
5617                         continue;
5618                     }
5619                     if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
5620                         continue;
5621                     }
5622                     printedAnything = true;
5623                     if (!printed) {
5624                         if (needSep) pw.println();
5625                         needSep = true;
5626                         pw.println("  Destroying services:");
5627                         printed = true;
5628                     }
5629                     pw.print("  * Destroy "); pw.println(r);
5630                     r.dump(pw, "    ");
5631                 }
5632                 needSep = true;
5633             }
5634 
5635             if (dumpAll) {
5636                 printed = false;
5637                 for (int ic=0; ic<mServiceConnections.size(); ic++) {
5638                     ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
5639                     for (int i=0; i<r.size(); i++) {
5640                         ConnectionRecord cr = r.get(i);
5641                         if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
5642                             continue;
5643                         }
5644                         if (dumpPackage != null && (cr.binding.client == null
5645                                 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
5646                             continue;
5647                         }
5648                         printedAnything = true;
5649                         if (!printed) {
5650                             if (needSep) pw.println();
5651                             needSep = true;
5652                             pw.println("  Connection bindings to services:");
5653                             printed = true;
5654                         }
5655                         pw.print("  * "); pw.println(cr);
5656                         cr.dump(pw, "    ");
5657                     }
5658                 }
5659             }
5660 
5661             if (matcher.all) {
5662                 final long nowElapsed = SystemClock.elapsedRealtime();
5663                 final int[] users = mAm.mUserController.getUsers();
5664                 for (int user : users) {
5665                     boolean printedUser = false;
5666                     ServiceMap smap = mServiceMap.get(user);
5667                     if (smap == null) {
5668                         continue;
5669                     }
5670                     for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
5671                         ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
5672                         if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
5673                             continue;
5674                         }
5675                         if (!printedUser) {
5676                             printedUser = true;
5677                             printedAnything = true;
5678                             if (needSep) pw.println();
5679                             needSep = true;
5680                             pw.print("Active foreground apps - user ");
5681                             pw.print(user);
5682                             pw.println(":");
5683                         }
5684                         pw.print("  #");
5685                         pw.print(i);
5686                         pw.print(": ");
5687                         pw.println(aa.mPackageName);
5688                         if (aa.mLabel != null) {
5689                             pw.print("    mLabel=");
5690                             pw.println(aa.mLabel);
5691                         }
5692                         pw.print("    mNumActive=");
5693                         pw.print(aa.mNumActive);
5694                         pw.print(" mAppOnTop=");
5695                         pw.print(aa.mAppOnTop);
5696                         pw.print(" mShownWhileTop=");
5697                         pw.print(aa.mShownWhileTop);
5698                         pw.print(" mShownWhileScreenOn=");
5699                         pw.println(aa.mShownWhileScreenOn);
5700                         pw.print("    mStartTime=");
5701                         TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
5702                         pw.print(" mStartVisibleTime=");
5703                         TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
5704                         pw.println();
5705                         if (aa.mEndTime != 0) {
5706                             pw.print("    mEndTime=");
5707                             TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
5708                             pw.println();
5709                         }
5710                     }
5711                     if (smap.hasMessagesOrCallbacks()) {
5712                         if (needSep) {
5713                             pw.println();
5714                         }
5715                         printedAnything = true;
5716                         needSep = true;
5717                         pw.print("  Handler - user ");
5718                         pw.print(user);
5719                         pw.println(":");
5720                         smap.dumpMine(new PrintWriterPrinter(pw), "    ");
5721                     }
5722                 }
5723             }
5724 
5725             if (!printedAnything) {
5726                 pw.println("  (nothing)");
5727             }
5728         }
5729     }
5730 
newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)5731     ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
5732             int opti, boolean dumpAll, String dumpPackage) {
5733         return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
5734     }
5735 
dumpDebug(ProtoOutputStream proto, long fieldId)5736     protected void dumpDebug(ProtoOutputStream proto, long fieldId) {
5737         synchronized (mAm) {
5738             final long outterToken = proto.start(fieldId);
5739             int[] users = mAm.mUserController.getUsers();
5740             for (int user : users) {
5741                 ServiceMap smap = mServiceMap.get(user);
5742                 if (smap == null) {
5743                     continue;
5744                 }
5745                 long token = proto.start(ActiveServicesProto.SERVICES_BY_USERS);
5746                 proto.write(ActiveServicesProto.ServicesByUser.USER_ID, user);
5747                 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
5748                 for (int i=0; i<alls.size(); i++) {
5749                     alls.valueAt(i).dumpDebug(proto,
5750                             ActiveServicesProto.ServicesByUser.SERVICE_RECORDS);
5751                 }
5752                 proto.end(token);
5753             }
5754             proto.end(outterToken);
5755         }
5756     }
5757 
5758     /**
5759      * There are three ways to call this:
5760      *  - no service specified: dump all the services
5761      *  - a flattened component name that matched an existing service was specified as the
5762      *    first arg: dump that one service
5763      *  - the first arg isn't the flattened component name of an existing service:
5764      *    dump all services whose component contains the first arg as a substring
5765      */
dumpService(FileDescriptor fd, PrintWriter pw, String name, int[] users, String[] args, int opti, boolean dumpAll)5766     protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, int[] users,
5767             String[] args, int opti, boolean dumpAll) {
5768         final ArrayList<ServiceRecord> services = new ArrayList<>();
5769 
5770         final Predicate<ServiceRecord> filter = DumpUtils.filterRecord(name);
5771 
5772         synchronized (mAm) {
5773             if (users == null) {
5774                 users = mAm.mUserController.getUsers();
5775             }
5776 
5777             for (int user : users) {
5778                 ServiceMap smap = mServiceMap.get(user);
5779                 if (smap == null) {
5780                     continue;
5781                 }
5782                 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByInstanceName;
5783                 for (int i=0; i<alls.size(); i++) {
5784                     ServiceRecord r1 = alls.valueAt(i);
5785 
5786                     if (filter.test(r1)) {
5787                         services.add(r1);
5788                     }
5789                 }
5790             }
5791         }
5792 
5793         if (services.size() <= 0) {
5794             return false;
5795         }
5796 
5797         // Sort by component name.
5798         services.sort(Comparator.comparing(WithComponentName::getComponentName));
5799 
5800         boolean needSep = false;
5801         for (int i=0; i<services.size(); i++) {
5802             if (needSep) {
5803                 pw.println();
5804             }
5805             needSep = true;
5806             dumpService("", fd, pw, services.get(i), args, dumpAll);
5807         }
5808         return true;
5809     }
5810 
5811     /**
5812      * Invokes IApplicationThread.dumpService() on the thread of the specified service if
5813      * there is a thread associated with the service.
5814      */
dumpService(String prefix, FileDescriptor fd, PrintWriter pw, final ServiceRecord r, String[] args, boolean dumpAll)5815     private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
5816             final ServiceRecord r, String[] args, boolean dumpAll) {
5817         String innerPrefix = prefix + "  ";
5818         synchronized (mAm) {
5819             pw.print(prefix); pw.print("SERVICE ");
5820             pw.print(r.shortInstanceName); pw.print(" ");
5821             pw.print(Integer.toHexString(System.identityHashCode(r)));
5822             pw.print(" pid=");
5823             if (r.app != null) {
5824                 pw.print(r.app.getPid());
5825                 pw.print(" user="); pw.println(r.userId);
5826             } else pw.println("(not running)");
5827             if (dumpAll) {
5828                 r.dump(pw, innerPrefix);
5829             }
5830         }
5831         IApplicationThread thread;
5832         if (r.app != null && (thread = r.app.getThread()) != null) {
5833             pw.print(prefix); pw.println("  Client:");
5834             pw.flush();
5835             try {
5836                 TransferPipe tp = new TransferPipe();
5837                 try {
5838                     thread.dumpService(tp.getWriteFd(), r, args);
5839                     tp.setBufferPrefix(prefix + "    ");
5840                     tp.go(fd);
5841                 } finally {
5842                     tp.kill();
5843                 }
5844             } catch (IOException e) {
5845                 pw.println(prefix + "    Failure while dumping the service: " + e);
5846             } catch (RemoteException e) {
5847                 pw.println(prefix + "    Got a RemoteException while dumping the service");
5848             }
5849         }
5850     }
5851 
5852     /**
5853      * There are two FGS restrictions:
5854      * In R, mAllowWhileInUsePermissionInFgs is to allow while-in-use permissions in foreground
5855      *  service or not. while-in-use permissions in FGS started from background might be restricted.
5856      * In S, mAllowStartForeground is to allow FGS to startForeground or not. Service started
5857      * from background may not become a FGS.
5858      * @param callingPackage caller app's package name.
5859      * @param callingUid caller app's uid.
5860      * @param intent intent to start/bind service.
5861      * @param r the service to start.
5862      * @return true if allow, false otherwise.
5863      */
setFgsRestrictionLocked(String callingPackage, int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId, boolean allowBackgroundActivityStarts)5864     private void setFgsRestrictionLocked(String callingPackage,
5865             int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId,
5866             boolean allowBackgroundActivityStarts) {
5867         r.mLastSetFgsRestrictionTime = SystemClock.elapsedRealtime();
5868         // Check DeviceConfig flag.
5869         if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) {
5870             r.mAllowWhileInUsePermissionInFgs = true;
5871         }
5872 
5873         if (!r.mAllowWhileInUsePermissionInFgs
5874                 || (r.mAllowStartForeground == REASON_DENIED)) {
5875             final @ReasonCode int allowWhileInUse = shouldAllowFgsWhileInUsePermissionLocked(
5876                     callingPackage, callingPid, callingUid, r, allowBackgroundActivityStarts);
5877             if (!r.mAllowWhileInUsePermissionInFgs) {
5878                 r.mAllowWhileInUsePermissionInFgs = (allowWhileInUse != REASON_DENIED);
5879             }
5880             if (r.mAllowStartForeground == REASON_DENIED) {
5881                 r.mAllowStartForeground = shouldAllowFgsStartForegroundLocked(allowWhileInUse,
5882                         callingPackage, callingPid, callingUid, intent, r,
5883                         userId);
5884             }
5885         }
5886     }
5887 
resetFgsRestrictionLocked(ServiceRecord r)5888     void resetFgsRestrictionLocked(ServiceRecord r) {
5889         r.mAllowWhileInUsePermissionInFgs = false;
5890         r.mAllowStartForeground = REASON_DENIED;
5891         r.mInfoAllowStartForeground = null;
5892         r.mInfoTempFgsAllowListReason = null;
5893         r.mLoggedInfoAllowStartForeground = false;
5894         r.mLastSetFgsRestrictionTime = 0;
5895     }
5896 
canStartForegroundServiceLocked(int callingPid, int callingUid, String callingPackage)5897     boolean canStartForegroundServiceLocked(int callingPid, int callingUid, String callingPackage) {
5898         if (!mAm.mConstants.mFlagBackgroundFgsStartRestrictionEnabled) {
5899             return true;
5900         }
5901         final @ReasonCode int allowWhileInUse = shouldAllowFgsWhileInUsePermissionLocked(
5902                 callingPackage, callingPid, callingUid, null /* serviceRecord */,
5903                 false /* allowBackgroundActivityStarts */);
5904         final @ReasonCode int allowStartFgs = shouldAllowFgsStartForegroundLocked(
5905                 allowWhileInUse, callingPid, callingUid, callingPackage, null /* targetService */);
5906         return allowStartFgs != REASON_DENIED;
5907     }
5908 
5909     /**
5910      * Should allow while-in-use permissions in FGS or not.
5911      * A typical BG started FGS is not allowed to have while-in-use permissions.
5912      * @param callingPackage caller app's package name.
5913      * @param callingUid caller app's uid.
5914      * @param targetService the service to start.
5915      * @return {@link ReasonCode}
5916      */
shouldAllowFgsWhileInUsePermissionLocked(String callingPackage, int callingPid, int callingUid, @Nullable ServiceRecord targetService, boolean allowBackgroundActivityStarts)5917     private @ReasonCode int shouldAllowFgsWhileInUsePermissionLocked(String callingPackage,
5918             int callingPid, int callingUid, @Nullable ServiceRecord targetService,
5919             boolean allowBackgroundActivityStarts) {
5920         int ret = REASON_DENIED;
5921 
5922         final int uidState = mAm.getUidStateLocked(callingUid);
5923         if (ret == REASON_DENIED) {
5924             // Is the calling UID at PROCESS_STATE_TOP or above?
5925             if (uidState <= PROCESS_STATE_TOP) {
5926                 ret = getReasonCodeFromProcState(uidState);
5927             }
5928         }
5929 
5930         if (ret == REASON_DENIED) {
5931             // Does the calling UID have any visible activity?
5932             final boolean isCallingUidVisible = mAm.mAtmInternal.isUidForeground(callingUid);
5933             if (isCallingUidVisible) {
5934                 ret = REASON_UID_VISIBLE;
5935             }
5936         }
5937 
5938         if (ret == REASON_DENIED) {
5939             // Is the allow activity background start flag on?
5940             if (allowBackgroundActivityStarts) {
5941                 ret = REASON_START_ACTIVITY_FLAG;
5942             }
5943         }
5944 
5945         if (ret == REASON_DENIED) {
5946             boolean isCallerSystem = false;
5947             final int callingAppId = UserHandle.getAppId(callingUid);
5948             switch (callingAppId) {
5949                 case ROOT_UID:
5950                 case SYSTEM_UID:
5951                 case NFC_UID:
5952                 case SHELL_UID:
5953                     isCallerSystem = true;
5954                     break;
5955                 default:
5956                     isCallerSystem = false;
5957                     break;
5958             }
5959 
5960             if (isCallerSystem) {
5961                 ret = REASON_SYSTEM_UID;
5962             }
5963         }
5964 
5965         if (ret == REASON_DENIED) {
5966             final Integer allowedType = mAm.mProcessList.searchEachLruProcessesLOSP(false, pr -> {
5967                 if (pr.uid == callingUid) {
5968                     if (pr.getWindowProcessController().areBackgroundFgsStartsAllowed()) {
5969                         return REASON_ACTIVITY_STARTER;
5970                     }
5971                 }
5972                 return null;
5973             });
5974             if (allowedType != null) {
5975                 ret = allowedType;
5976             }
5977         }
5978 
5979         if (ret == REASON_DENIED) {
5980             if (mAm.mInternal.isTempAllowlistedForFgsWhileInUse(callingUid)) {
5981                 return REASON_TEMP_ALLOWED_WHILE_IN_USE;
5982             }
5983         }
5984 
5985         if (ret == REASON_DENIED) {
5986             if (targetService != null && targetService.app != null) {
5987                 ActiveInstrumentation instr = targetService.app.getActiveInstrumentation();
5988                 if (instr != null && instr.mHasBackgroundActivityStartsPermission) {
5989                     ret = REASON_INSTR_BACKGROUND_ACTIVITY_PERMISSION;
5990                 }
5991             }
5992         }
5993 
5994         if (ret == REASON_DENIED) {
5995             if (mAm.checkPermission(START_ACTIVITIES_FROM_BACKGROUND, callingPid, callingUid)
5996                     == PERMISSION_GRANTED) {
5997                 ret = REASON_BACKGROUND_ACTIVITY_PERMISSION;
5998             }
5999         }
6000 
6001         if (ret == REASON_DENIED) {
6002             final boolean isAllowedPackage =
6003                     mAllowListWhileInUsePermissionInFgs.contains(callingPackage);
6004             if (isAllowedPackage) {
6005                 ret = REASON_ALLOWLISTED_PACKAGE;
6006             }
6007         }
6008 
6009         if (ret == REASON_DENIED) {
6010             // Is the calling UID a device owner app?
6011             final boolean isDeviceOwner = mAm.mInternal.isDeviceOwner(callingUid);
6012             if (isDeviceOwner) {
6013                 ret = REASON_DEVICE_OWNER;
6014             }
6015         }
6016         return ret;
6017     }
6018 
6019     /**
6020      * Should allow the FGS to start (AKA startForeground()) or not.
6021      * The check in this method is in addition to check in
6022      * {@link #shouldAllowFgsWhileInUsePermissionLocked}
6023      * @param allowWhileInUse the return code from {@link #shouldAllowFgsWhileInUsePermissionLocked}
6024      * @param callingPackage caller app's package name.
6025      * @param callingUid caller app's uid.
6026      * @param intent intent to start/bind service.
6027      * @param r the service to start.
6028      * @return {@link ReasonCode}
6029      */
shouldAllowFgsStartForegroundLocked( @easonCode int allowWhileInUse, String callingPackage, int callingPid, int callingUid, Intent intent, ServiceRecord r, int userId)6030     private @ReasonCode int shouldAllowFgsStartForegroundLocked(
6031             @ReasonCode int allowWhileInUse, String callingPackage, int callingPid,
6032             int callingUid, Intent intent, ServiceRecord r, int userId) {
6033         ActivityManagerService.FgsTempAllowListItem tempAllowListReason =
6034                 r.mInfoTempFgsAllowListReason = mAm.isAllowlistedForFgsStartLOSP(callingUid);
6035         int ret = shouldAllowFgsStartForegroundLocked(allowWhileInUse, callingPid, callingUid,
6036                 callingPackage, r);
6037 
6038         String bindFromPackage = null;
6039         if (ret == REASON_DENIED) {
6040             // If the callingUid is not allowed to start FGS, check if the callingUid has any
6041             // service that is bound by a clientUid, the clientUid can propagate its BG-FGS-start
6042             // capability down to the callingUid.
6043             final ArraySet<Integer> checkedClientUids = new ArraySet<>();
6044             final Pair<Integer, String> isAllowed = mAm.mProcessList.searchEachLruProcessesLOSP(
6045                     false, pr -> {
6046                 if (pr.uid == callingUid) {
6047                     final ProcessServiceRecord psr = pr.mServices;
6048                     final int serviceCount = psr.mServices.size();
6049                     for (int svc = 0; svc < serviceCount; svc++) {
6050                         final ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns =
6051                                 psr.mServices.valueAt(svc).getConnections();
6052                         final int size = conns.size();
6053                         for (int conni = 0; conni < size; conni++) {
6054                             final ArrayList<ConnectionRecord> crs = conns.valueAt(conni);
6055                             for (int con = 0; con < crs.size(); con++) {
6056                                 final ConnectionRecord cr = crs.get(con);
6057                                 final ProcessRecord clientPr = cr.binding.client;
6058                                 // Persistent process does not propagate BG-FGS-start capability
6059                                 // down to service over binding.
6060                                 if (clientPr.mState.getCurProcState()
6061                                         <= PROCESS_STATE_PERSISTENT_UI) {
6062                                     continue;
6063                                 }
6064                                 final int clientPid = clientPr.mPid;
6065                                 final int clientUid = clientPr.uid;
6066                                 // An UID can bind to itself, do not check on itself again.
6067                                 // Also skip already checked clientUid.
6068                                 if (clientUid == callingUid
6069                                         || checkedClientUids.contains(clientUid)) {
6070                                     continue;
6071                                 }
6072                                 final String clientPackageName = cr.clientPackageName;
6073                                 final @ReasonCode int allowWhileInUse2 =
6074                                         shouldAllowFgsWhileInUsePermissionLocked(clientPackageName,
6075                                                 clientPid, clientUid, null /* serviceRecord */,
6076                                                 false /* allowBackgroundActivityStarts */);
6077                                 final @ReasonCode int allowStartFgs =
6078                                         shouldAllowFgsStartForegroundLocked(allowWhileInUse2,
6079                                                 clientPid, clientUid, clientPackageName, null /* targetService */);
6080                                 if (allowStartFgs != REASON_DENIED) {
6081                                     return new Pair<>(allowStartFgs, clientPackageName);
6082                                 } else {
6083                                     checkedClientUids.add(clientUid);
6084                                 }
6085 
6086                             }
6087                         }
6088                     }
6089                 }
6090                 return null;
6091             });
6092             if (isAllowed != null) {
6093                 ret = REASON_FGS_BINDING;
6094                 bindFromPackage = isAllowed.second;
6095             }
6096         }
6097 
6098         final int uidState = mAm.getUidStateLocked(callingUid);
6099         int callerTargetSdkVersion = INVALID_UID;
6100         try {
6101             ApplicationInfo ai = mAm.mContext.getPackageManager().getApplicationInfoAsUser(
6102                     callingPackage, PackageManager.MATCH_KNOWN_PACKAGES, userId);
6103             callerTargetSdkVersion = ai.targetSdkVersion;
6104         } catch (PackageManager.NameNotFoundException e) {
6105         }
6106         final String debugInfo =
6107                 "[callingPackage: " + callingPackage
6108                         + "; callingUid: " + callingUid
6109                         + "; uidState: " + ProcessList.makeProcStateString(uidState)
6110                         + "; intent: " + intent
6111                         + "; code:" + reasonCodeToString(ret)
6112                         + "; tempAllowListReason:<"
6113                         + (tempAllowListReason == null ? null :
6114                                 (tempAllowListReason.mReason
6115                                         + ",reasonCode:"
6116                                         + reasonCodeToString(tempAllowListReason.mReasonCode)
6117                                         + ",duration:" + tempAllowListReason.mDuration
6118                                         + ",callingUid:" + tempAllowListReason.mCallingUid))
6119                         + ">"
6120                         + "; targetSdkVersion:" + r.appInfo.targetSdkVersion
6121                         + "; callerTargetSdkVersion:" + callerTargetSdkVersion
6122                         + "; startForegroundCount:" + r.mStartForegroundCount
6123                         + "; bindFromPackage:" + bindFromPackage
6124                         + "]";
6125         if (!debugInfo.equals(r.mInfoAllowStartForeground)) {
6126             r.mLoggedInfoAllowStartForeground = false;
6127             r.mInfoAllowStartForeground = debugInfo;
6128         }
6129         return ret;
6130     }
6131 
shouldAllowFgsStartForegroundLocked(@easonCode int allowWhileInUse, int callingPid, int callingUid, String callingPackage, @Nullable ServiceRecord targetService)6132     private @ReasonCode int shouldAllowFgsStartForegroundLocked(@ReasonCode int allowWhileInUse,
6133             int callingPid, int callingUid, String callingPackage,
6134             @Nullable ServiceRecord targetService) {
6135         int ret = allowWhileInUse;
6136 
6137         if (ret == REASON_DENIED) {
6138             final int uidState = mAm.getUidStateLocked(callingUid);
6139             // Is the calling UID at PROCESS_STATE_TOP or above?
6140             if (uidState <= PROCESS_STATE_TOP) {
6141                 ret = getReasonCodeFromProcState(uidState);
6142             }
6143         }
6144 
6145         if (ret == REASON_DENIED) {
6146             final Integer allowedType = mAm.mProcessList.searchEachLruProcessesLOSP(false, app -> {
6147                 if (app.uid == callingUid) {
6148                     final ProcessStateRecord state = app.mState;
6149                     if (state.isAllowedStartFgsState()) {
6150                         return getReasonCodeFromProcState(state.getAllowStartFgsState());
6151                     } else {
6152                         final ActiveInstrumentation instr = app.getActiveInstrumentation();
6153                         if (instr != null
6154                                 && instr.mHasBackgroundForegroundServiceStartsPermission) {
6155                             return REASON_INSTR_BACKGROUND_FGS_PERMISSION;
6156                         }
6157                         final long lastInvisibleTime = app.mState.getLastInvisibleTime();
6158                         if (lastInvisibleTime > 0 && lastInvisibleTime < Long.MAX_VALUE) {
6159                             final long sinceLastInvisible = SystemClock.elapsedRealtime()
6160                                     - lastInvisibleTime;
6161                             if (sinceLastInvisible < mAm.mConstants.mFgToBgFgsGraceDuration) {
6162                                 return REASON_ACTIVITY_VISIBILITY_GRACE_PERIOD;
6163                             }
6164                         }
6165                     }
6166                 }
6167                 return null;
6168             });
6169             if (allowedType != null) {
6170                 ret = allowedType;
6171             }
6172         }
6173 
6174         if (ret == REASON_DENIED) {
6175             if (mAm.checkPermission(START_FOREGROUND_SERVICES_FROM_BACKGROUND, callingPid,
6176                     callingUid) == PERMISSION_GRANTED) {
6177                 ret = REASON_BACKGROUND_FGS_PERMISSION;
6178             }
6179         }
6180 
6181         if (ret == REASON_DENIED) {
6182             if (mAm.mAtmInternal.hasSystemAlertWindowPermission(callingUid, callingPid,
6183                     callingPackage)) {
6184                 ret = REASON_SYSTEM_ALERT_WINDOW_PERMISSION;
6185             }
6186         }
6187 
6188         // Check for CDM apps with either REQUEST_COMPANION_RUN_IN_BACKGROUND or
6189         // REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND.
6190         // Note: When a CDM app has REQUEST_COMPANION_RUN_IN_BACKGROUND, the app is also put
6191         // in the user-allowlist. However, in this case, we want to use the reason code
6192         // REASON_COMPANION_DEVICE_MANAGER, so this check needs to be before the
6193         // isAllowlistedForFgsStartLOSP check.
6194         if (ret == REASON_DENIED) {
6195             final boolean isCompanionApp = mAm.mInternal.isAssociatedCompanionApp(
6196                     UserHandle.getUserId(callingUid), callingUid);
6197             if (isCompanionApp) {
6198                 if (isPermissionGranted(
6199                         REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND,
6200                         callingPid, callingUid)
6201                         || isPermissionGranted(REQUEST_COMPANION_RUN_IN_BACKGROUND,
6202                         callingPid, callingUid)) {
6203                     ret = REASON_COMPANION_DEVICE_MANAGER;
6204                 }
6205             }
6206         }
6207 
6208         if (ret == REASON_DENIED) {
6209             ActivityManagerService.FgsTempAllowListItem item =
6210                     mAm.isAllowlistedForFgsStartLOSP(callingUid);
6211             if (item != null) {
6212                 if (item == ActivityManagerService.FAKE_TEMP_ALLOW_LIST_ITEM) {
6213                     ret = REASON_SYSTEM_ALLOW_LISTED;
6214                 } else {
6215                     ret = item.mReasonCode;
6216                 }
6217             }
6218         }
6219 
6220         if (ret == REASON_DENIED) {
6221             if (UserManager.isDeviceInDemoMode(mAm.mContext)) {
6222                 ret = REASON_DEVICE_DEMO_MODE;
6223             }
6224         }
6225 
6226         if (ret == REASON_DENIED) {
6227             // Is the calling UID a profile owner app?
6228             final boolean isProfileOwner = mAm.mInternal.isProfileOwner(callingUid);
6229             if (isProfileOwner) {
6230                 ret = REASON_PROFILE_OWNER;
6231             }
6232         }
6233 
6234         if (ret == REASON_DENIED) {
6235             final AppOpsManager appOpsManager = mAm.getAppOpsManager();
6236             if (appOpsManager.checkOpNoThrow(AppOpsManager.OP_ACTIVATE_VPN, callingUid,
6237                     callingPackage) == AppOpsManager.MODE_ALLOWED) {
6238                 ret = REASON_OP_ACTIVATE_VPN;
6239             } else if (appOpsManager.checkOpNoThrow(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN,
6240                     callingUid, callingPackage) == AppOpsManager.MODE_ALLOWED) {
6241                 ret = REASON_OP_ACTIVATE_PLATFORM_VPN;
6242             }
6243         }
6244 
6245         if (ret == REASON_DENIED) {
6246             final String inputMethod =
6247                     Settings.Secure.getStringForUser(mAm.mContext.getContentResolver(),
6248                             Settings.Secure.DEFAULT_INPUT_METHOD,
6249                             UserHandle.getUserId(callingUid));
6250             if (inputMethod != null) {
6251                 final ComponentName cn = ComponentName.unflattenFromString(inputMethod);
6252                 if (cn != null && cn.getPackageName().equals(callingPackage)) {
6253                     ret = REASON_CURRENT_INPUT_METHOD;
6254                 }
6255             }
6256         }
6257 
6258         if (ret == REASON_DENIED) {
6259             if (mAm.mConstants.mFgsAllowOptOut
6260                     && targetService != null
6261                     && targetService.appInfo.hasRequestForegroundServiceExemption()) {
6262                 ret = REASON_OPT_OUT_REQUESTED;
6263             }
6264         }
6265         return ret;
6266     }
6267 
isPermissionGranted(String permission, int callingPid, int callingUid)6268     private boolean isPermissionGranted(String permission, int callingPid, int callingUid) {
6269         return mAm.checkPermission(permission, callingPid, callingUid) == PERMISSION_GRANTED;
6270     }
6271 
isFgsBgStart(@easonCode int code)6272     private static boolean isFgsBgStart(@ReasonCode int code) {
6273         return code != REASON_PROC_STATE_PERSISTENT
6274                 && code != REASON_PROC_STATE_PERSISTENT_UI
6275                 && code != REASON_PROC_STATE_TOP
6276                 && code != REASON_UID_VISIBLE;
6277     }
6278 
showFgsBgRestrictedNotificationLocked(ServiceRecord r)6279     private void showFgsBgRestrictedNotificationLocked(ServiceRecord r) {
6280         if (!mAm.mConstants.mFgsStartRestrictionNotificationEnabled /* default is false */) {
6281             return;
6282         }
6283         final Context context = mAm.mContext;
6284         final String title = "Foreground Service BG-Launch Restricted";
6285         final String content = "App restricted: " + r.mRecentCallingPackage;
6286         final long now = System.currentTimeMillis();
6287         final String bigText = DATE_FORMATTER.format(now) + " " + r.mInfoAllowStartForeground;
6288         final String groupKey = "com.android.fgs-bg-restricted";
6289         final Notification.Builder n =
6290                 new Notification.Builder(context,
6291                         SystemNotificationChannels.ALERTS)
6292                         .setGroup(groupKey)
6293                         .setSmallIcon(R.drawable.stat_sys_vitals)
6294                         .setWhen(0)
6295                         .setColor(context.getColor(
6296                                 com.android.internal.R.color.system_notification_accent_color))
6297                         .setTicker(title)
6298                         .setContentTitle(title)
6299                         .setContentText(content)
6300                         .setStyle(new Notification.BigTextStyle().bigText(bigText));
6301         context.getSystemService(NotificationManager.class).notifyAsUser(Long.toString(now),
6302                 NOTE_FOREGROUND_SERVICE_BG_LAUNCH, n.build(), UserHandle.ALL);
6303     }
6304 
isBgFgsRestrictionEnabled(ServiceRecord r)6305     private boolean isBgFgsRestrictionEnabled(ServiceRecord r) {
6306         return mAm.mConstants.mFlagFgsStartRestrictionEnabled
6307                 // Checking service's targetSdkVersion.
6308                 && CompatChanges.isChangeEnabled(FGS_BG_START_RESTRICTION_CHANGE_ID, r.appInfo.uid)
6309                 && (!mAm.mConstants.mFgsStartRestrictionCheckCallerTargetSdk
6310                     // Checking callingUid's targetSdkVersion.
6311                     || CompatChanges.isChangeEnabled(
6312                             FGS_BG_START_RESTRICTION_CHANGE_ID, r.mRecentCallingUid));
6313     }
6314 
logFgsBackgroundStart(ServiceRecord r)6315     private void logFgsBackgroundStart(ServiceRecord r) {
6316         // Only log if FGS is started from background.
6317         if (!isFgsBgStart(r.mAllowStartForeground)) {
6318             return;
6319         }
6320         if (!r.mLoggedInfoAllowStartForeground) {
6321             final String msg = "Background started FGS: "
6322                     + ((r.mAllowStartForeground != REASON_DENIED) ? "Allowed " : "Disallowed ")
6323                     + r.mInfoAllowStartForeground;
6324             if (r.mAllowStartForeground != REASON_DENIED) {
6325                 if (ActivityManagerUtils.shouldSamplePackageForAtom(r.packageName,
6326                         mAm.mConstants.mFgsStartAllowedLogSampleRate)) {
6327                     Slog.wtfQuiet(TAG, msg);
6328                 }
6329                 Slog.i(TAG, msg);
6330             } else {
6331                 if (ActivityManagerUtils.shouldSamplePackageForAtom(r.packageName,
6332                         mAm.mConstants.mFgsStartDeniedLogSampleRate)) {
6333                     Slog.wtfQuiet(TAG, msg);
6334                 }
6335                 Slog.w(TAG, msg);
6336             }
6337             r.mLoggedInfoAllowStartForeground = true;
6338         }
6339     }
6340 
6341     /**
6342      * Log the statsd event for FGS.
6343      * @param r ServiceRecord
6344      * @param state one of ENTER/EXIT/DENIED event.
6345      * @param durationMs Only meaningful for EXIT event, the duration from ENTER and EXIT state.
6346      */
logFGSStateChangeLocked(ServiceRecord r, int state, int durationMs)6347     private void logFGSStateChangeLocked(ServiceRecord r, int state, int durationMs) {
6348         if (!ActivityManagerUtils.shouldSamplePackageForAtom(
6349                 r.packageName, mAm.mConstants.mFgsAtomSampleRate)) {
6350             return;
6351         }
6352         boolean allowWhileInUsePermissionInFgs;
6353         @PowerExemptionManager.ReasonCode int fgsStartReasonCode;
6354         if (state == FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__ENTER
6355                 || state == FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED__STATE__EXIT) {
6356             allowWhileInUsePermissionInFgs = r.mAllowWhileInUsePermissionInFgsAtEntering;
6357             fgsStartReasonCode = r.mAllowStartForegroundAtEntering;
6358         } else {
6359             allowWhileInUsePermissionInFgs = r.mAllowWhileInUsePermissionInFgs;
6360             fgsStartReasonCode = r.mAllowStartForeground;
6361         }
6362         FrameworkStatsLog.write(FrameworkStatsLog.FOREGROUND_SERVICE_STATE_CHANGED,
6363                 r.appInfo.uid,
6364                 r.shortInstanceName,
6365                 state,
6366                 allowWhileInUsePermissionInFgs,
6367                 fgsStartReasonCode,
6368                 r.appInfo.targetSdkVersion,
6369                 r.mRecentCallingUid,
6370                 r.mRecentCallerApplicationInfo != null
6371                         ? r.mRecentCallerApplicationInfo.targetSdkVersion : 0,
6372                 r.mInfoTempFgsAllowListReason != null
6373                         ? r.mInfoTempFgsAllowListReason.mCallingUid : INVALID_UID,
6374                 r.mFgsNotificationWasDeferred,
6375                 r.mFgsNotificationShown,
6376                 durationMs,
6377                 r.mStartForegroundCount,
6378                 ActivityManagerUtils.hashComponentNameForAtom(r.shortInstanceName));
6379     }
6380 
canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid, String callingPackage)6381     boolean canAllowWhileInUsePermissionInFgsLocked(int callingPid, int callingUid,
6382             String callingPackage) {
6383         return shouldAllowFgsWhileInUsePermissionLocked(callingPackage, callingPid, callingUid,
6384                 /* targetService */ null,
6385                 /* allowBackgroundActivityStarts */ false)
6386                 != REASON_DENIED;
6387     }
6388 }
6389