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