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