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