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