1 /*
2  * Copyright (C) 2006 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.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
20 import static android.app.PendingIntent.FLAG_IMMUTABLE;
21 import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
22 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_BOUND_SERVICE;
23 import static android.os.PowerExemptionManager.REASON_DENIED;
24 import static android.os.PowerExemptionManager.reasonCodeToString;
25 import static android.os.Process.INVALID_UID;
26 
27 import static com.android.internal.util.Preconditions.checkArgument;
28 import static com.android.server.am.ActiveServices.TAG_SERVICE;
29 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE;
30 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
31 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
32 
33 import android.annotation.ElapsedRealtimeLong;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.UptimeMillisLong;
37 import android.app.BackgroundStartPrivileges;
38 import android.app.IApplicationThread;
39 import android.app.Notification;
40 import android.app.PendingIntent;
41 import android.app.RemoteServiceException.CannotPostForegroundServiceNotificationException;
42 import android.app.compat.CompatChanges;
43 import android.compat.annotation.ChangeId;
44 import android.compat.annotation.EnabledAfter;
45 import android.content.ComponentName;
46 import android.content.Context;
47 import android.content.Intent;
48 import android.content.pm.ApplicationInfo;
49 import android.content.pm.PackageManager;
50 import android.content.pm.ServiceInfo;
51 import android.net.Uri;
52 import android.os.Binder;
53 import android.os.Build;
54 import android.os.Build.VERSION_CODES;
55 import android.os.IBinder;
56 import android.os.PowerExemptionManager;
57 import android.os.SystemClock;
58 import android.os.UserHandle;
59 import android.provider.Settings;
60 import android.util.ArrayMap;
61 import android.util.Slog;
62 import android.util.TimeUtils;
63 import android.util.proto.ProtoOutputStream;
64 import android.util.proto.ProtoUtils;
65 
66 import com.android.internal.annotations.GuardedBy;
67 import com.android.internal.app.procstats.ServiceState;
68 import com.android.server.LocalServices;
69 import com.android.server.notification.NotificationManagerInternal;
70 import com.android.server.uri.NeededUriGrants;
71 import com.android.server.uri.UriPermissionOwner;
72 
73 import java.io.PrintWriter;
74 import java.util.ArrayList;
75 import java.util.List;
76 import java.util.Objects;
77 
78 /**
79  * A running application service.
80  */
81 final class ServiceRecord extends Binder implements ComponentName.WithComponentName {
82     private static final String TAG = TAG_WITH_CLASS_NAME ? "ServiceRecord" : TAG_AM;
83 
84     // Maximum number of delivery attempts before giving up.
85     static final int MAX_DELIVERY_COUNT = 3;
86 
87     // Maximum number of times it can fail during execution before giving up.
88     static final int MAX_DONE_EXECUTING_COUNT = 6;
89 
90 
91     // Compat IDs for the new FGS logic. For now, we just disable all of them.
92     // TODO: Enable them at some point, but only for V+ builds.
93 
94     /**
95      * Compat ID to enable the new FGS start logic, for permission calculation used for
96      * per-FGS-type eligibility calculation.
97      * (See also android.app.ForegroundServiceTypePolicy)
98      */
99     @ChangeId
100     @EnabledAfter(targetSdkVersion = VERSION_CODES.UPSIDE_DOWN_CAKE)
101     static final long USE_NEW_WIU_LOGIC_FOR_START = 311208629L;
102 
103     /**
104      * Compat ID to enable the new FGS start logic, for capability calculation.
105      */
106     @ChangeId
107     @EnabledAfter(targetSdkVersion = VERSION_CODES.UPSIDE_DOWN_CAKE)
108     static final long USE_NEW_WIU_LOGIC_FOR_CAPABILITIES = 313677553L;
109 
110     /**
111      * Compat ID to enable the new FGS start logic, for deciding whether to allow FGS start from
112      * the background.
113      */
114     @ChangeId
115     @EnabledAfter(targetSdkVersion = VERSION_CODES.UPSIDE_DOWN_CAKE)
116     static final long USE_NEW_BFSL_LOGIC = 311208749L;
117 
118     final ActivityManagerService ams;
119     final ComponentName name; // service component.
120     final ComponentName instanceName; // service component's per-instance name.
121     final String shortInstanceName; // instanceName.flattenToShortString().
122     final String definingPackageName;
123                             // Can be different from appInfo.packageName for external services
124     final int definingUid;
125                             // Can be different from appInfo.uid for external services
126     final Intent.FilterComparison intent;
127                             // original intent used to find service.
128     final ServiceInfo serviceInfo;
129                             // all information about the service.
130     ApplicationInfo appInfo;
131                             // information about service's app.
132     final int userId;       // user that this service is running as
133     final String packageName; // the package implementing intent's component
134     final String processName; // process where this component wants to run
135     final String permission;// permission needed to access service
136     final boolean exported; // from ServiceInfo.exported
137     final Runnable restarter; // used to schedule retries of starting the service
138     final long createRealTime;  // when this service was created
139     final boolean isSdkSandbox; // whether this is a sdk sandbox service
140     final int sdkSandboxClientAppUid; // the app uid for which this sdk sandbox service is running
141     final String sdkSandboxClientAppPackage; // the app package for which this sdk sandbox service
142                                              // is running
143     final ArrayMap<Intent.FilterComparison, IntentBindRecord> bindings
144             = new ArrayMap<Intent.FilterComparison, IntentBindRecord>();
145                             // All active bindings to the service.
146     private final ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections
147             = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>();
148                             // IBinder -> ConnectionRecord of all bound clients
149 
150     ProcessRecord app;      // where this service is running or null.
151     ProcessRecord isolationHostProc; // process which we've started for this service (used for
152                                      // isolated and sdk sandbox processes)
153     ServiceState tracker; // tracking service execution, may be null
154     ServiceState restartTracker; // tracking service restart
155     boolean allowlistManager; // any bindings to this service have BIND_ALLOW_WHITELIST_MANAGEMENT?
156     boolean delayed;        // are we waiting to start this service in the background?
157     boolean fgRequired;     // is the service required to go foreground after starting?
158     boolean fgWaiting;      // is a timeout for going foreground already scheduled?
159     boolean isNotAppComponentUsage; // is service binding not considered component/package usage?
160     boolean isForeground;   // is service currently in foreground mode?
161     boolean inSharedIsolatedProcess; // is the service in a shared isolated process
162     int foregroundId;       // Notification ID of last foreground req.
163     Notification foregroundNoti; // Notification record of foreground state.
164     long fgDisplayTime;     // time at which the FGS notification should become visible
165     int foregroundServiceType; // foreground service types.
166     long lastActivity;      // last time there was some activity on the service.
167     long startingBgTimeout;  // time at which we scheduled this for a delayed start.
168     boolean startRequested; // someone explicitly called start?
169     boolean delayedStop;    // service has been stopped but is in a delayed start?
170     boolean stopIfKilled;   // last onStart() said to stop if service killed?
171     boolean callStart;      // last onStart() has asked to always be called on restart.
172     int startCommandResult; // last result from onStartCommand(), only for dumpsys.
173     int executeNesting;     // number of outstanding operations keeping foreground.
174     boolean executeFg;      // should we be executing in the foreground?
175     long executingStart;    // start time of last execute request.
176     boolean createdFromFg;  // was this service last created due to a foreground process call?
177     int crashCount;         // number of times proc has crashed with service running
178     int totalRestartCount;  // number of times we have had to restart.
179     int restartCount;       // number of restarts performed in a row.
180     long restartDelay;      // delay until next restart attempt.
181     long restartTime;       // time of last restart.
182     long nextRestartTime;   // time when restartDelay will expire.
183     boolean destroying;     // set when we have started destroying the service
184     long destroyTime;       // time at which destory was initiated.
185     int pendingConnectionGroup;        // To be filled in to ProcessRecord once it connects
186     int pendingConnectionImportance;   // To be filled in to ProcessRecord once it connects
187 
188     /**
189      * The last time (in uptime timebase) a bind request was made with BIND_ALMOST_PERCEPTIBLE for
190      * this service while on TOP.
191      */
192     long lastTopAlmostPerceptibleBindRequestUptimeMs;
193 
194     // any current binding to this service has BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS flag?
195     private boolean mIsAllowedBgActivityStartsByBinding;
196     // used to clean up the state of mIsAllowedBgActivityStartsByStart after a timeout
197     private Runnable mCleanUpAllowBgActivityStartsByStartCallback;
198     private ProcessRecord mAppForAllowingBgActivityStartsByStart;
199     // These are the privileges that currently allow bg activity starts by service start.
200     // Each time the contents of this list change #mBackgroundStartPrivilegesByStartMerged has to
201     // be updated to reflect the merged state. The merged state retains the attribution to the
202     // originating token only if it is the only cause for being privileged.
203     @GuardedBy("ams")
204     private ArrayList<BackgroundStartPrivileges> mBackgroundStartPrivilegesByStart =
205             new ArrayList<>();
206 
207     // merged privileges for mBackgroundStartPrivilegesByStart (for performance)
208     private BackgroundStartPrivileges mBackgroundStartPrivilegesByStartMerged =
209             BackgroundStartPrivileges.NONE;
210 
211     // Reason code for allow while-in-use permissions in foreground service.
212     // If it's not DENIED, while-in-use permissions are allowed.
213     // while-in-use permissions in FGS started from background might be restricted.
214     @PowerExemptionManager.ReasonCode
215     int mAllowWiu_noBinding = REASON_DENIED;
216 
217     // A copy of mAllowWhileInUsePermissionInFgs's value when the service is entering FGS state.
218     boolean mAllowWhileInUsePermissionInFgsAtEntering;
219     /** Allow scheduling user-initiated jobs from the background. */
220     boolean mAllowUiJobScheduling;
221 
222     // the most recent package that start/bind this service.
223     String mRecentCallingPackage;
224     // the most recent uid that start/bind this service.
225     int mRecentCallingUid;
226     // ApplicationInfo of the most recent callingPackage that start/bind this service.
227     @Nullable ApplicationInfo mRecentCallerApplicationInfo;
228 
229     // The uptime when the service enters FGS state.
230     long mFgsEnterTime = 0;
231     // The uptime when the service exits FGS state.
232     long mFgsExitTime = 0;
233     // FGS notification is deferred.
234     boolean mFgsNotificationDeferred;
235     // FGS notification was deferred.
236     boolean mFgsNotificationWasDeferred;
237     // FGS notification was shown before the FGS finishes, or it wasn't deferred in the first place.
238     boolean mFgsNotificationShown;
239     // Whether FGS package has permissions to show notifications.
240     boolean mFgsHasNotificationPermission;
241 
242     // allow the service becomes foreground service? Service started from background may not be
243     // allowed to become a foreground service.
244     @PowerExemptionManager.ReasonCode
245     int mAllowStart_noBinding = REASON_DENIED;
246     // A copy of mAllowStartForeground's value when the service is entering FGS state.
247     @PowerExemptionManager.ReasonCode
248     int mAllowStartForegroundAtEntering = REASON_DENIED;
249     // Debug info why mAllowStartForeground is allowed or denied.
250     String mInfoAllowStartForeground;
251     // Debug info if mAllowStartForeground is allowed because of a temp-allowlist.
252     ActivityManagerService.FgsTempAllowListItem mInfoTempFgsAllowListReason;
253     // Is the same mInfoAllowStartForeground string has been logged before? Used for dedup.
254     boolean mLoggedInfoAllowStartForeground;
255 
256     @PowerExemptionManager.ReasonCode
257     int mAllowWiu_inBindService = REASON_DENIED;
258 
259     @PowerExemptionManager.ReasonCode
260     int mAllowWiu_byBindings = REASON_DENIED;
261 
262     @PowerExemptionManager.ReasonCode
263     int mAllowStart_inBindService = REASON_DENIED;
264 
265     @PowerExemptionManager.ReasonCode
266     int mAllowStart_byBindings = REASON_DENIED;
267 
268     /**
269      * The oom adj seq number snapshot of the host process. We're taking a snapshot
270      * before executing the service. Since we may or may not bump the host process's
271      * proc state / oom adj value before that, at the end of the execution, we could
272      * compare this seq against the current seq of the host process to see if we could
273      * skip the oom adj update from there too.
274      */
275     int mAdjSeq;
276 
277     /**
278      * Whether to use the new "while-in-use permission" logic for FGS start
279      */
useNewWiuLogic_forStart()280     private boolean useNewWiuLogic_forStart() {
281         return Flags.newFgsRestrictionLogic() // This flag should only be set on V+
282                 && CompatChanges.isChangeEnabled(USE_NEW_WIU_LOGIC_FOR_START, appInfo.uid);
283     }
284 
285     /**
286      * Whether to use the new "while-in-use permission" logic for capabilities
287      */
useNewWiuLogic_forCapabilities()288     private boolean useNewWiuLogic_forCapabilities() {
289         return Flags.newFgsRestrictionLogic() // This flag should only be set on V+
290                 && CompatChanges.isChangeEnabled(USE_NEW_WIU_LOGIC_FOR_CAPABILITIES, appInfo.uid);
291     }
292 
293     /**
294      * Whether to use the new "FGS BG start exemption" logic.
295      */
useNewBfslLogic()296     private boolean useNewBfslLogic() {
297         return Flags.newFgsRestrictionLogic() // This flag should only be set on V+
298                 && CompatChanges.isChangeEnabled(USE_NEW_BFSL_LOGIC, appInfo.uid);
299     }
300 
301 
302     @PowerExemptionManager.ReasonCode
getFgsAllowWiu_legacy()303     private int getFgsAllowWiu_legacy() {
304         // In the legacy mode (U-), we use mAllowWiu_inBindService and mAllowWiu_noBinding.
305         return reasonOr(
306                 mAllowWiu_noBinding,
307                 mAllowWiu_inBindService
308         );
309     }
310 
311     @PowerExemptionManager.ReasonCode
getFgsAllowWiu_new()312     private int getFgsAllowWiu_new() {
313         // In the new mode, use by-bindings instead of in-bind-service
314         return reasonOr(
315                 mAllowWiu_noBinding,
316                 mAllowWiu_byBindings
317         );
318     }
319 
320     /**
321      * We use this logic for ForegroundServiceTypePolicy and UIDT eligibility check.
322      */
323     @PowerExemptionManager.ReasonCode
getFgsAllowWiu_forStart()324     int getFgsAllowWiu_forStart() {
325         if (useNewWiuLogic_forStart()) {
326             return getFgsAllowWiu_new();
327         } else {
328             return getFgsAllowWiu_legacy();
329         }
330     }
331 
332     /**
333      * We use this logic for the capability calculation in oom-adjuster.
334      */
335     @PowerExemptionManager.ReasonCode
getFgsAllowWiu_forCapabilities()336     int getFgsAllowWiu_forCapabilities() {
337         if (useNewWiuLogic_forCapabilities()) {
338             return getFgsAllowWiu_new();
339         } else {
340             // If alwaysUseNewLogicForWiuCapabilities() isn't set, just use the same logic as
341             // getFgsAllowWiu_forStart().
342             return getFgsAllowWiu_forStart();
343         }
344     }
345 
346     /**
347      * We use this logic for ForegroundServiceTypePolicy and UIDT eligibility check.
348      */
isFgsAllowedWiu_forStart()349     boolean isFgsAllowedWiu_forStart() {
350         return getFgsAllowWiu_forStart() != REASON_DENIED;
351     }
352 
353     /**
354      * We use this logic for the capability calculation in oom-adjuster.
355      */
isFgsAllowedWiu_forCapabilities()356     boolean isFgsAllowedWiu_forCapabilities() {
357         return getFgsAllowWiu_forCapabilities() != REASON_DENIED;
358     }
359 
360     @PowerExemptionManager.ReasonCode
getFgsAllowStart_legacy()361     private int getFgsAllowStart_legacy() {
362         // This is used for BFSL (background FGS launch) exemption.
363         // Originally -- on U-QPR1 and before -- we only used [in-bind-service] + [no-binding].
364         // This would exclude certain "valid" situations, so in U-QPR2, we started
365         // using [by-bindings] too.
366         return reasonOr(
367                 mAllowStart_noBinding,
368                 mAllowStart_inBindService,
369                 mAllowStart_byBindings
370         );
371     }
372 
373     @PowerExemptionManager.ReasonCode
getFgsAllowStart_new()374     private int getFgsAllowStart_new() {
375         // In the new mode, we don't use [in-bind-service].
376         return reasonOr(
377                 mAllowStart_noBinding,
378                 mAllowStart_byBindings
379         );
380     }
381 
382     /**
383      * Calculate a BFSL exemption code.
384      */
385     @PowerExemptionManager.ReasonCode
getFgsAllowStart()386     int getFgsAllowStart() {
387         if (useNewBfslLogic()) {
388             return getFgsAllowStart_new();
389         } else {
390             return getFgsAllowStart_legacy();
391         }
392     }
393 
394     /**
395      * Return whether BFSL is allowed or not.
396      */
isFgsAllowedStart()397     boolean isFgsAllowedStart() {
398         return getFgsAllowStart() != REASON_DENIED;
399     }
400 
clearFgsAllowWiu()401     void clearFgsAllowWiu() {
402         mAllowWiu_noBinding = REASON_DENIED;
403         mAllowWiu_inBindService = REASON_DENIED;
404         mAllowWiu_byBindings = REASON_DENIED;
405     }
406 
clearFgsAllowStart()407     void clearFgsAllowStart() {
408         mAllowStart_noBinding = REASON_DENIED;
409         mAllowStart_inBindService = REASON_DENIED;
410         mAllowStart_byBindings = REASON_DENIED;
411     }
412 
413     @PowerExemptionManager.ReasonCode
reasonOr( @owerExemptionManager.ReasonCode int first, @PowerExemptionManager.ReasonCode int second)414     static int reasonOr(
415             @PowerExemptionManager.ReasonCode int first,
416             @PowerExemptionManager.ReasonCode int second) {
417         return first != REASON_DENIED ? first : second;
418     }
419 
420     @PowerExemptionManager.ReasonCode
reasonOr( @owerExemptionManager.ReasonCode int first, @PowerExemptionManager.ReasonCode int second, @PowerExemptionManager.ReasonCode int third)421     static int reasonOr(
422             @PowerExemptionManager.ReasonCode int first,
423             @PowerExemptionManager.ReasonCode int second,
424             @PowerExemptionManager.ReasonCode int third) {
425         return first != REASON_DENIED ? first : reasonOr(second, third);
426     }
427 
allowedChanged( @owerExemptionManager.ReasonCode int legacyCode, @PowerExemptionManager.ReasonCode int newCode)428     boolean allowedChanged(
429             @PowerExemptionManager.ReasonCode int legacyCode,
430             @PowerExemptionManager.ReasonCode int newCode) {
431         return (legacyCode == REASON_DENIED) != (newCode == REASON_DENIED);
432     }
433 
getFgsInfoForWtf()434     private String getFgsInfoForWtf() {
435         return " cmp: " + this.getComponentName().toShortString()
436                 + " sdk: " + this.appInfo.targetSdkVersion
437                 ;
438     }
439 
maybeLogFgsLogicChange()440     void maybeLogFgsLogicChange() {
441         final int wiuLegacy = getFgsAllowWiu_legacy();
442         final int wiuNew = getFgsAllowWiu_new();
443 
444         final int startLegacy = getFgsAllowStart_legacy();
445         final int startNew = getFgsAllowStart_new();
446 
447         final boolean wiuChanged = allowedChanged(wiuLegacy, wiuNew);
448         final boolean startChanged = allowedChanged(startLegacy, startNew);
449 
450         if (!wiuChanged && !startChanged) {
451             return;
452         }
453         final String message = "FGS logic changed:"
454                 + (wiuChanged ? " [WIU changed]" : "")
455                 + (startChanged ? " [BFSL changed]" : "")
456                 + " Orig WIU:"
457                 + reasonCodeToString(wiuLegacy)
458                 + " New WIU:"
459                 + reasonCodeToString(wiuNew)
460                 + " Orig BFSL:"
461                 + reasonCodeToString(startLegacy)
462                 + " New BFSL:"
463                 + reasonCodeToString(startNew)
464                 + getFgsInfoForWtf();
465         Slog.wtf(TAG_SERVICE, message);
466     }
467 
468     // The number of times Service.startForeground() is called, after this service record is
469     // created. (i.e. due to "bound" or "start".) It never decreases, even when stopForeground()
470     // is called.
471     int mStartForegroundCount;
472 
473     // This is a service record of a FGS delegate (not a service record of a real service)
474     boolean mIsFgsDelegate;
475     @Nullable ForegroundServiceDelegation mFgsDelegation;
476 
477     String stringName;      // caching of toString
478 
479     private int lastStartId;    // identifier of most recent start request.
480 
481     boolean mKeepWarming; // Whether or not it'll keep critical code path of the host warm
482 
483     /**
484      * The original earliest restart time, which considers the number of crashes, etc.,
485      * but doesn't include the extra delays we put in between to scatter the restarts;
486      * it's the earliest time this auto service restart could happen alone(except those
487      * batch restarts which happens at time of process attach).
488      */
489     long mEarliestRestartTime;
490 
491     /**
492      * The original time when the service start is scheduled, it does NOT include the reschedules.
493      *
494      * <p>The {@link #restartDelay} would be updated when its restart is rescheduled, but this field
495      * won't, so it could be used when dumping how long the restart is delayed actually.</p>
496      */
497     long mRestartSchedulingTime;
498 
499     /**
500      * The snapshot process state when the service is requested (either start or bind).
501      */
502     int mProcessStateOnRequest;
503 
504     static class StartItem {
505         final ServiceRecord sr;
506         final boolean taskRemoved;
507         final int id;
508         final int callingId;
509         final String mCallingProcessName;
510         final Intent intent;
511         final NeededUriGrants neededGrants;
512         final @Nullable String mCallingPackageName;
513         final int mCallingProcessState;
514         long deliveredTime;
515         int deliveryCount;
516         int doneExecutingCount;
517         UriPermissionOwner uriPermissions;
518 
519         String stringName;      // caching of toString
520 
StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent, NeededUriGrants _neededGrants, int _callingId, String callingProcessName, @Nullable String callingPackageName, int callingProcessState)521         StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id,
522                 Intent _intent, NeededUriGrants _neededGrants, int _callingId,
523                 String callingProcessName, @Nullable String callingPackageName,
524                 int callingProcessState) {
525             sr = _sr;
526             taskRemoved = _taskRemoved;
527             id = _id;
528             intent = _intent;
529             neededGrants = _neededGrants;
530             callingId = _callingId;
531             mCallingProcessName = callingProcessName;
532             mCallingPackageName = callingPackageName;
533             mCallingProcessState = callingProcessState;
534         }
535 
getUriPermissionsLocked()536         UriPermissionOwner getUriPermissionsLocked() {
537             if (uriPermissions == null) {
538                 uriPermissions = new UriPermissionOwner(sr.ams.mUgmInternal, this);
539             }
540             return uriPermissions;
541         }
542 
removeUriPermissionsLocked()543         void removeUriPermissionsLocked() {
544             if (uriPermissions != null) {
545                 uriPermissions.removeUriPermissions();
546                 uriPermissions = null;
547             }
548         }
549 
dumpDebug(ProtoOutputStream proto, long fieldId, long now)550         public void dumpDebug(ProtoOutputStream proto, long fieldId, long now) {
551             long token = proto.start(fieldId);
552             proto.write(ServiceRecordProto.StartItem.ID, id);
553             ProtoUtils.toDuration(proto,
554                     ServiceRecordProto.StartItem.DURATION, deliveredTime, now);
555             proto.write(ServiceRecordProto.StartItem.DELIVERY_COUNT, deliveryCount);
556             proto.write(ServiceRecordProto.StartItem.DONE_EXECUTING_COUNT, doneExecutingCount);
557             if (intent != null) {
558                 intent.dumpDebug(proto, ServiceRecordProto.StartItem.INTENT, true, true,
559                         true, false);
560             }
561             if (neededGrants != null) {
562                 neededGrants.dumpDebug(proto, ServiceRecordProto.StartItem.NEEDED_GRANTS);
563             }
564             if (uriPermissions != null) {
565                 uriPermissions.dumpDebug(proto, ServiceRecordProto.StartItem.URI_PERMISSIONS);
566             }
567             proto.end(token);
568         }
569 
toString()570         public String toString() {
571             if (stringName != null) {
572                 return stringName;
573             }
574             StringBuilder sb = new StringBuilder(128);
575             sb.append("ServiceRecord{")
576                 .append(Integer.toHexString(System.identityHashCode(sr)))
577                 .append(' ').append(sr.shortInstanceName)
578                 .append(" StartItem ")
579                 .append(Integer.toHexString(System.identityHashCode(this)))
580                 .append(" id=").append(id).append('}');
581             return stringName = sb.toString();
582         }
583     }
584 
585     final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>();
586                             // start() arguments which been delivered.
587     final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>();
588                             // start() arguments that haven't yet been delivered.
589 
590     /**
591      * Information specific to "SHORT_SERVICE" FGS.
592      */
593     class ShortFgsInfo {
594         /** Time FGS started */
595         private final long mStartTime;
596 
597         /**
598          * Copied from {@link #mStartForegroundCount}. If this is different from the parent's,
599          * that means this instance is stale.
600          */
601         private int mStartForegroundCount;
602 
603         /** Service's "start ID" when this short-service started. */
604         private int mStartId;
605 
ShortFgsInfo(long startTime)606         ShortFgsInfo(long startTime) {
607             mStartTime = startTime;
608             update();
609         }
610 
611         /**
612          * Update {@link #mStartForegroundCount} and {@link #mStartId}.
613          * (but not {@link #mStartTime})
614          */
update()615         public void update() {
616             this.mStartForegroundCount = ServiceRecord.this.mStartForegroundCount;
617             this.mStartId = getLastStartId();
618         }
619 
getStartTime()620         long getStartTime() {
621             return mStartTime;
622         }
623 
getStartForegroundCount()624         int getStartForegroundCount() {
625             return mStartForegroundCount;
626         }
627 
getStartId()628         int getStartId() {
629             return mStartId;
630         }
631 
632         /**
633          * @return whether this {@link ShortFgsInfo} is still "current" or not -- i.e.
634          * it's "start foreground count" is the same as that of the ServiceRecord's.
635          *
636          * Note, we do _not_ check the "start id" here, because the start id increments if the
637          * app calls startService() or startForegroundService() on the same service,
638          * but that will _not_ update the ShortFgsInfo, and will not extend the timeout.
639          */
isCurrent()640         boolean isCurrent() {
641             return this.mStartForegroundCount == ServiceRecord.this.mStartForegroundCount;
642         }
643 
644         /** Time when Service.onTimeout() should be called */
getTimeoutTime()645         long getTimeoutTime() {
646             return mStartTime + ams.mConstants.mShortFgsTimeoutDuration;
647         }
648 
649         /** Time when the procstate should be lowered. */
getProcStateDemoteTime()650         long getProcStateDemoteTime() {
651             return mStartTime + ams.mConstants.mShortFgsTimeoutDuration
652                     + ams.mConstants.mShortFgsProcStateExtraWaitDuration;
653         }
654 
655         /** Time when the app should be declared ANR. */
getAnrTime()656         long getAnrTime() {
657             return mStartTime + ams.mConstants.mShortFgsTimeoutDuration
658                     + ams.mConstants.mShortFgsAnrExtraWaitDuration;
659         }
660 
getDescription()661         String getDescription() {
662             return "sfc=" + this.mStartForegroundCount
663                     + " sid=" + this.mStartId
664                     + " stime=" + this.mStartTime
665                     + " tt=" + this.getTimeoutTime()
666                     + " dt=" + this.getProcStateDemoteTime()
667                     + " at=" + this.getAnrTime();
668         }
669     }
670 
671     /**
672      * Keep track of short-fgs specific information. This field gets cleared when the timeout
673      * stops.
674      */
675     private ShortFgsInfo mShortFgsInfo;
676 
677     /**
678      * Data container class to help track certain fgs info for time-restricted types.
679      */
680     static class TimeLimitedFgsInfo {
681         @UptimeMillisLong
682         private long mFirstFgsStartUptime;
683         // The first fgs start time is maintained here separately in realtime-base
684         // for the 24-hour window reset logic.
685         @ElapsedRealtimeLong
686         private long mFirstFgsStartRealtime;
687         @UptimeMillisLong
688         private long mLastFgsStartTime;
689         @UptimeMillisLong
690         private long mTimeLimitExceededAt = Long.MIN_VALUE;
691         @UptimeMillisLong
692         private long mTotalRuntime = 0;
693         private int mNumParallelServices = 0;
694 
noteFgsFgsStart(@ptimeMillisLong long startTime)695         public void noteFgsFgsStart(@UptimeMillisLong long startTime) {
696             mNumParallelServices++;
697             if (mNumParallelServices == 1) {
698                 mFirstFgsStartUptime = startTime;
699                 mFirstFgsStartRealtime = SystemClock.elapsedRealtime();
700             }
701             mLastFgsStartTime = startTime;
702         }
703 
704         @UptimeMillisLong
getFirstFgsStartUptime()705         public long getFirstFgsStartUptime() {
706             return mFirstFgsStartUptime;
707         }
708 
709         @ElapsedRealtimeLong
getFirstFgsStartRealtime()710         public long getFirstFgsStartRealtime() {
711             return mFirstFgsStartRealtime;
712         }
713 
714         @UptimeMillisLong
getLastFgsStartTime()715         public long getLastFgsStartTime() {
716             return mLastFgsStartTime;
717         }
718 
decNumParallelServices()719         public void decNumParallelServices() {
720             if (mNumParallelServices > 0) {
721                 mNumParallelServices--;
722             }
723             if (mNumParallelServices == 0) {
724                 mLastFgsStartTime = 0;
725             }
726         }
727 
updateTotalRuntime(@ptimeMillisLong long nowUptime)728         public void updateTotalRuntime(@UptimeMillisLong long nowUptime) {
729             mTotalRuntime += nowUptime - mLastFgsStartTime;
730             mLastFgsStartTime = nowUptime;
731         }
732 
733         @UptimeMillisLong
getTotalRuntime()734         public long getTotalRuntime() {
735             return mTotalRuntime;
736         }
737 
setTimeLimitExceededAt(@ptimeMillisLong long timeLimitExceededAt)738         public void setTimeLimitExceededAt(@UptimeMillisLong long timeLimitExceededAt) {
739             mTimeLimitExceededAt = timeLimitExceededAt;
740         }
741 
742         @UptimeMillisLong
getTimeLimitExceededAt()743         public long getTimeLimitExceededAt() {
744             return mTimeLimitExceededAt;
745         }
746 
reset()747         public void reset() {
748             mNumParallelServices = 0;
749             mFirstFgsStartUptime = 0;
750             mFirstFgsStartRealtime = 0;
751             mLastFgsStartTime = 0;
752             mTotalRuntime = 0;
753             mTimeLimitExceededAt = Long.MIN_VALUE;
754         }
755     }
756 
dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now)757     void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) {
758         final int N = list.size();
759         for (int i=0; i<N; i++) {
760             StartItem si = list.get(i);
761             pw.print(prefix); pw.print("#"); pw.print(i);
762                     pw.print(" id="); pw.print(si.id);
763                     if (now != 0) {
764                         pw.print(" dur=");
765                         TimeUtils.formatDuration(si.deliveredTime, now, pw);
766                     }
767                     if (si.deliveryCount != 0) {
768                         pw.print(" dc="); pw.print(si.deliveryCount);
769                     }
770                     if (si.doneExecutingCount != 0) {
771                         pw.print(" dxc="); pw.print(si.doneExecutingCount);
772                     }
773                     pw.println("");
774             pw.print(prefix); pw.print("  intent=");
775                     if (si.intent != null) pw.println(si.intent.toString());
776                     else pw.println("null");
777             if (si.neededGrants != null) {
778                 pw.print(prefix); pw.print("  neededGrants=");
779                         pw.println(si.neededGrants);
780             }
781             if (si.uriPermissions != null) {
782                 si.uriPermissions.dump(pw, prefix);
783             }
784         }
785     }
786 
dumpDebug(ProtoOutputStream proto, long fieldId)787     void dumpDebug(ProtoOutputStream proto, long fieldId) {
788         long token = proto.start(fieldId);
789         proto.write(ServiceRecordProto.SHORT_NAME, this.shortInstanceName);
790         proto.write(ServiceRecordProto.IS_RUNNING, app != null);
791         if (app != null) {
792             proto.write(ServiceRecordProto.PID, app.getPid());
793         }
794         if (intent != null) {
795             intent.getIntent().dumpDebug(proto, ServiceRecordProto.INTENT, false, true, false,
796                     false);
797         }
798         proto.write(ServiceRecordProto.PACKAGE_NAME, packageName);
799         proto.write(ServiceRecordProto.PROCESS_NAME, processName);
800         proto.write(ServiceRecordProto.PERMISSION, permission);
801 
802         long now = SystemClock.uptimeMillis();
803         long nowReal = SystemClock.elapsedRealtime();
804         if (appInfo != null) {
805             long appInfoToken = proto.start(ServiceRecordProto.APPINFO);
806             proto.write(ServiceRecordProto.AppInfo.BASE_DIR, appInfo.sourceDir);
807             if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
808                 proto.write(ServiceRecordProto.AppInfo.RES_DIR, appInfo.publicSourceDir);
809             }
810             proto.write(ServiceRecordProto.AppInfo.DATA_DIR, appInfo.dataDir);
811             proto.write(ServiceRecordProto.AppInfo.TARGET_SDK_VERSION, appInfo.targetSdkVersion);
812             proto.end(appInfoToken);
813         }
814         if (app != null) {
815             app.dumpDebug(proto, ServiceRecordProto.APP);
816         }
817         if (isolationHostProc != null) {
818             isolationHostProc.dumpDebug(proto, ServiceRecordProto.ISOLATED_PROC);
819         }
820         proto.write(ServiceRecordProto.WHITELIST_MANAGER, allowlistManager);
821         proto.write(ServiceRecordProto.DELAYED, delayed);
822         if (isForeground || foregroundId != 0) {
823             long fgToken = proto.start(ServiceRecordProto.FOREGROUND);
824             proto.write(ServiceRecordProto.Foreground.ID, foregroundId);
825             foregroundNoti.dumpDebug(proto, ServiceRecordProto.Foreground.NOTIFICATION);
826             proto.write(ServiceRecordProto.Foreground.FOREGROUND_SERVICE_TYPE,
827                     foregroundServiceType);
828             proto.end(fgToken);
829         }
830         ProtoUtils.toDuration(proto, ServiceRecordProto.CREATE_REAL_TIME, createRealTime, nowReal);
831         ProtoUtils.toDuration(proto,
832                 ServiceRecordProto.STARTING_BG_TIMEOUT, startingBgTimeout, now);
833         ProtoUtils.toDuration(proto, ServiceRecordProto.LAST_ACTIVITY_TIME, lastActivity, now);
834         ProtoUtils.toDuration(proto, ServiceRecordProto.RESTART_TIME, restartTime, now);
835         proto.write(ServiceRecordProto.CREATED_FROM_FG, createdFromFg);
836 
837         // TODO: Log "forStart" too.
838         proto.write(ServiceRecordProto.ALLOW_WHILE_IN_USE_PERMISSION_IN_FGS,
839                 isFgsAllowedWiu_forCapabilities());
840 
841         if (startRequested || delayedStop || lastStartId != 0) {
842             long startToken = proto.start(ServiceRecordProto.START);
843             proto.write(ServiceRecordProto.Start.START_REQUESTED, startRequested);
844             proto.write(ServiceRecordProto.Start.DELAYED_STOP, delayedStop);
845             proto.write(ServiceRecordProto.Start.STOP_IF_KILLED, stopIfKilled);
846             proto.write(ServiceRecordProto.Start.LAST_START_ID, lastStartId);
847             proto.write(ServiceRecordProto.Start.START_COMMAND_RESULT, startCommandResult);
848             proto.end(startToken);
849         }
850 
851         if (executeNesting != 0) {
852             long executNestingToken = proto.start(ServiceRecordProto.EXECUTE);
853             proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_NESTING, executeNesting);
854             proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_FG, executeFg);
855             ProtoUtils.toDuration(proto,
856                     ServiceRecordProto.ExecuteNesting.EXECUTING_START, executingStart, now);
857             proto.end(executNestingToken);
858         }
859         if (destroying || destroyTime != 0) {
860             ProtoUtils.toDuration(proto, ServiceRecordProto.DESTORY_TIME, destroyTime, now);
861         }
862         if (crashCount != 0 || restartCount != 0 || (nextRestartTime - mRestartSchedulingTime) != 0
863                 || nextRestartTime != 0) {
864             long crashToken = proto.start(ServiceRecordProto.CRASH);
865             proto.write(ServiceRecordProto.Crash.RESTART_COUNT, restartCount);
866             ProtoUtils.toDuration(proto, ServiceRecordProto.Crash.RESTART_DELAY,
867                     (nextRestartTime - mRestartSchedulingTime), now);
868             ProtoUtils.toDuration(proto,
869                     ServiceRecordProto.Crash.NEXT_RESTART_TIME, nextRestartTime, now);
870             proto.write(ServiceRecordProto.Crash.CRASH_COUNT, crashCount);
871             proto.end(crashToken);
872         }
873 
874         if (deliveredStarts.size() > 0) {
875             final int N = deliveredStarts.size();
876             for (int i = 0; i < N; i++) {
877                 deliveredStarts.get(i).dumpDebug(proto,
878                         ServiceRecordProto.DELIVERED_STARTS, now);
879             }
880         }
881         if (pendingStarts.size() > 0) {
882             final int N = pendingStarts.size();
883             for (int i = 0; i < N; i++) {
884                 pendingStarts.get(i).dumpDebug(proto, ServiceRecordProto.PENDING_STARTS, now);
885             }
886         }
887         if (bindings.size() > 0) {
888             final int N = bindings.size();
889             for (int i=0; i<N; i++) {
890                 IntentBindRecord b = bindings.valueAt(i);
891                 b.dumpDebug(proto, ServiceRecordProto.BINDINGS);
892             }
893         }
894         if (connections.size() > 0) {
895             final int N = connections.size();
896             for (int conni=0; conni<N; conni++) {
897                 ArrayList<ConnectionRecord> c = connections.valueAt(conni);
898                 for (int i=0; i<c.size(); i++) {
899                     c.get(i).dumpDebug(proto, ServiceRecordProto.CONNECTIONS);
900                 }
901             }
902         }
903         if (mShortFgsInfo != null && mShortFgsInfo.isCurrent()) {
904             final long shortFgsToken = proto.start(ServiceRecordProto.SHORT_FGS_INFO);
905             proto.write(ServiceRecordProto.ShortFgsInfo.START_TIME,
906                     mShortFgsInfo.getStartTime());
907             proto.write(ServiceRecordProto.ShortFgsInfo.START_ID,
908                     mShortFgsInfo.getStartId());
909             proto.write(ServiceRecordProto.ShortFgsInfo.TIMEOUT_TIME,
910                     mShortFgsInfo.getTimeoutTime());
911             proto.write(ServiceRecordProto.ShortFgsInfo.PROC_STATE_DEMOTE_TIME,
912                     mShortFgsInfo.getProcStateDemoteTime());
913             proto.write(ServiceRecordProto.ShortFgsInfo.ANR_TIME,
914                     mShortFgsInfo.getAnrTime());
915             proto.end(shortFgsToken);
916         }
917 
918         // TODO: Dump all the mAllowWiu* and mAllowStart* fields as needed.
919 
920         proto.end(token);
921     }
922 
dumpReasonCode(PrintWriter pw, String prefix, String fieldName, int code)923     void dumpReasonCode(PrintWriter pw, String prefix, String fieldName, int code) {
924         pw.print(prefix);
925         pw.print(fieldName);
926         pw.print("=");
927         pw.println(PowerExemptionManager.reasonCodeToString(code));
928     }
929 
dump(PrintWriter pw, String prefix)930     void dump(PrintWriter pw, String prefix) {
931         pw.print(prefix); pw.print("intent={");
932                 pw.print(intent.getIntent().toShortString(false, true, false, false));
933                 pw.println('}');
934         pw.print(prefix); pw.print("packageName="); pw.println(packageName);
935         pw.print(prefix); pw.print("processName="); pw.println(processName);
936         pw.print(prefix); pw.print("targetSdkVersion="); pw.println(appInfo.targetSdkVersion);
937         if (permission != null) {
938             pw.print(prefix); pw.print("permission="); pw.println(permission);
939         }
940         long now = SystemClock.uptimeMillis();
941         long nowReal = SystemClock.elapsedRealtime();
942         if (appInfo != null) {
943             pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir);
944             if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
945                 pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir);
946             }
947             pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir);
948         }
949         pw.print(prefix); pw.print("app="); pw.println(app);
950         if (isolationHostProc != null) {
951             pw.print(prefix); pw.print("isolationHostProc="); pw.println(isolationHostProc);
952         }
953         if (allowlistManager) {
954             pw.print(prefix); pw.print("allowlistManager="); pw.println(allowlistManager);
955         }
956         if (mIsAllowedBgActivityStartsByBinding) {
957             pw.print(prefix); pw.print("mIsAllowedBgActivityStartsByBinding=");
958             pw.println(mIsAllowedBgActivityStartsByBinding);
959         }
960         if (mBackgroundStartPrivilegesByStartMerged.allowsAny()) {
961             pw.print(prefix); pw.print("mIsAllowedBgActivityStartsByStart=");
962             pw.println(mBackgroundStartPrivilegesByStartMerged);
963         }
964 
965         pw.print(prefix); pw.print("useNewWiuLogic_forCapabilities()=");
966         pw.println(useNewWiuLogic_forCapabilities());
967         pw.print(prefix); pw.print("useNewWiuLogic_forStart()=");
968         pw.println(useNewWiuLogic_forStart());
969         pw.print(prefix); pw.print("useNewBfslLogic()=");
970         pw.println(useNewBfslLogic());
971 
972         dumpReasonCode(pw, prefix, "mAllowWiu_noBinding", mAllowWiu_noBinding);
973         dumpReasonCode(pw, prefix, "mAllowWiu_inBindService", mAllowWiu_inBindService);
974         dumpReasonCode(pw, prefix, "mAllowWiu_byBindings", mAllowWiu_byBindings);
975 
976         dumpReasonCode(pw, prefix, "getFgsAllowWiu_legacy", getFgsAllowWiu_legacy());
977         dumpReasonCode(pw, prefix, "getFgsAllowWiu_new", getFgsAllowWiu_new());
978 
979         dumpReasonCode(pw, prefix, "getFgsAllowWiu_forStart", getFgsAllowWiu_forStart());
980         dumpReasonCode(pw, prefix, "getFgsAllowWiu_forCapabilities",
981                 getFgsAllowWiu_forCapabilities());
982 
983         pw.print(prefix); pw.print("allowUiJobScheduling="); pw.println(mAllowUiJobScheduling);
984         pw.print(prefix); pw.print("recentCallingPackage=");
985                 pw.println(mRecentCallingPackage);
986         pw.print(prefix); pw.print("recentCallingUid=");
987         pw.println(mRecentCallingUid);
988 
989         dumpReasonCode(pw, prefix, "mAllowStart_noBinding", mAllowStart_noBinding);
990         dumpReasonCode(pw, prefix, "mAllowStart_inBindService", mAllowStart_inBindService);
991         dumpReasonCode(pw, prefix, "mAllowStart_byBindings", mAllowStart_byBindings);
992 
993         dumpReasonCode(pw, prefix, "getFgsAllowStart_legacy", getFgsAllowStart_legacy());
994         dumpReasonCode(pw, prefix, "getFgsAllowStart_new", getFgsAllowStart_new());
995         dumpReasonCode(pw, prefix, "getFgsAllowStart", getFgsAllowStart());
996 
997         pw.print(prefix); pw.print("startForegroundCount=");
998         pw.println(mStartForegroundCount);
999         pw.print(prefix); pw.print("infoAllowStartForeground=");
1000         pw.println(mInfoAllowStartForeground);
1001 
1002         if (delayed) {
1003             pw.print(prefix); pw.print("delayed="); pw.println(delayed);
1004         }
1005         if (isForeground || foregroundId != 0) {
1006             pw.print(prefix); pw.print("isForeground="); pw.print(isForeground);
1007             pw.print(" foregroundId="); pw.print(foregroundId);
1008             pw.printf(" types=0x%08X", foregroundServiceType);
1009             pw.print(" foregroundNoti="); pw.println(foregroundNoti);
1010 
1011             if (isShortFgs() && mShortFgsInfo != null) {
1012                 pw.print(prefix); pw.print("isShortFgs=true");
1013                 pw.print(" startId="); pw.print(mShortFgsInfo.getStartId());
1014                 pw.print(" startForegroundCount=");
1015                 pw.print(mShortFgsInfo.getStartForegroundCount());
1016                 pw.print(" startTime=");
1017                 TimeUtils.formatDuration(mShortFgsInfo.getStartTime(), now, pw);
1018                 pw.print(" timeout=");
1019                 TimeUtils.formatDuration(mShortFgsInfo.getTimeoutTime(), now, pw);
1020                 pw.print(" demoteTime=");
1021                 TimeUtils.formatDuration(mShortFgsInfo.getProcStateDemoteTime(), now, pw);
1022                 pw.print(" anrTime=");
1023                 TimeUtils.formatDuration(mShortFgsInfo.getAnrTime(), now, pw);
1024                 pw.println();
1025             }
1026         }
1027         if (mIsFgsDelegate) {
1028             pw.print(prefix); pw.print("isFgsDelegate="); pw.println(mIsFgsDelegate);
1029         }
1030         pw.print(prefix); pw.print("createTime=");
1031                 TimeUtils.formatDuration(createRealTime, nowReal, pw);
1032                 pw.print(" startingBgTimeout=");
1033                 TimeUtils.formatDuration(startingBgTimeout, now, pw);
1034                 pw.println();
1035         pw.print(prefix); pw.print("lastActivity=");
1036                 TimeUtils.formatDuration(lastActivity, now, pw);
1037                 pw.print(" restartTime=");
1038                 TimeUtils.formatDuration(restartTime, now, pw);
1039                 pw.print(" createdFromFg="); pw.println(createdFromFg);
1040         if (pendingConnectionGroup != 0) {
1041             pw.print(prefix); pw.print(" pendingConnectionGroup=");
1042             pw.print(pendingConnectionGroup);
1043             pw.print(" Importance="); pw.println(pendingConnectionImportance);
1044         }
1045         if (startRequested || delayedStop || lastStartId != 0) {
1046             pw.print(prefix); pw.print("startRequested="); pw.print(startRequested);
1047                     pw.print(" delayedStop="); pw.print(delayedStop);
1048                     pw.print(" stopIfKilled="); pw.print(stopIfKilled);
1049                     pw.print(" callStart="); pw.print(callStart);
1050                     pw.print(" lastStartId="); pw.println(lastStartId);
1051                     pw.print(" startCommandResult="); pw.println(startCommandResult);
1052         }
1053         if (executeNesting != 0) {
1054             pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting);
1055                     pw.print(" executeFg="); pw.print(executeFg);
1056                     pw.print(" executingStart=");
1057                     TimeUtils.formatDuration(executingStart, now, pw);
1058                     pw.println();
1059         }
1060         if (destroying || destroyTime != 0) {
1061             pw.print(prefix); pw.print("destroying="); pw.print(destroying);
1062                     pw.print(" destroyTime=");
1063                     TimeUtils.formatDuration(destroyTime, now, pw);
1064                     pw.println();
1065         }
1066         if (crashCount != 0 || restartCount != 0
1067                 || (nextRestartTime - mRestartSchedulingTime) != 0 || nextRestartTime != 0) {
1068             pw.print(prefix); pw.print("restartCount="); pw.print(restartCount);
1069                     pw.print(" restartDelay=");
1070                     TimeUtils.formatDuration(nextRestartTime - mRestartSchedulingTime, now, pw);
1071                     pw.print(" nextRestartTime=");
1072                     TimeUtils.formatDuration(nextRestartTime, now, pw);
1073                     pw.print(" crashCount="); pw.println(crashCount);
1074         }
1075         if (deliveredStarts.size() > 0) {
1076             pw.print(prefix); pw.println("Delivered Starts:");
1077             dumpStartList(pw, prefix, deliveredStarts, now);
1078         }
1079         if (pendingStarts.size() > 0) {
1080             pw.print(prefix); pw.println("Pending Starts:");
1081             dumpStartList(pw, prefix, pendingStarts, 0);
1082         }
1083         if (bindings.size() > 0) {
1084             pw.print(prefix); pw.println("Bindings:");
1085             for (int i=0; i<bindings.size(); i++) {
1086                 IntentBindRecord b = bindings.valueAt(i);
1087                 pw.print(prefix); pw.print("* IntentBindRecord{");
1088                         pw.print(Integer.toHexString(System.identityHashCode(b)));
1089                         if ((b.collectFlags()&Context.BIND_AUTO_CREATE) != 0) {
1090                             pw.append(" CREATE");
1091                         }
1092                         pw.println("}:");
1093                 b.dumpInService(pw, prefix + "  ");
1094             }
1095         }
1096         if (connections.size() > 0) {
1097             pw.print(prefix); pw.println("All Connections:");
1098             for (int conni=0; conni<connections.size(); conni++) {
1099                 ArrayList<ConnectionRecord> c = connections.valueAt(conni);
1100                 for (int i=0; i<c.size(); i++) {
1101                     pw.print(prefix); pw.print("  "); pw.println(c.get(i));
1102                 }
1103             }
1104         }
1105     }
1106 
1107     /** Used only for tests */
ServiceRecord(ActivityManagerService ams)1108     private ServiceRecord(ActivityManagerService ams) {
1109         this.ams = ams;
1110         name = null;
1111         instanceName = null;
1112         shortInstanceName = null;
1113         definingPackageName = null;
1114         definingUid = 0;
1115         intent = null;
1116         serviceInfo = null;
1117         userId = 0;
1118         packageName = null;
1119         processName = null;
1120         permission = null;
1121         exported = false;
1122         restarter = null;
1123         createRealTime = 0;
1124         isSdkSandbox = false;
1125         sdkSandboxClientAppUid = 0;
1126         sdkSandboxClientAppPackage = null;
1127         inSharedIsolatedProcess = false;
1128     }
1129 
newEmptyInstanceForTest(ActivityManagerService ams)1130     public static ServiceRecord newEmptyInstanceForTest(ActivityManagerService ams) {
1131         return new ServiceRecord(ams);
1132     }
1133 
ServiceRecord(ActivityManagerService ams, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter)1134     ServiceRecord(ActivityManagerService ams, ComponentName name,
1135             ComponentName instanceName, String definingPackageName, int definingUid,
1136             Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg,
1137             Runnable restarter) {
1138         this(ams, name, instanceName, definingPackageName, definingUid, intent, sInfo, callerIsFg,
1139                 restarter, sInfo.processName, INVALID_UID, null, false);
1140     }
1141 
ServiceRecord(ActivityManagerService ams, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter, String processName, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage, boolean inSharedIsolatedProcess)1142     ServiceRecord(ActivityManagerService ams, ComponentName name,
1143             ComponentName instanceName, String definingPackageName, int definingUid,
1144             Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg,
1145             Runnable restarter, String processName, int sdkSandboxClientAppUid,
1146             String sdkSandboxClientAppPackage, boolean inSharedIsolatedProcess) {
1147         this.ams = ams;
1148         this.name = name;
1149         this.instanceName = instanceName;
1150         shortInstanceName = instanceName.flattenToShortString();
1151         this.definingPackageName = definingPackageName;
1152         this.definingUid = definingUid;
1153         this.intent = intent;
1154         serviceInfo = sInfo;
1155         appInfo = sInfo.applicationInfo;
1156         packageName = sInfo.applicationInfo.packageName;
1157         this.isSdkSandbox = sdkSandboxClientAppUid != INVALID_UID;
1158         this.sdkSandboxClientAppUid = sdkSandboxClientAppUid;
1159         this.sdkSandboxClientAppPackage = sdkSandboxClientAppPackage;
1160         this.inSharedIsolatedProcess = inSharedIsolatedProcess;
1161         this.processName = processName;
1162         permission = sInfo.permission;
1163         exported = sInfo.exported;
1164         this.restarter = restarter;
1165         createRealTime = SystemClock.elapsedRealtime();
1166         lastActivity = SystemClock.uptimeMillis();
1167         userId = UserHandle.getUserId(appInfo.uid);
1168         createdFromFg = callerIsFg;
1169         updateKeepWarmLocked();
1170         // initialize notification permission state; this'll be updated whenever there's an attempt
1171         // to post or update a notification, but that doesn't cover the time before the first
1172         // notification
1173         updateFgsHasNotificationPermission();
1174     }
1175 
getTracker()1176     public ServiceState getTracker() {
1177         if (tracker != null) {
1178             return tracker;
1179         }
1180         if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
1181             tracker = ams.mProcessStats.getServiceState(serviceInfo.packageName,
1182                     serviceInfo.applicationInfo.uid,
1183                     serviceInfo.applicationInfo.longVersionCode,
1184                     serviceInfo.processName, serviceInfo.name);
1185             if (tracker != null) {
1186                 tracker.applyNewOwner(this);
1187             }
1188         }
1189         return tracker;
1190     }
1191 
forceClearTracker()1192     public void forceClearTracker() {
1193         if (tracker != null) {
1194             tracker.clearCurrentOwner(this, true);
1195             tracker = null;
1196         }
1197     }
1198 
makeRestarting(int memFactor, long now)1199     public void makeRestarting(int memFactor, long now) {
1200         if (restartTracker == null) {
1201             if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
1202                 restartTracker = ams.mProcessStats.getServiceState(
1203                         serviceInfo.packageName,
1204                         serviceInfo.applicationInfo.uid,
1205                         serviceInfo.applicationInfo.longVersionCode,
1206                         serviceInfo.processName, serviceInfo.name);
1207             }
1208             if (restartTracker == null) {
1209                 return;
1210             }
1211         }
1212         restartTracker.setRestarting(true, memFactor, now);
1213     }
1214 
setProcess(ProcessRecord proc, IApplicationThread thread, int pid, UidRecord uidRecord)1215     public void setProcess(ProcessRecord proc, IApplicationThread thread, int pid,
1216             UidRecord uidRecord) {
1217         if (proc != null) {
1218             // We're starting a new process for this service, but a previous one is allowed to start
1219             // background activities. Remove that ability now (unless the new process is the same as
1220             // the previous one, which is a common case).
1221             if (mAppForAllowingBgActivityStartsByStart != null) {
1222                 if (mAppForAllowingBgActivityStartsByStart != proc) {
1223                     mAppForAllowingBgActivityStartsByStart
1224                             .removeBackgroundStartPrivileges(this);
1225                     ams.mHandler.removeCallbacks(mCleanUpAllowBgActivityStartsByStartCallback);
1226                 }
1227             }
1228             // Make sure the cleanup callback knows about the new process.
1229             mAppForAllowingBgActivityStartsByStart =
1230                     mBackgroundStartPrivilegesByStartMerged.allowsAny()
1231                     ? proc : null;
1232             BackgroundStartPrivileges backgroundStartPrivileges =
1233                     getBackgroundStartPrivilegesWithExclusiveToken();
1234             if (backgroundStartPrivileges.allowsAny()) {
1235                 proc.addOrUpdateBackgroundStartPrivileges(this,
1236                         backgroundStartPrivileges);
1237             } else {
1238                 proc.removeBackgroundStartPrivileges(this);
1239             }
1240         }
1241         if (app != null && app != proc) {
1242             // If the old app is allowed to start bg activities because of a service start, leave it
1243             // that way until the cleanup callback runs. Otherwise we can remove its bg activity
1244             // start ability immediately (it can't be bound now).
1245             if (mBackgroundStartPrivilegesByStartMerged.allowsNothing()) {
1246                 app.removeBackgroundStartPrivileges(this);
1247             }
1248             app.mServices.updateBoundClientUids();
1249             app.mServices.updateHostingComonentTypeForBindingsLocked();
1250         }
1251         app = proc;
1252         updateProcessStateOnRequest();
1253         if (pendingConnectionGroup > 0 && proc != null) {
1254             final ProcessServiceRecord psr = proc.mServices;
1255             psr.setConnectionService(this);
1256             psr.setConnectionGroup(pendingConnectionGroup);
1257             psr.setConnectionImportance(pendingConnectionImportance);
1258             pendingConnectionGroup = pendingConnectionImportance = 0;
1259         }
1260         if (ActivityManagerService.TRACK_PROCSTATS_ASSOCIATIONS) {
1261             for (int conni = connections.size() - 1; conni >= 0; conni--) {
1262                 ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
1263                 for (int i = 0; i < cr.size(); i++) {
1264                     final ConnectionRecord conn = cr.get(i);
1265                     if (proc != null) {
1266                         conn.startAssociationIfNeeded();
1267                     } else {
1268                         conn.stopAssociation();
1269                     }
1270                 }
1271             }
1272         }
1273         if (proc != null) {
1274             proc.mServices.updateBoundClientUids();
1275             proc.mServices.updateHostingComonentTypeForBindingsLocked();
1276         }
1277     }
1278 
updateProcessStateOnRequest()1279     void updateProcessStateOnRequest() {
1280         mProcessStateOnRequest = app != null && app.getThread() != null && !app.isKilled()
1281                 ? app.mState.getCurProcState() : PROCESS_STATE_NONEXISTENT;
1282     }
1283 
1284     @NonNull
getConnections()1285     ArrayMap<IBinder, ArrayList<ConnectionRecord>> getConnections() {
1286         return connections;
1287     }
1288 
addConnection(IBinder binder, ConnectionRecord c)1289     void addConnection(IBinder binder, ConnectionRecord c) {
1290         ArrayList<ConnectionRecord> clist = connections.get(binder);
1291         if (clist == null) {
1292             clist = new ArrayList<>();
1293             connections.put(binder, clist);
1294         }
1295         clist.add(c);
1296 
1297         // if we have a process attached, add bound client uid of this connection to it
1298         if (app != null) {
1299             app.mServices.addBoundClientUid(c.clientUid, c.clientPackageName, c.getFlags());
1300             app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE);
1301         }
1302     }
1303 
removeConnection(IBinder binder)1304     void removeConnection(IBinder binder) {
1305         connections.remove(binder);
1306         // if we have a process attached, tell it to update the state of bound clients
1307         if (app != null) {
1308             app.mServices.updateBoundClientUids();
1309             app.mServices.updateHostingComonentTypeForBindingsLocked();
1310         }
1311     }
1312 
1313     /**
1314      * @return {@code true} if the killed service which was started by {@link Context#startService}
1315      *         has no reason to start again. Note this condition doesn't consider the bindings.
1316      */
canStopIfKilled(boolean isStartCanceled)1317     boolean canStopIfKilled(boolean isStartCanceled) {
1318         if (isShortFgs()) { // Short-FGS should always stop if killed.
1319             return true;
1320         }
1321         return startRequested && (stopIfKilled || isStartCanceled) && pendingStarts.isEmpty();
1322     }
1323 
updateIsAllowedBgActivityStartsByBinding()1324     void updateIsAllowedBgActivityStartsByBinding() {
1325         boolean isAllowedByBinding = false;
1326         for (int conni = connections.size() - 1; conni >= 0; conni--) {
1327             ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
1328             for (int i = 0; i < cr.size(); i++) {
1329                 if (cr.get(i).hasFlag(Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS)) {
1330                     isAllowedByBinding = true;
1331                     break;
1332                 }
1333             }
1334             if (isAllowedByBinding) {
1335                 break;
1336             }
1337         }
1338         setAllowedBgActivityStartsByBinding(isAllowedByBinding);
1339     }
1340 
setAllowedBgActivityStartsByBinding(boolean newValue)1341     void setAllowedBgActivityStartsByBinding(boolean newValue) {
1342         mIsAllowedBgActivityStartsByBinding = newValue;
1343         updateParentProcessBgActivityStartsToken();
1344     }
1345 
1346     /**
1347      * Called when the service is started with allowBackgroundActivityStarts set. We allow
1348      * it for background activity starts, setting up a callback to remove this ability after a
1349      * timeout. Note that the ability for starting background activities persists for the process
1350      * even if the service is subsequently stopped.
1351      */
allowBgActivityStartsOnServiceStart(BackgroundStartPrivileges backgroundStartPrivileges)1352     void allowBgActivityStartsOnServiceStart(BackgroundStartPrivileges backgroundStartPrivileges) {
1353         checkArgument(backgroundStartPrivileges.allowsAny());
1354         mBackgroundStartPrivilegesByStart.add(backgroundStartPrivileges);
1355         setAllowedBgActivityStartsByStart(
1356                 backgroundStartPrivileges.merge(mBackgroundStartPrivilegesByStartMerged));
1357         if (app != null) {
1358             mAppForAllowingBgActivityStartsByStart = app;
1359         }
1360 
1361         // This callback is stateless, so we create it once when we first need it.
1362         if (mCleanUpAllowBgActivityStartsByStartCallback == null) {
1363             mCleanUpAllowBgActivityStartsByStartCallback = () -> {
1364                 synchronized (ams) {
1365                     mBackgroundStartPrivilegesByStart.remove(0);
1366                     if (!mBackgroundStartPrivilegesByStart.isEmpty()) {
1367                         // recalculate the merged token
1368                         mBackgroundStartPrivilegesByStartMerged =
1369                                 BackgroundStartPrivileges.merge(mBackgroundStartPrivilegesByStart);
1370 
1371                         // There are other callbacks in the queue, let's just update the originating
1372                         // token
1373                         if (mBackgroundStartPrivilegesByStartMerged.allowsAny()) {
1374                             // mAppForAllowingBgActivityStartsByStart can be null here for example
1375                             // if get 2 calls to allowBgActivityStartsOnServiceStart() without a
1376                             // process attached to this ServiceRecord, so we need to perform a null
1377                             // check here.
1378                             if (mAppForAllowingBgActivityStartsByStart != null) {
1379                                 mAppForAllowingBgActivityStartsByStart
1380                                         .addOrUpdateBackgroundStartPrivileges(this,
1381                                                 getBackgroundStartPrivilegesWithExclusiveToken());
1382                             }
1383                         } else {
1384                             Slog.wtf(TAG,
1385                                     "Service callback to revoke bg activity starts by service "
1386                                             + "start triggered but "
1387                                             + "mBackgroundStartPrivilegesByStartMerged = "
1388                                             + mBackgroundStartPrivilegesByStartMerged
1389                                             + ". This should never happen.");
1390                         }
1391                     } else {
1392                         // Last callback on the queue
1393                         if (app == mAppForAllowingBgActivityStartsByStart) {
1394                             // The process we allowed is still running the service. We remove
1395                             // the ability by start, but it may still be allowed via bound
1396                             // connections.
1397                             setAllowedBgActivityStartsByStart(BackgroundStartPrivileges.NONE);
1398                         } else if (mAppForAllowingBgActivityStartsByStart != null) {
1399                             // The process we allowed is not running the service. It therefore can't
1400                             // be bound so we can unconditionally remove the ability.
1401                             mAppForAllowingBgActivityStartsByStart
1402                                     .removeBackgroundStartPrivileges(ServiceRecord.this);
1403                         }
1404                         mAppForAllowingBgActivityStartsByStart = null;
1405                     }
1406                 }
1407             };
1408         }
1409 
1410         // Existing callbacks will only update the originating token, only when the last callback is
1411         // executed is the grant revoked.
1412         ams.mHandler.postDelayed(mCleanUpAllowBgActivityStartsByStartCallback,
1413                 ams.mConstants.SERVICE_BG_ACTIVITY_START_TIMEOUT);
1414     }
1415 
updateAllowUiJobScheduling(boolean allowUiJobScheduling)1416     void updateAllowUiJobScheduling(boolean allowUiJobScheduling) {
1417         if (mAllowUiJobScheduling == allowUiJobScheduling) {
1418             return;
1419         }
1420         mAllowUiJobScheduling = allowUiJobScheduling;
1421     }
1422 
setAllowedBgActivityStartsByStart(BackgroundStartPrivileges newValue)1423     private void setAllowedBgActivityStartsByStart(BackgroundStartPrivileges newValue) {
1424         if (mBackgroundStartPrivilegesByStartMerged == newValue) {
1425             return;
1426         }
1427         mBackgroundStartPrivilegesByStartMerged = newValue;
1428         updateParentProcessBgActivityStartsToken();
1429     }
1430 
1431     /**
1432      * Whether the process this service runs in should be temporarily allowed to start
1433      * activities from background depends on the current state of both
1434      * {@code mIsAllowedBgActivityStartsByStart} and
1435      * {@code mIsAllowedBgActivityStartsByBinding}. If either is true, this ServiceRecord
1436      * should be contributing as a token in parent ProcessRecord.
1437      *
1438      * @see com.android.server.am.ProcessRecord#addOrUpdateBackgroundStartPrivileges(Binder,
1439      *         BackgroundStartPrivileges)
1440      * @see com.android.server.am.ProcessRecord#removeBackgroundStartPrivileges(Binder)
1441      */
updateParentProcessBgActivityStartsToken()1442     private void updateParentProcessBgActivityStartsToken() {
1443         if (app == null) {
1444             return;
1445         }
1446         BackgroundStartPrivileges backgroundStartPrivileges =
1447                 getBackgroundStartPrivilegesWithExclusiveToken();
1448         if (backgroundStartPrivileges.allowsAny()) {
1449             // if the token is already there it's safe to "re-add it" - we're dealing with
1450             // a set of Binder objects
1451             app.addOrUpdateBackgroundStartPrivileges(this,
1452                     backgroundStartPrivileges);
1453         } else {
1454             app.removeBackgroundStartPrivileges(this);
1455         }
1456     }
1457 
1458     /**
1459      * Returns {@link BackgroundStartPrivileges} that represents the privileges a specific
1460      * originating token or a generic aggregate token.
1461      *
1462      * If all privileges are associated with the same token (i.e. the service is only allowed due
1463      * to starts) the token will be retained, otherwise (e.g. the privileges were granted by
1464      * bindings) the originating token will be empty.
1465      */
1466     @Nullable
getBackgroundStartPrivilegesWithExclusiveToken()1467     private BackgroundStartPrivileges getBackgroundStartPrivilegesWithExclusiveToken() {
1468         if (mIsAllowedBgActivityStartsByBinding) {
1469             return BackgroundStartPrivileges.ALLOW_BAL;
1470         }
1471         if (mBackgroundStartPrivilegesByStart.isEmpty()) {
1472             return BackgroundStartPrivileges.NONE;
1473         }
1474         return mBackgroundStartPrivilegesByStartMerged;
1475     }
1476 
1477     @GuardedBy("ams")
updateKeepWarmLocked()1478     void updateKeepWarmLocked() {
1479         mKeepWarming = ams.mConstants.KEEP_WARMING_SERVICES.contains(name)
1480                 && (ams.mUserController.getCurrentUserId() == userId
1481                 || ams.mUserController.isCurrentProfile(userId)
1482                 || ams.isSingleton(processName, appInfo, instanceName.getClassName(),
1483                         serviceInfo.flags));
1484     }
1485 
retrieveAppBindingLocked(Intent intent, ProcessRecord app, ProcessRecord attributedApp)1486     public AppBindRecord retrieveAppBindingLocked(Intent intent,
1487             ProcessRecord app, ProcessRecord attributedApp) {
1488         Intent.FilterComparison filter = new Intent.FilterComparison(intent);
1489         IntentBindRecord i = bindings.get(filter);
1490         if (i == null) {
1491             i = new IntentBindRecord(this, filter);
1492             bindings.put(filter, i);
1493         }
1494         AppBindRecord a = i.apps.get(app);
1495         if (a != null) {
1496             return a;
1497         }
1498         a = new AppBindRecord(this, i, app, attributedApp);
1499         i.apps.put(app, a);
1500         return a;
1501     }
1502 
hasAutoCreateConnections()1503     public boolean hasAutoCreateConnections() {
1504         // XXX should probably keep a count of the number of auto-create
1505         // connections directly in the service.
1506         for (int conni=connections.size()-1; conni>=0; conni--) {
1507             ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
1508             for (int i=0; i<cr.size(); i++) {
1509                 if (cr.get(i).hasFlag(Context.BIND_AUTO_CREATE)) {
1510                     return true;
1511                 }
1512             }
1513         }
1514         return false;
1515     }
1516 
updateAllowlistManager()1517     public void updateAllowlistManager() {
1518         allowlistManager = false;
1519         for (int conni=connections.size()-1; conni>=0; conni--) {
1520             ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
1521             for (int i=0; i<cr.size(); i++) {
1522                 if (cr.get(i).hasFlag(Context.BIND_ALLOW_WHITELIST_MANAGEMENT)) {
1523                     allowlistManager = true;
1524                     return;
1525                 }
1526             }
1527         }
1528     }
1529 
resetRestartCounter()1530     public void resetRestartCounter() {
1531         restartCount = 0;
1532         restartDelay = 0;
1533         restartTime = 0;
1534         mEarliestRestartTime  = 0;
1535         mRestartSchedulingTime = 0;
1536     }
1537 
findDeliveredStart(int id, boolean taskRemoved, boolean remove)1538     public StartItem findDeliveredStart(int id, boolean taskRemoved, boolean remove) {
1539         final int N = deliveredStarts.size();
1540         for (int i=0; i<N; i++) {
1541             StartItem si = deliveredStarts.get(i);
1542             if (si.id == id && si.taskRemoved == taskRemoved) {
1543                 if (remove) deliveredStarts.remove(i);
1544                 return si;
1545             }
1546         }
1547 
1548         return null;
1549     }
1550 
getLastStartId()1551     public int getLastStartId() {
1552         return lastStartId;
1553     }
1554 
makeNextStartId()1555     public int makeNextStartId() {
1556         lastStartId++;
1557         if (lastStartId < 1) {
1558             lastStartId = 1;
1559         }
1560         return lastStartId;
1561     }
1562 
updateFgsHasNotificationPermission()1563     private void updateFgsHasNotificationPermission() {
1564         // Do asynchronous communication with notification manager to avoid deadlocks.
1565         final String localPackageName = packageName;
1566         final int appUid = appInfo.uid;
1567 
1568         ams.mHandler.post(new Runnable() {
1569             public void run() {
1570                 NotificationManagerInternal nm = LocalServices.getService(
1571                         NotificationManagerInternal.class);
1572                 if (nm == null) {
1573                     return;
1574                 }
1575                 // Record whether the package has permission to notify the user
1576                 mFgsHasNotificationPermission = nm.areNotificationsEnabledForPackage(
1577                         localPackageName, appUid);
1578             }
1579         });
1580     }
1581 
postNotification(boolean byForegroundService)1582     public void postNotification(boolean byForegroundService) {
1583         if (isForeground && foregroundNoti != null && app != null) {
1584             final int appUid = appInfo.uid;
1585             final int appPid = app.getPid();
1586             // Do asynchronous communication with notification manager to
1587             // avoid deadlocks.
1588             final String localPackageName = packageName;
1589             final int localForegroundId = foregroundId;
1590             final Notification _foregroundNoti = foregroundNoti;
1591             final ServiceRecord record = this;
1592             if (DEBUG_FOREGROUND_SERVICE) {
1593                 Slog.d(TAG, "Posting notification " + _foregroundNoti
1594                         + " for foreground service " + this);
1595             }
1596             ams.mHandler.post(new Runnable() {
1597                 public void run() {
1598                     NotificationManagerInternal nm = LocalServices.getService(
1599                             NotificationManagerInternal.class);
1600                     if (nm == null) {
1601                         return;
1602                     }
1603                     // Record whether the package has permission to notify the user
1604                     mFgsHasNotificationPermission = nm.areNotificationsEnabledForPackage(
1605                             localPackageName, appUid);
1606                     Notification localForegroundNoti = _foregroundNoti;
1607                     try {
1608                         if (localForegroundNoti.getSmallIcon() == null) {
1609                             // It is not correct for the caller to not supply a notification
1610                             // icon, but this used to be able to slip through, so for
1611                             // those dirty apps we will create a notification clearly
1612                             // blaming the app.
1613                             Slog.v(TAG, "Attempted to start a foreground service ("
1614                                     + shortInstanceName
1615                                     + ") with a broken notification (no icon: "
1616                                     + localForegroundNoti
1617                                     + ")");
1618 
1619                             CharSequence appName = appInfo.loadLabel(
1620                                     ams.mContext.getPackageManager());
1621                             if (appName == null) {
1622                                 appName = appInfo.packageName;
1623                             }
1624                             Context ctx = null;
1625                             try {
1626                                 ctx = ams.mContext.createPackageContextAsUser(
1627                                         appInfo.packageName, 0, new UserHandle(userId));
1628 
1629                                 Notification.Builder notiBuilder = new Notification.Builder(ctx,
1630                                         localForegroundNoti.getChannelId());
1631 
1632                                 // it's ugly, but it clearly identifies the app
1633                                 notiBuilder.setSmallIcon(appInfo.icon);
1634 
1635                                 // mark as foreground
1636                                 notiBuilder.setFlag(Notification.FLAG_FOREGROUND_SERVICE, true);
1637 
1638                                 Intent runningIntent = new Intent(
1639                                         Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
1640                                 runningIntent.setData(Uri.fromParts("package",
1641                                         appInfo.packageName, null));
1642                                 PendingIntent pi = PendingIntent.getActivityAsUser(ams.mContext, 0,
1643                                         runningIntent, FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE, null,
1644                                         UserHandle.of(userId));
1645                                 notiBuilder.setColor(ams.mContext.getColor(
1646                                         com.android.internal
1647                                                 .R.color.system_notification_accent_color));
1648                                 notiBuilder.setContentTitle(
1649                                         ams.mContext.getString(
1650                                                 com.android.internal.R.string
1651                                                         .app_running_notification_title,
1652                                                 appName));
1653                                 notiBuilder.setContentText(
1654                                         ams.mContext.getString(
1655                                                 com.android.internal.R.string
1656                                                         .app_running_notification_text,
1657                                                 appName));
1658                                 notiBuilder.setContentIntent(pi);
1659 
1660                                 localForegroundNoti = notiBuilder.build();
1661                             } catch (PackageManager.NameNotFoundException e) {
1662                             }
1663                         }
1664                         if (nm.getNotificationChannel(localPackageName, appUid,
1665                                 localForegroundNoti.getChannelId()) == null) {
1666                             int targetSdkVersion = Build.VERSION_CODES.O_MR1;
1667                             try {
1668                                 final ApplicationInfo applicationInfo =
1669                                         ams.mContext.getPackageManager().getApplicationInfoAsUser(
1670                                                 appInfo.packageName, 0, userId);
1671                                 targetSdkVersion = applicationInfo.targetSdkVersion;
1672                             } catch (PackageManager.NameNotFoundException e) {
1673                             }
1674                             if (targetSdkVersion >= Build.VERSION_CODES.O_MR1) {
1675                                 throw new RuntimeException(
1676                                         "invalid channel for service notification: "
1677                                                 + foregroundNoti);
1678                             }
1679                         }
1680                         if (localForegroundNoti.getSmallIcon() == null) {
1681                             // Notifications whose icon is 0 are defined to not show
1682                             // a notification.  We don't want to
1683                             // just ignore it, we want to prevent the service from
1684                             // being foreground.
1685                             throw new RuntimeException("invalid service notification: "
1686                                     + foregroundNoti);
1687                         }
1688                         nm.enqueueNotification(localPackageName, localPackageName,
1689                                 appUid, appPid, null, localForegroundId, localForegroundNoti,
1690                                 userId, byForegroundService /* byForegroundService */);
1691 
1692                         foregroundNoti = localForegroundNoti; // save it for amending next time
1693 
1694                         signalForegroundServiceNotification(packageName, appInfo.uid,
1695                                 localForegroundId, false /* canceling */);
1696 
1697                     } catch (RuntimeException e) {
1698                         Slog.w(TAG, "Error showing notification for service", e);
1699                         // If it gave us a garbage notification, it doesn't
1700                         // get to be foreground.
1701                         ams.mServices.killMisbehavingService(record,
1702                                 appUid, appPid, localPackageName,
1703                                 CannotPostForegroundServiceNotificationException.TYPE_ID);
1704                     }
1705                 }
1706             });
1707         }
1708     }
1709 
cancelNotification()1710     public void cancelNotification() {
1711         // Do asynchronous communication with notification manager to
1712         // avoid deadlocks.
1713         final String localPackageName = packageName;
1714         final int localForegroundId = foregroundId;
1715         final int appUid = appInfo.uid;
1716         final int appPid = app != null ? app.getPid() : 0;
1717         ams.mHandler.post(new Runnable() {
1718             public void run() {
1719                 NotificationManagerInternal nm = LocalServices.getService(
1720                         NotificationManagerInternal.class);
1721                 if (nm == null) {
1722                     return;
1723                 }
1724                 try {
1725                     nm.cancelNotification(localPackageName, localPackageName, appUid, appPid,
1726                             null, localForegroundId, userId);
1727                 } catch (RuntimeException e) {
1728                     Slog.w(TAG, "Error canceling notification for service", e);
1729                 }
1730                 signalForegroundServiceNotification(packageName, appInfo.uid, localForegroundId,
1731                         true /* canceling */);
1732             }
1733         });
1734     }
1735 
signalForegroundServiceNotification(String packageName, int uid, int foregroundId, boolean canceling)1736     private void signalForegroundServiceNotification(String packageName, int uid,
1737             int foregroundId, boolean canceling) {
1738         synchronized (ams) {
1739             for (int i = ams.mForegroundServiceStateListeners.size() - 1; i >= 0; i--) {
1740                 ams.mForegroundServiceStateListeners.get(i).onForegroundServiceNotificationUpdated(
1741                         packageName, appInfo.uid, foregroundId, canceling);
1742             }
1743         }
1744     }
1745 
stripForegroundServiceFlagFromNotification()1746     public void stripForegroundServiceFlagFromNotification() {
1747         final int localForegroundId = foregroundId;
1748         final int localUserId = userId;
1749         final String localPackageName = packageName;
1750 
1751         // Do asynchronous communication with notification manager to
1752         // avoid deadlocks.
1753         ams.mHandler.post(new Runnable() {
1754             @Override
1755             public void run() {
1756                 NotificationManagerInternal nmi = LocalServices.getService(
1757                         NotificationManagerInternal.class);
1758                 if (nmi == null) {
1759                     return;
1760                 }
1761                 nmi.removeForegroundServiceFlagFromNotification(localPackageName, localForegroundId,
1762                         localUserId);
1763             }
1764         });
1765     }
1766 
clearDeliveredStartsLocked()1767     public void clearDeliveredStartsLocked() {
1768         for (int i=deliveredStarts.size()-1; i>=0; i--) {
1769             deliveredStarts.get(i).removeUriPermissionsLocked();
1770         }
1771         deliveredStarts.clear();
1772     }
1773 
toString()1774     public String toString() {
1775         if (stringName != null) {
1776             return stringName;
1777         }
1778         StringBuilder sb = new StringBuilder(128);
1779         sb.append("ServiceRecord{")
1780             .append(Integer.toHexString(System.identityHashCode(this)))
1781             .append(" u").append(userId)
1782             .append(' ').append(shortInstanceName);
1783         if (mRecentCallingPackage != null) {
1784             sb.append(" c:").append(mRecentCallingPackage);
1785         }
1786         sb.append('}');
1787         return stringName = sb.toString();
1788     }
1789 
getComponentName()1790     public ComponentName getComponentName() {
1791         return name;
1792     }
1793 
1794     /**
1795      * @return true if it's a foreground service of the "short service" type and don't have
1796      * other fgs type bits set.
1797      */
isShortFgs()1798     public boolean isShortFgs() {
1799         // Note if the type contains FOREGROUND_SERVICE_TYPE_SHORT_SERVICE but also other bits
1800         // set, it's _not_ considered be a short service. (because we shouldn't apply
1801         // the short-service restrictions)
1802         // (But we should be preventing mixture of FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
1803         // and other types in Service.startForeground().)
1804         return startRequested && isForeground
1805                 && (foregroundServiceType == ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE);
1806     }
1807 
getShortFgsInfo()1808     public ShortFgsInfo getShortFgsInfo() {
1809         return isShortFgs() ? mShortFgsInfo : null;
1810     }
1811 
1812     /**
1813      * Call it when a short FGS starts.
1814      */
setShortFgsInfo(long uptimeNow)1815     public void setShortFgsInfo(long uptimeNow) {
1816         this.mShortFgsInfo = new ShortFgsInfo(uptimeNow);
1817     }
1818 
1819     /** @return whether {@link #mShortFgsInfo} is set or not. */
hasShortFgsInfo()1820     public boolean hasShortFgsInfo() {
1821         return mShortFgsInfo != null;
1822     }
1823 
1824     /**
1825      * Call it when a short FGS stops.
1826      */
clearShortFgsInfo()1827     public void clearShortFgsInfo() {
1828         this.mShortFgsInfo = null;
1829     }
1830 
shouldTriggerShortFgsTimedEvent(long targetTime, long nowUptime)1831     private boolean shouldTriggerShortFgsTimedEvent(long targetTime, long nowUptime) {
1832         if (!isAppAlive()) {
1833             return false;
1834         }
1835         if (!this.startRequested || !isShortFgs() || mShortFgsInfo == null
1836                 || !mShortFgsInfo.isCurrent()) {
1837             return false;
1838         }
1839         return targetTime <= nowUptime;
1840     }
1841 
1842     /**
1843      * @return true if it's a short FGS that's still up and running, and should be timed out.
1844      */
shouldTriggerShortFgsTimeout(long nowUptime)1845     public boolean shouldTriggerShortFgsTimeout(long nowUptime) {
1846         return shouldTriggerShortFgsTimedEvent(
1847                 (mShortFgsInfo == null ? 0 : mShortFgsInfo.getTimeoutTime()),
1848                 nowUptime);
1849     }
1850 
1851     /**
1852      * @return true if it's a short FGS's procstate should be demoted.
1853      */
shouldDemoteShortFgsProcState(long nowUptime)1854     public boolean shouldDemoteShortFgsProcState(long nowUptime) {
1855         return shouldTriggerShortFgsTimedEvent(
1856                 (mShortFgsInfo == null ? 0 : mShortFgsInfo.getProcStateDemoteTime()),
1857                 nowUptime);
1858     }
1859 
1860     /**
1861      * @return true if it's a short FGS that's still up and running, and should be declared
1862      * an ANR.
1863      */
shouldTriggerShortFgsAnr(long nowUptime)1864     public boolean shouldTriggerShortFgsAnr(long nowUptime) {
1865         return shouldTriggerShortFgsTimedEvent(
1866                 (mShortFgsInfo == null ? 0 : mShortFgsInfo.getAnrTime()),
1867                 nowUptime);
1868     }
1869 
1870     /**
1871      * Human readable description about short-FGS internal states.
1872      */
getShortFgsTimedEventDescription(long nowUptime)1873     public String getShortFgsTimedEventDescription(long nowUptime) {
1874         return "aa=" + isAppAlive()
1875                 + " sreq=" + this.startRequested
1876                 + " isfg=" + this.isForeground
1877                 + " type=" + Integer.toHexString(this.foregroundServiceType)
1878                 + " sfc=" + this.mStartForegroundCount
1879                 + " now=" + nowUptime
1880                 + " " + (mShortFgsInfo == null ? "" : mShortFgsInfo.getDescription());
1881     }
1882 
1883     /**
1884      * Called when a time-limited FGS starts.
1885      */
createTimeLimitedFgsInfo()1886     public TimeLimitedFgsInfo createTimeLimitedFgsInfo() {
1887         return new TimeLimitedFgsInfo();
1888     }
1889 
1890     /**
1891      * @return true if one of the types of this FGS has a time limit.
1892      */
isFgsTimeLimited()1893     public boolean isFgsTimeLimited() {
1894         return startRequested
1895                 && isForeground
1896                 && ams.mServices.getTimeLimitedFgsType(foregroundServiceType)
1897                         != ServiceInfo.FOREGROUND_SERVICE_TYPE_NONE;
1898     }
1899 
isAppAlive()1900     private boolean isAppAlive() {
1901         if (app == null) {
1902             return false;
1903         }
1904         if (app.getThread() == null || app.isKilled() || app.isKilledByAm()) {
1905             return false;
1906         }
1907         return true;
1908     }
1909 
1910     /**
1911      * @return {@code true} if the host process has updated its oom adj scores.
1912      */
wasOomAdjUpdated()1913     boolean wasOomAdjUpdated() {
1914         return app != null && app.mState.getAdjSeq() > mAdjSeq;
1915     }
1916 
updateOomAdjSeq()1917     void updateOomAdjSeq() {
1918         if (app != null) {
1919             mAdjSeq = app.mState.getAdjSeq();
1920         }
1921     }
1922 }
1923