• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.PendingIntent.FLAG_IMMUTABLE;
20 import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
21 
22 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
23 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
24 
25 import android.app.Notification;
26 import android.app.PendingIntent;
27 import android.content.ComponentName;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.pm.ApplicationInfo;
31 import android.content.pm.PackageManager;
32 import android.content.pm.ServiceInfo;
33 import android.net.Uri;
34 import android.os.Binder;
35 import android.os.Build;
36 import android.os.IBinder;
37 import android.os.SystemClock;
38 import android.os.UserHandle;
39 import android.provider.Settings;
40 import android.util.ArrayMap;
41 import android.util.Slog;
42 import android.util.TimeUtils;
43 import android.util.proto.ProtoOutputStream;
44 import android.util.proto.ProtoUtils;
45 
46 import com.android.internal.annotations.GuardedBy;
47 import com.android.internal.app.procstats.ServiceState;
48 import com.android.internal.os.BatteryStatsImpl;
49 import com.android.server.LocalServices;
50 import com.android.server.notification.NotificationManagerInternal;
51 import com.android.server.uri.NeededUriGrants;
52 import com.android.server.uri.UriPermissionOwner;
53 
54 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.List;
57 import java.util.Objects;
58 
59 /**
60  * A running application service.
61  */
62 final class ServiceRecord extends Binder implements ComponentName.WithComponentName {
63     private static final String TAG = TAG_WITH_CLASS_NAME ? "ServiceRecord" : TAG_AM;
64 
65     // Maximum number of delivery attempts before giving up.
66     static final int MAX_DELIVERY_COUNT = 3;
67 
68     // Maximum number of times it can fail during execution before giving up.
69     static final int MAX_DONE_EXECUTING_COUNT = 6;
70 
71     final ActivityManagerService ams;
72     final BatteryStatsImpl.Uid.Pkg.Serv stats;
73     final ComponentName name; // service component.
74     final ComponentName instanceName; // service component's per-instance name.
75     final String shortInstanceName; // instanceName.flattenToShortString().
76     final String definingPackageName;
77                             // Can be different from appInfo.packageName for external services
78     final int definingUid;
79                             // Can be different from appInfo.uid for external services
80     final Intent.FilterComparison intent;
81                             // original intent used to find service.
82     final ServiceInfo serviceInfo;
83                             // all information about the service.
84     ApplicationInfo appInfo;
85                             // information about service's app.
86     final int userId;       // user that this service is running as
87     final String packageName; // the package implementing intent's component
88     final String processName; // process where this component wants to run
89     final String permission;// permission needed to access service
90     final boolean exported; // from ServiceInfo.exported
91     final Runnable restarter; // used to schedule retries of starting the service
92     final long createRealTime;  // when this service was created
93     final ArrayMap<Intent.FilterComparison, IntentBindRecord> bindings
94             = new ArrayMap<Intent.FilterComparison, IntentBindRecord>();
95                             // All active bindings to the service.
96     private final ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections
97             = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>();
98                             // IBinder -> ConnectionRecord of all bound clients
99 
100     ProcessRecord app;      // where this service is running or null.
101     ProcessRecord isolatedProc; // keep track of isolated process, if requested
102     ServiceState tracker; // tracking service execution, may be null
103     ServiceState restartTracker; // tracking service restart
104     boolean whitelistManager; // any bindings to this service have BIND_ALLOW_WHITELIST_MANAGEMENT?
105     boolean delayed;        // are we waiting to start this service in the background?
106     boolean fgRequired;     // is the service required to go foreground after starting?
107     boolean fgWaiting;      // is a timeout for going foreground already scheduled?
108     boolean isForeground;   // is service currently in foreground mode?
109     int foregroundId;       // Notification ID of last foreground req.
110     Notification foregroundNoti; // Notification record of foreground state.
111     int foregroundServiceType; // foreground service types.
112     long lastActivity;      // last time there was some activity on the service.
113     long startingBgTimeout;  // time at which we scheduled this for a delayed start.
114     boolean startRequested; // someone explicitly called start?
115     boolean delayedStop;    // service has been stopped but is in a delayed start?
116     boolean stopIfKilled;   // last onStart() said to stop if service killed?
117     boolean callStart;      // last onStart() has asked to always be called on restart.
118     int executeNesting;     // number of outstanding operations keeping foreground.
119     boolean executeFg;      // should we be executing in the foreground?
120     long executingStart;    // start time of last execute request.
121     boolean createdFromFg;  // was this service last created due to a foreground process call?
122     int crashCount;         // number of times proc has crashed with service running
123     int totalRestartCount;  // number of times we have had to restart.
124     int restartCount;       // number of restarts performed in a row.
125     long restartDelay;      // delay until next restart attempt.
126     long restartTime;       // time of last restart.
127     long nextRestartTime;   // time when restartDelay will expire.
128     boolean destroying;     // set when we have started destroying the service
129     long destroyTime;       // time at which destory was initiated.
130     int pendingConnectionGroup;        // To be filled in to ProcessRecord once it connects
131     int pendingConnectionImportance;   // To be filled in to ProcessRecord once it connects
132 
133     // any current binding to this service has BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS flag?
134     private boolean mHasBindingWhitelistingBgActivityStarts;
135     // is this service currently whitelisted to start activities from background by providing
136     // allowBackgroundActivityStarts=true to startServiceLocked()?
137     private boolean mHasStartedWhitelistingBgActivityStarts;
138     // used to clean up the state of hasStartedWhitelistingBgActivityStarts after a timeout
139     private Runnable mStartedWhitelistingBgActivityStartsCleanUp;
140     private ProcessRecord mAppForStartedWhitelistingBgActivityStarts;
141 
142     // allow while-in-use permissions in foreground service or not.
143     // while-in-use permissions in FGS started from background might be restricted.
144     boolean mAllowWhileInUsePermissionInFgs;
145     // The number of times Service.startForeground() is called;
146     int mStartForegroundCount;
147     // Last time mAllowWhileInUsePermissionInFgs is set.
148     long mLastSetFgsRestrictionTime;
149 
150     // the most recent package that start/bind this service.
151     String mRecentCallingPackage;
152 
153     String stringName;      // caching of toString
154 
155     private int lastStartId;    // identifier of most recent start request.
156 
157     boolean mKeepWarming; // Whether or not it'll keep critical code path of the host warm
158 
159     static class StartItem {
160         final ServiceRecord sr;
161         final boolean taskRemoved;
162         final int id;
163         final int callingId;
164         final Intent intent;
165         final NeededUriGrants neededGrants;
166         long deliveredTime;
167         int deliveryCount;
168         int doneExecutingCount;
169         UriPermissionOwner uriPermissions;
170 
171         String stringName;      // caching of toString
172 
StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent, NeededUriGrants _neededGrants, int _callingId)173         StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent,
174                 NeededUriGrants _neededGrants, int _callingId) {
175             sr = _sr;
176             taskRemoved = _taskRemoved;
177             id = _id;
178             intent = _intent;
179             neededGrants = _neededGrants;
180             callingId = _callingId;
181         }
182 
getUriPermissionsLocked()183         UriPermissionOwner getUriPermissionsLocked() {
184             if (uriPermissions == null) {
185                 uriPermissions = new UriPermissionOwner(sr.ams.mUgmInternal, this);
186             }
187             return uriPermissions;
188         }
189 
removeUriPermissionsLocked()190         void removeUriPermissionsLocked() {
191             if (uriPermissions != null) {
192                 uriPermissions.removeUriPermissions();
193                 uriPermissions = null;
194             }
195         }
196 
dumpDebug(ProtoOutputStream proto, long fieldId, long now)197         public void dumpDebug(ProtoOutputStream proto, long fieldId, long now) {
198             long token = proto.start(fieldId);
199             proto.write(ServiceRecordProto.StartItem.ID, id);
200             ProtoUtils.toDuration(proto,
201                     ServiceRecordProto.StartItem.DURATION, deliveredTime, now);
202             proto.write(ServiceRecordProto.StartItem.DELIVERY_COUNT, deliveryCount);
203             proto.write(ServiceRecordProto.StartItem.DONE_EXECUTING_COUNT, doneExecutingCount);
204             if (intent != null) {
205                 intent.dumpDebug(proto, ServiceRecordProto.StartItem.INTENT, true, true,
206                         true, false);
207             }
208             if (neededGrants != null) {
209                 neededGrants.dumpDebug(proto, ServiceRecordProto.StartItem.NEEDED_GRANTS);
210             }
211             if (uriPermissions != null) {
212                 uriPermissions.dumpDebug(proto, ServiceRecordProto.StartItem.URI_PERMISSIONS);
213             }
214             proto.end(token);
215         }
216 
toString()217         public String toString() {
218             if (stringName != null) {
219                 return stringName;
220             }
221             StringBuilder sb = new StringBuilder(128);
222             sb.append("ServiceRecord{")
223                 .append(Integer.toHexString(System.identityHashCode(sr)))
224                 .append(' ').append(sr.shortInstanceName)
225                 .append(" StartItem ")
226                 .append(Integer.toHexString(System.identityHashCode(this)))
227                 .append(" id=").append(id).append('}');
228             return stringName = sb.toString();
229         }
230     }
231 
232     final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>();
233                             // start() arguments which been delivered.
234     final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>();
235                             // start() arguments that haven't yet been delivered.
236 
dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now)237     void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) {
238         final int N = list.size();
239         for (int i=0; i<N; i++) {
240             StartItem si = list.get(i);
241             pw.print(prefix); pw.print("#"); pw.print(i);
242                     pw.print(" id="); pw.print(si.id);
243                     if (now != 0) {
244                         pw.print(" dur=");
245                         TimeUtils.formatDuration(si.deliveredTime, now, pw);
246                     }
247                     if (si.deliveryCount != 0) {
248                         pw.print(" dc="); pw.print(si.deliveryCount);
249                     }
250                     if (si.doneExecutingCount != 0) {
251                         pw.print(" dxc="); pw.print(si.doneExecutingCount);
252                     }
253                     pw.println("");
254             pw.print(prefix); pw.print("  intent=");
255                     if (si.intent != null) pw.println(si.intent.toString());
256                     else pw.println("null");
257             if (si.neededGrants != null) {
258                 pw.print(prefix); pw.print("  neededGrants=");
259                         pw.println(si.neededGrants);
260             }
261             if (si.uriPermissions != null) {
262                 si.uriPermissions.dump(pw, prefix);
263             }
264         }
265     }
266 
dumpDebug(ProtoOutputStream proto, long fieldId)267     void dumpDebug(ProtoOutputStream proto, long fieldId) {
268         long token = proto.start(fieldId);
269         proto.write(ServiceRecordProto.SHORT_NAME, this.shortInstanceName);
270         proto.write(ServiceRecordProto.IS_RUNNING, app != null);
271         if (app != null) {
272             proto.write(ServiceRecordProto.PID, app.pid);
273         }
274         if (intent != null) {
275             intent.getIntent().dumpDebug(proto, ServiceRecordProto.INTENT, false, true, false,
276                     false);
277         }
278         proto.write(ServiceRecordProto.PACKAGE_NAME, packageName);
279         proto.write(ServiceRecordProto.PROCESS_NAME, processName);
280         proto.write(ServiceRecordProto.PERMISSION, permission);
281 
282         long now = SystemClock.uptimeMillis();
283         long nowReal = SystemClock.elapsedRealtime();
284         if (appInfo != null) {
285             long appInfoToken = proto.start(ServiceRecordProto.APPINFO);
286             proto.write(ServiceRecordProto.AppInfo.BASE_DIR, appInfo.sourceDir);
287             if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
288                 proto.write(ServiceRecordProto.AppInfo.RES_DIR, appInfo.publicSourceDir);
289             }
290             proto.write(ServiceRecordProto.AppInfo.DATA_DIR, appInfo.dataDir);
291             proto.end(appInfoToken);
292         }
293         if (app != null) {
294             app.dumpDebug(proto, ServiceRecordProto.APP);
295         }
296         if (isolatedProc != null) {
297             isolatedProc.dumpDebug(proto, ServiceRecordProto.ISOLATED_PROC);
298         }
299         proto.write(ServiceRecordProto.WHITELIST_MANAGER, whitelistManager);
300         proto.write(ServiceRecordProto.DELAYED, delayed);
301         if (isForeground || foregroundId != 0) {
302             long fgToken = proto.start(ServiceRecordProto.FOREGROUND);
303             proto.write(ServiceRecordProto.Foreground.ID, foregroundId);
304             foregroundNoti.dumpDebug(proto, ServiceRecordProto.Foreground.NOTIFICATION);
305             proto.end(fgToken);
306         }
307         ProtoUtils.toDuration(proto, ServiceRecordProto.CREATE_REAL_TIME, createRealTime, nowReal);
308         ProtoUtils.toDuration(proto,
309                 ServiceRecordProto.STARTING_BG_TIMEOUT, startingBgTimeout, now);
310         ProtoUtils.toDuration(proto, ServiceRecordProto.LAST_ACTIVITY_TIME, lastActivity, now);
311         ProtoUtils.toDuration(proto, ServiceRecordProto.RESTART_TIME, restartTime, now);
312         proto.write(ServiceRecordProto.CREATED_FROM_FG, createdFromFg);
313         proto.write(ServiceRecordProto.ALLOW_WHILE_IN_USE_PERMISSION_IN_FGS,
314                 mAllowWhileInUsePermissionInFgs);
315 
316         if (startRequested || delayedStop || lastStartId != 0) {
317             long startToken = proto.start(ServiceRecordProto.START);
318             proto.write(ServiceRecordProto.Start.START_REQUESTED, startRequested);
319             proto.write(ServiceRecordProto.Start.DELAYED_STOP, delayedStop);
320             proto.write(ServiceRecordProto.Start.STOP_IF_KILLED, stopIfKilled);
321             proto.write(ServiceRecordProto.Start.LAST_START_ID, lastStartId);
322             proto.end(startToken);
323         }
324 
325         if (executeNesting != 0) {
326             long executNestingToken = proto.start(ServiceRecordProto.EXECUTE);
327             proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_NESTING, executeNesting);
328             proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_FG, executeFg);
329             ProtoUtils.toDuration(proto,
330                     ServiceRecordProto.ExecuteNesting.EXECUTING_START, executingStart, now);
331             proto.end(executNestingToken);
332         }
333         if (destroying || destroyTime != 0) {
334             ProtoUtils.toDuration(proto, ServiceRecordProto.DESTORY_TIME, destroyTime, now);
335         }
336         if (crashCount != 0 || restartCount != 0 || restartDelay != 0 || nextRestartTime != 0) {
337             long crashToken = proto.start(ServiceRecordProto.CRASH);
338             proto.write(ServiceRecordProto.Crash.RESTART_COUNT, restartCount);
339             ProtoUtils.toDuration(proto, ServiceRecordProto.Crash.RESTART_DELAY, restartDelay, now);
340             ProtoUtils.toDuration(proto,
341                     ServiceRecordProto.Crash.NEXT_RESTART_TIME, nextRestartTime, now);
342             proto.write(ServiceRecordProto.Crash.CRASH_COUNT, crashCount);
343             proto.end(crashToken);
344         }
345 
346         if (deliveredStarts.size() > 0) {
347             final int N = deliveredStarts.size();
348             for (int i = 0; i < N; i++) {
349                 deliveredStarts.get(i).dumpDebug(proto,
350                         ServiceRecordProto.DELIVERED_STARTS, now);
351             }
352         }
353         if (pendingStarts.size() > 0) {
354             final int N = pendingStarts.size();
355             for (int i = 0; i < N; i++) {
356                 pendingStarts.get(i).dumpDebug(proto, ServiceRecordProto.PENDING_STARTS, now);
357             }
358         }
359         if (bindings.size() > 0) {
360             final int N = bindings.size();
361             for (int i=0; i<N; i++) {
362                 IntentBindRecord b = bindings.valueAt(i);
363                 b.dumpDebug(proto, ServiceRecordProto.BINDINGS);
364             }
365         }
366         if (connections.size() > 0) {
367             final int N = connections.size();
368             for (int conni=0; conni<N; conni++) {
369                 ArrayList<ConnectionRecord> c = connections.valueAt(conni);
370                 for (int i=0; i<c.size(); i++) {
371                     c.get(i).dumpDebug(proto, ServiceRecordProto.CONNECTIONS);
372                 }
373             }
374         }
375         proto.end(token);
376     }
377 
dump(PrintWriter pw, String prefix)378     void dump(PrintWriter pw, String prefix) {
379         pw.print(prefix); pw.print("intent={");
380                 pw.print(intent.getIntent().toShortString(false, true, false, false));
381                 pw.println('}');
382         pw.print(prefix); pw.print("packageName="); pw.println(packageName);
383         pw.print(prefix); pw.print("processName="); pw.println(processName);
384         if (permission != null) {
385             pw.print(prefix); pw.print("permission="); pw.println(permission);
386         }
387         long now = SystemClock.uptimeMillis();
388         long nowReal = SystemClock.elapsedRealtime();
389         if (appInfo != null) {
390             pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir);
391             if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
392                 pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir);
393             }
394             pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir);
395         }
396         pw.print(prefix); pw.print("app="); pw.println(app);
397         if (isolatedProc != null) {
398             pw.print(prefix); pw.print("isolatedProc="); pw.println(isolatedProc);
399         }
400         if (whitelistManager) {
401             pw.print(prefix); pw.print("whitelistManager="); pw.println(whitelistManager);
402         }
403         if (mHasBindingWhitelistingBgActivityStarts) {
404             pw.print(prefix); pw.print("hasBindingWhitelistingBgActivityStarts=");
405             pw.println(mHasBindingWhitelistingBgActivityStarts);
406         }
407         if (mHasStartedWhitelistingBgActivityStarts) {
408             pw.print(prefix); pw.print("hasStartedWhitelistingBgActivityStarts=");
409             pw.println(mHasStartedWhitelistingBgActivityStarts);
410         }
411         pw.print(prefix); pw.print("allowWhileInUsePermissionInFgs=");
412                 pw.println(mAllowWhileInUsePermissionInFgs);
413         pw.print(prefix); pw.print("startForegroundCount=");
414         pw.println(mStartForegroundCount);
415         pw.print(prefix); pw.print("recentCallingPackage=");
416                 pw.println(mRecentCallingPackage);
417         if (delayed) {
418             pw.print(prefix); pw.print("delayed="); pw.println(delayed);
419         }
420         if (isForeground || foregroundId != 0) {
421             pw.print(prefix); pw.print("isForeground="); pw.print(isForeground);
422                     pw.print(" foregroundId="); pw.print(foregroundId);
423                     pw.print(" foregroundNoti="); pw.println(foregroundNoti);
424         }
425         pw.print(prefix); pw.print("createTime=");
426                 TimeUtils.formatDuration(createRealTime, nowReal, pw);
427                 pw.print(" startingBgTimeout=");
428                 TimeUtils.formatDuration(startingBgTimeout, now, pw);
429                 pw.println();
430         pw.print(prefix); pw.print("lastActivity=");
431                 TimeUtils.formatDuration(lastActivity, now, pw);
432                 pw.print(" restartTime=");
433                 TimeUtils.formatDuration(restartTime, now, pw);
434                 pw.print(" createdFromFg="); pw.println(createdFromFg);
435         if (pendingConnectionGroup != 0) {
436             pw.print(prefix); pw.print(" pendingConnectionGroup=");
437             pw.print(pendingConnectionGroup);
438             pw.print(" Importance="); pw.println(pendingConnectionImportance);
439         }
440         if (startRequested || delayedStop || lastStartId != 0) {
441             pw.print(prefix); pw.print("startRequested="); pw.print(startRequested);
442                     pw.print(" delayedStop="); pw.print(delayedStop);
443                     pw.print(" stopIfKilled="); pw.print(stopIfKilled);
444                     pw.print(" callStart="); pw.print(callStart);
445                     pw.print(" lastStartId="); pw.println(lastStartId);
446         }
447         if (executeNesting != 0) {
448             pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting);
449                     pw.print(" executeFg="); pw.print(executeFg);
450                     pw.print(" executingStart=");
451                     TimeUtils.formatDuration(executingStart, now, pw);
452                     pw.println();
453         }
454         if (destroying || destroyTime != 0) {
455             pw.print(prefix); pw.print("destroying="); pw.print(destroying);
456                     pw.print(" destroyTime=");
457                     TimeUtils.formatDuration(destroyTime, now, pw);
458                     pw.println();
459         }
460         if (crashCount != 0 || restartCount != 0
461                 || restartDelay != 0 || nextRestartTime != 0) {
462             pw.print(prefix); pw.print("restartCount="); pw.print(restartCount);
463                     pw.print(" restartDelay=");
464                     TimeUtils.formatDuration(restartDelay, now, pw);
465                     pw.print(" nextRestartTime=");
466                     TimeUtils.formatDuration(nextRestartTime, now, pw);
467                     pw.print(" crashCount="); pw.println(crashCount);
468         }
469         if (deliveredStarts.size() > 0) {
470             pw.print(prefix); pw.println("Delivered Starts:");
471             dumpStartList(pw, prefix, deliveredStarts, now);
472         }
473         if (pendingStarts.size() > 0) {
474             pw.print(prefix); pw.println("Pending Starts:");
475             dumpStartList(pw, prefix, pendingStarts, 0);
476         }
477         if (bindings.size() > 0) {
478             pw.print(prefix); pw.println("Bindings:");
479             for (int i=0; i<bindings.size(); i++) {
480                 IntentBindRecord b = bindings.valueAt(i);
481                 pw.print(prefix); pw.print("* IntentBindRecord{");
482                         pw.print(Integer.toHexString(System.identityHashCode(b)));
483                         if ((b.collectFlags()&Context.BIND_AUTO_CREATE) != 0) {
484                             pw.append(" CREATE");
485                         }
486                         pw.println("}:");
487                 b.dumpInService(pw, prefix + "  ");
488             }
489         }
490         if (connections.size() > 0) {
491             pw.print(prefix); pw.println("All Connections:");
492             for (int conni=0; conni<connections.size(); conni++) {
493                 ArrayList<ConnectionRecord> c = connections.valueAt(conni);
494                 for (int i=0; i<c.size(); i++) {
495                     pw.print(prefix); pw.print("  "); pw.println(c.get(i));
496                 }
497             }
498         }
499     }
500 
ServiceRecord(ActivityManagerService ams, BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter)501     ServiceRecord(ActivityManagerService ams,
502             BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
503             ComponentName instanceName, String definingPackageName, int definingUid,
504             Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg,
505             Runnable restarter) {
506         this.ams = ams;
507         this.stats = servStats;
508         this.name = name;
509         this.instanceName = instanceName;
510         shortInstanceName = instanceName.flattenToShortString();
511         this.definingPackageName = definingPackageName;
512         this.definingUid = definingUid;
513         this.intent = intent;
514         serviceInfo = sInfo;
515         appInfo = sInfo.applicationInfo;
516         packageName = sInfo.applicationInfo.packageName;
517         if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) {
518             processName = sInfo.processName + ":" + instanceName.getClassName();
519         } else {
520             processName = sInfo.processName;
521         }
522         permission = sInfo.permission;
523         exported = sInfo.exported;
524         this.restarter = restarter;
525         createRealTime = SystemClock.elapsedRealtime();
526         lastActivity = SystemClock.uptimeMillis();
527         userId = UserHandle.getUserId(appInfo.uid);
528         createdFromFg = callerIsFg;
529         updateKeepWarmLocked();
530     }
531 
getTracker()532     public ServiceState getTracker() {
533         if (tracker != null) {
534             return tracker;
535         }
536         if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
537             tracker = ams.mProcessStats.getServiceStateLocked(serviceInfo.packageName,
538                     serviceInfo.applicationInfo.uid, serviceInfo.applicationInfo.longVersionCode,
539                     serviceInfo.processName, serviceInfo.name);
540             tracker.applyNewOwner(this);
541         }
542         return tracker;
543     }
544 
forceClearTracker()545     public void forceClearTracker() {
546         if (tracker != null) {
547             tracker.clearCurrentOwner(this, true);
548             tracker = null;
549         }
550     }
551 
makeRestarting(int memFactor, long now)552     public void makeRestarting(int memFactor, long now) {
553         if (restartTracker == null) {
554             if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
555                 restartTracker = ams.mProcessStats.getServiceStateLocked(serviceInfo.packageName,
556                         serviceInfo.applicationInfo.uid,
557                         serviceInfo.applicationInfo.longVersionCode,
558                         serviceInfo.processName, serviceInfo.name);
559             }
560             if (restartTracker == null) {
561                 return;
562             }
563         }
564         restartTracker.setRestarting(true, memFactor, now);
565     }
566 
setProcess(ProcessRecord _proc)567     public void setProcess(ProcessRecord _proc) {
568         if (_proc != null) {
569             // We're starting a new process for this service, but a previous one is whitelisted.
570             // Remove that whitelisting now (unless the new process is the same as the previous one,
571             // which is a common case).
572             if (mAppForStartedWhitelistingBgActivityStarts != null) {
573                 if (mAppForStartedWhitelistingBgActivityStarts != _proc) {
574                     mAppForStartedWhitelistingBgActivityStarts
575                             .removeAllowBackgroundActivityStartsToken(this);
576                     ams.mHandler.removeCallbacks(mStartedWhitelistingBgActivityStartsCleanUp);
577                 }
578             }
579             // Make sure the cleanup callback knows about the new process.
580             mAppForStartedWhitelistingBgActivityStarts = mHasStartedWhitelistingBgActivityStarts
581                     ? _proc : null;
582             if (mHasStartedWhitelistingBgActivityStarts
583                     || mHasBindingWhitelistingBgActivityStarts) {
584                 _proc.addAllowBackgroundActivityStartsToken(this);
585             } else {
586                 _proc.removeAllowBackgroundActivityStartsToken(this);
587             }
588         }
589         if (app != null && app != _proc) {
590             // If the old app is whitelisted because of a service start, leave it whitelisted until
591             // the cleanup callback runs. Otherwise we can remove it from the whitelist immediately
592             // (it can't be bound now).
593             if (!mHasStartedWhitelistingBgActivityStarts) {
594                 app.removeAllowBackgroundActivityStartsToken(this);
595             }
596             app.updateBoundClientUids();
597         }
598         app = _proc;
599         if (pendingConnectionGroup > 0 && _proc != null) {
600             _proc.connectionService = this;
601             _proc.connectionGroup = pendingConnectionGroup;
602             _proc.connectionImportance = pendingConnectionImportance;
603             pendingConnectionGroup = pendingConnectionImportance = 0;
604         }
605         if (ActivityManagerService.TRACK_PROCSTATS_ASSOCIATIONS) {
606             for (int conni = connections.size() - 1; conni >= 0; conni--) {
607                 ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
608                 for (int i = 0; i < cr.size(); i++) {
609                     final ConnectionRecord conn = cr.get(i);
610                     if (_proc != null) {
611                         conn.startAssociationIfNeeded();
612                     } else {
613                         conn.stopAssociation();
614                     }
615                 }
616             }
617         }
618         if (_proc != null) {
619             _proc.updateBoundClientUids();
620         }
621     }
622 
getConnections()623     ArrayMap<IBinder, ArrayList<ConnectionRecord>> getConnections() {
624         return connections;
625     }
626 
addConnection(IBinder binder, ConnectionRecord c)627     void addConnection(IBinder binder, ConnectionRecord c) {
628         ArrayList<ConnectionRecord> clist = connections.get(binder);
629         if (clist == null) {
630             clist = new ArrayList<>();
631             connections.put(binder, clist);
632         }
633         clist.add(c);
634 
635         // if we have a process attached, add bound client uid of this connection to it
636         if (app != null) {
637             app.addBoundClientUid(c.clientUid);
638         }
639     }
640 
removeConnection(IBinder binder)641     void removeConnection(IBinder binder) {
642         connections.remove(binder);
643         // if we have a process attached, tell it to update the state of bound clients
644         if (app != null) {
645             app.updateBoundClientUids();
646         }
647     }
648 
649     /**
650      * @return {@code true} if the killed service which was started by {@link Context#startService}
651      *         has no reason to start again. Note this condition doesn't consider the bindings.
652      */
canStopIfKilled(boolean isStartCanceled)653     boolean canStopIfKilled(boolean isStartCanceled) {
654         return startRequested && (stopIfKilled || isStartCanceled) && pendingStarts.isEmpty();
655     }
656 
updateHasBindingWhitelistingBgActivityStarts()657     void updateHasBindingWhitelistingBgActivityStarts() {
658         boolean hasWhitelistingBinding = false;
659         for (int conni = connections.size() - 1; conni >= 0; conni--) {
660             ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
661             for (int i = 0; i < cr.size(); i++) {
662                 if ((cr.get(i).flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) {
663                     hasWhitelistingBinding = true;
664                     break;
665                 }
666             }
667             if (hasWhitelistingBinding) {
668                 break;
669             }
670         }
671         setHasBindingWhitelistingBgActivityStarts(hasWhitelistingBinding);
672     }
673 
setHasBindingWhitelistingBgActivityStarts(boolean newValue)674     void setHasBindingWhitelistingBgActivityStarts(boolean newValue) {
675         if (mHasBindingWhitelistingBgActivityStarts != newValue) {
676             mHasBindingWhitelistingBgActivityStarts = newValue;
677             updateParentProcessBgActivityStartsWhitelistingToken();
678         }
679     }
680 
681     /**
682      * Called when the service is started with allowBackgroundActivityStarts set. We whitelist
683      * it for background activity starts, setting up a callback to remove the whitelisting after a
684      * timeout. Note that the whitelisting persists for the process even if the service is
685      * subsequently stopped.
686      */
whitelistBgActivityStartsOnServiceStart()687     void whitelistBgActivityStartsOnServiceStart() {
688         setHasStartedWhitelistingBgActivityStarts(true);
689         if (app != null) {
690             mAppForStartedWhitelistingBgActivityStarts = app;
691         }
692 
693         // This callback is stateless, so we create it once when we first need it.
694         if (mStartedWhitelistingBgActivityStartsCleanUp == null) {
695             mStartedWhitelistingBgActivityStartsCleanUp = () -> {
696                 synchronized (ams) {
697                     if (app == mAppForStartedWhitelistingBgActivityStarts) {
698                         // The process we whitelisted is still running the service. We remove
699                         // the started whitelisting, but it may still be whitelisted via bound
700                         // connections.
701                         setHasStartedWhitelistingBgActivityStarts(false);
702                     } else  if (mAppForStartedWhitelistingBgActivityStarts != null) {
703                         // The process we whitelisted is not running the service. It therefore
704                         // can't be bound so we can unconditionally remove the whitelist.
705                         mAppForStartedWhitelistingBgActivityStarts
706                                 .removeAllowBackgroundActivityStartsToken(ServiceRecord.this);
707                     }
708                     mAppForStartedWhitelistingBgActivityStarts = null;
709                 }
710             };
711         }
712 
713         // if there's a request pending from the past, drop it before scheduling a new one
714         ams.mHandler.removeCallbacks(mStartedWhitelistingBgActivityStartsCleanUp);
715         ams.mHandler.postDelayed(mStartedWhitelistingBgActivityStartsCleanUp,
716                 ams.mConstants.SERVICE_BG_ACTIVITY_START_TIMEOUT);
717     }
718 
setHasStartedWhitelistingBgActivityStarts(boolean newValue)719     private void setHasStartedWhitelistingBgActivityStarts(boolean newValue) {
720         if (mHasStartedWhitelistingBgActivityStarts != newValue) {
721             mHasStartedWhitelistingBgActivityStarts = newValue;
722             updateParentProcessBgActivityStartsWhitelistingToken();
723         }
724     }
725 
726     /**
727      * Whether the process this service runs in should be temporarily whitelisted to start
728      * activities from background depends on the current state of both
729      * {@code hasStartedWhitelistingBgActivityStarts} and
730      * {@code hasBindingWhitelistingBgActivityStarts}. If either is true, this ServiceRecord
731      * should be contributing as a token in parent ProcessRecord.
732      *
733      * @see com.android.server.am.ProcessRecord#mAllowBackgroundActivityStartsTokens
734      */
updateParentProcessBgActivityStartsWhitelistingToken()735     private void updateParentProcessBgActivityStartsWhitelistingToken() {
736         if (app == null) {
737             return;
738         }
739         if (mHasStartedWhitelistingBgActivityStarts || mHasBindingWhitelistingBgActivityStarts) {
740             // if the token is already there it's safe to "re-add it" - we're dealing with
741             // a set of Binder objects
742             app.addAllowBackgroundActivityStartsToken(this);
743         } else {
744             app.removeAllowBackgroundActivityStartsToken(this);
745         }
746     }
747 
748     @GuardedBy("ams")
updateKeepWarmLocked()749     void updateKeepWarmLocked() {
750         mKeepWarming = ams.mConstants.KEEP_WARMING_SERVICES.contains(name)
751                 && (ams.mUserController.getCurrentUserId() == userId
752                 || ams.isSingleton(processName, appInfo, instanceName.getClassName(),
753                         serviceInfo.flags));
754     }
755 
retrieveAppBindingLocked(Intent intent, ProcessRecord app)756     public AppBindRecord retrieveAppBindingLocked(Intent intent,
757             ProcessRecord app) {
758         Intent.FilterComparison filter = new Intent.FilterComparison(intent);
759         IntentBindRecord i = bindings.get(filter);
760         if (i == null) {
761             i = new IntentBindRecord(this, filter);
762             bindings.put(filter, i);
763         }
764         AppBindRecord a = i.apps.get(app);
765         if (a != null) {
766             return a;
767         }
768         a = new AppBindRecord(this, i, app);
769         i.apps.put(app, a);
770         return a;
771     }
772 
hasAutoCreateConnections()773     public boolean hasAutoCreateConnections() {
774         // XXX should probably keep a count of the number of auto-create
775         // connections directly in the service.
776         for (int conni=connections.size()-1; conni>=0; conni--) {
777             ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
778             for (int i=0; i<cr.size(); i++) {
779                 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
780                     return true;
781                 }
782             }
783         }
784         return false;
785     }
786 
updateWhitelistManager()787     public void updateWhitelistManager() {
788         whitelistManager = false;
789         for (int conni=connections.size()-1; conni>=0; conni--) {
790             ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
791             for (int i=0; i<cr.size(); i++) {
792                 if ((cr.get(i).flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
793                     whitelistManager = true;
794                     return;
795                 }
796             }
797         }
798     }
799 
resetRestartCounter()800     public void resetRestartCounter() {
801         restartCount = 0;
802         restartDelay = 0;
803         restartTime = 0;
804     }
805 
findDeliveredStart(int id, boolean taskRemoved, boolean remove)806     public StartItem findDeliveredStart(int id, boolean taskRemoved, boolean remove) {
807         final int N = deliveredStarts.size();
808         for (int i=0; i<N; i++) {
809             StartItem si = deliveredStarts.get(i);
810             if (si.id == id && si.taskRemoved == taskRemoved) {
811                 if (remove) deliveredStarts.remove(i);
812                 return si;
813             }
814         }
815 
816         return null;
817     }
818 
getLastStartId()819     public int getLastStartId() {
820         return lastStartId;
821     }
822 
makeNextStartId()823     public int makeNextStartId() {
824         lastStartId++;
825         if (lastStartId < 1) {
826             lastStartId = 1;
827         }
828         return lastStartId;
829     }
830 
postNotification()831     public void postNotification() {
832         final int appUid = appInfo.uid;
833         final int appPid = app.pid;
834         if (foregroundId != 0 && foregroundNoti != null) {
835             // Do asynchronous communication with notification manager to
836             // avoid deadlocks.
837             final String localPackageName = packageName;
838             final int localForegroundId = foregroundId;
839             final Notification _foregroundNoti = foregroundNoti;
840             final ServiceRecord record = this;
841             ams.mHandler.post(new Runnable() {
842                 public void run() {
843                     NotificationManagerInternal nm = LocalServices.getService(
844                             NotificationManagerInternal.class);
845                     if (nm == null) {
846                         return;
847                     }
848                     Notification localForegroundNoti = _foregroundNoti;
849                     try {
850                         if (localForegroundNoti.getSmallIcon() == null) {
851                             // It is not correct for the caller to not supply a notification
852                             // icon, but this used to be able to slip through, so for
853                             // those dirty apps we will create a notification clearly
854                             // blaming the app.
855                             Slog.v(TAG, "Attempted to start a foreground service ("
856                                     + shortInstanceName
857                                     + ") with a broken notification (no icon: "
858                                     + localForegroundNoti
859                                     + ")");
860 
861                             CharSequence appName = appInfo.loadLabel(
862                                     ams.mContext.getPackageManager());
863                             if (appName == null) {
864                                 appName = appInfo.packageName;
865                             }
866                             Context ctx = null;
867                             try {
868                                 ctx = ams.mContext.createPackageContextAsUser(
869                                         appInfo.packageName, 0, new UserHandle(userId));
870 
871                                 Notification.Builder notiBuilder = new Notification.Builder(ctx,
872                                         localForegroundNoti.getChannelId());
873 
874                                 // it's ugly, but it clearly identifies the app
875                                 notiBuilder.setSmallIcon(appInfo.icon);
876 
877                                 // mark as foreground
878                                 notiBuilder.setFlag(Notification.FLAG_FOREGROUND_SERVICE, true);
879 
880                                 Intent runningIntent = new Intent(
881                                         Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
882                                 runningIntent.setData(Uri.fromParts("package",
883                                         appInfo.packageName, null));
884                                 PendingIntent pi = PendingIntent.getActivityAsUser(ams.mContext, 0,
885                                         runningIntent, FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE, null,
886                                         UserHandle.of(userId));
887                                 notiBuilder.setColor(ams.mContext.getColor(
888                                         com.android.internal
889                                                 .R.color.system_notification_accent_color));
890                                 notiBuilder.setContentTitle(
891                                         ams.mContext.getString(
892                                                 com.android.internal.R.string
893                                                         .app_running_notification_title,
894                                                 appName));
895                                 notiBuilder.setContentText(
896                                         ams.mContext.getString(
897                                                 com.android.internal.R.string
898                                                         .app_running_notification_text,
899                                                 appName));
900                                 notiBuilder.setContentIntent(pi);
901 
902                                 localForegroundNoti = notiBuilder.build();
903                             } catch (PackageManager.NameNotFoundException e) {
904                             }
905                         }
906                         if (nm.getNotificationChannel(localPackageName, appUid,
907                                 localForegroundNoti.getChannelId()) == null) {
908                             int targetSdkVersion = Build.VERSION_CODES.O_MR1;
909                             try {
910                                 final ApplicationInfo applicationInfo =
911                                         ams.mContext.getPackageManager().getApplicationInfoAsUser(
912                                                 appInfo.packageName, 0, userId);
913                                 targetSdkVersion = applicationInfo.targetSdkVersion;
914                             } catch (PackageManager.NameNotFoundException e) {
915                             }
916                             if (targetSdkVersion >= Build.VERSION_CODES.O_MR1) {
917                                 throw new RuntimeException(
918                                         "invalid channel for service notification: "
919                                                 + foregroundNoti);
920                             }
921                         }
922                         if (localForegroundNoti.getSmallIcon() == null) {
923                             // Notifications whose icon is 0 are defined to not show
924                             // a notification.  We don't want to
925                             // just ignore it, we want to prevent the service from
926                             // being foreground.
927                             throw new RuntimeException("invalid service notification: "
928                                     + foregroundNoti);
929                         }
930                         nm.enqueueNotification(localPackageName, localPackageName,
931                                 appUid, appPid, null, localForegroundId, localForegroundNoti,
932                                 userId);
933 
934                         foregroundNoti = localForegroundNoti; // save it for amending next time
935                     } catch (RuntimeException e) {
936                         Slog.w(TAG, "Error showing notification for service", e);
937                         // If it gave us a garbage notification, it doesn't
938                         // get to be foreground.
939                         ams.mServices.killMisbehavingService(record,
940                                 appUid, appPid, localPackageName);
941                     }
942                 }
943             });
944         }
945     }
946 
cancelNotification()947     public void cancelNotification() {
948         // Do asynchronous communication with notification manager to
949         // avoid deadlocks.
950         final String localPackageName = packageName;
951         final int localForegroundId = foregroundId;
952         final int appUid = appInfo.uid;
953         final int appPid = app != null ? app.pid : 0;
954         ams.mHandler.post(new Runnable() {
955             public void run() {
956                 NotificationManagerInternal nm = LocalServices.getService(
957                         NotificationManagerInternal.class);
958                 if (nm == null) {
959                     return;
960                 }
961                 try {
962                     nm.cancelNotification(localPackageName, localPackageName, appUid, appPid,
963                             null, localForegroundId, userId);
964                 } catch (RuntimeException e) {
965                     Slog.w(TAG, "Error canceling notification for service", e);
966                 }
967             }
968         });
969     }
970 
stripForegroundServiceFlagFromNotification()971     public void stripForegroundServiceFlagFromNotification() {
972         if (foregroundId == 0) {
973             return;
974         }
975 
976         final int localForegroundId = foregroundId;
977         final int localUserId = userId;
978         final String localPackageName = packageName;
979 
980         // Do asynchronous communication with notification manager to
981         // avoid deadlocks.
982         ams.mHandler.post(new Runnable() {
983             @Override
984             public void run() {
985                 NotificationManagerInternal nmi = LocalServices.getService(
986                         NotificationManagerInternal.class);
987                 if (nmi == null) {
988                     return;
989                 }
990                 nmi.removeForegroundServiceFlagFromNotification(localPackageName, localForegroundId,
991                         localUserId);
992             }
993         });
994     }
995 
clearDeliveredStartsLocked()996     public void clearDeliveredStartsLocked() {
997         for (int i=deliveredStarts.size()-1; i>=0; i--) {
998             deliveredStarts.get(i).removeUriPermissionsLocked();
999         }
1000         deliveredStarts.clear();
1001     }
1002 
toString()1003     public String toString() {
1004         if (stringName != null) {
1005             return stringName;
1006         }
1007         StringBuilder sb = new StringBuilder(128);
1008         sb.append("ServiceRecord{")
1009             .append(Integer.toHexString(System.identityHashCode(this)))
1010             .append(" u").append(userId)
1011             .append(' ').append(shortInstanceName).append('}');
1012         return stringName = sb.toString();
1013     }
1014 
getComponentName()1015     public ComponentName getComponentName() {
1016         return name;
1017     }
1018 }
1019