• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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.ProcessMemoryState.HOSTING_COMPONENT_TYPE_BOUND_SERVICE;
20 import static android.app.ProcessMemoryState.HOSTING_COMPONENT_TYPE_FOREGROUND_SERVICE;
21 
22 import static com.android.server.am.Flags.serviceBindingOomAdjPolicy;
23 
24 import android.annotation.Nullable;
25 import android.app.ActivityManager;
26 import android.content.Context;
27 import android.content.pm.ServiceInfo;
28 import android.os.IBinder;
29 import android.os.SystemClock;
30 import android.util.ArrayMap;
31 import android.util.ArraySet;
32 
33 import com.android.internal.annotations.GuardedBy;
34 import com.android.server.wm.WindowProcessController;
35 
36 import java.io.PrintWriter;
37 import java.util.ArrayList;
38 
39 /**
40  * The state info of all services in the process.
41  */
42 final class ProcessServiceRecord {
43     /**
44      * Are there any client services with activities?
45      */
46     private boolean mHasClientActivities;
47 
48     /**
49      * Running any services that are foreground?
50      */
51     private boolean mHasForegroundServices;
52 
53     /**
54      * Last reported state of whether it's running any services that are foreground.
55      */
56     private boolean mRepHasForegroundServices;
57 
58     /**
59      * Running any services that are almost perceptible (started with
60      * {@link Context#BIND_ALMOST_PERCEPTIBLE} while the app was on TOP)?
61      */
62     private boolean mHasTopStartedAlmostPerceptibleServices;
63 
64     /**
65      * The latest value of {@link ServiceRecord#lastTopAlmostPerceptibleBindRequestUptimeMs} among
66      * the currently running services.
67      */
68     private long mLastTopStartedAlmostPerceptibleBindRequestUptimeMs;
69 
70     /**
71      * Service that applied current connectionGroup/Importance.
72      */
73     private ServiceRecord mConnectionService;
74 
75     /**
76      * Last group set by a connection.
77      */
78     private int mConnectionGroup;
79 
80     /**
81      * Last importance set by a connection.
82      */
83     private int mConnectionImportance;
84 
85     /**
86      * The OR'ed foreground service types that are running on this process.
87      * Note, because TYPE_NONE (==0) is also a valid type for pre-U apps, this field doesn't tell
88      * if the process has any TYPE_NONE FGS or not, but {@link #mHasTypeNoneFgs} will be set
89      * in that case.
90      */
91     private int mFgServiceTypes;
92 
93     /**
94      * Whether the process has any foreground services of TYPE_NONE running.
95      * @see #mFgServiceTypes
96      */
97     private boolean mHasTypeNoneFgs;
98 
99     /**
100      * Last reported foreground service types.
101      */
102     private int mRepFgServiceTypes;
103 
104     /**
105      * Bound using BIND_ABOVE_CLIENT, so want to be lower.
106      */
107     private boolean mHasAboveClient;
108 
109     /**
110      * Bound using BIND_TREAT_LIKE_ACTIVITY.
111      */
112     private boolean mTreatLikeActivity;
113 
114     /**
115      * Do we need to be executing services in the foreground?
116      */
117     private boolean mExecServicesFg;
118 
119     /**
120      * App is allowed to manage allowlists such as temporary Power Save mode allowlist.
121      */
122     boolean mAllowlistManager;
123 
124     /**
125      * All ServiceRecord running in this process.
126      */
127     final ArraySet<ServiceRecord> mServices = new ArraySet<>();
128 
129     /**
130      * Services that are currently executing code (need to remain foreground).
131      */
132     private final ArraySet<ServiceRecord> mExecutingServices = new ArraySet<>();
133 
134     /**
135      * All ConnectionRecord this process holds.
136      */
137     private final ArraySet<ConnectionRecord> mConnections = new ArraySet<>();
138 
139     /**
140      * All ConnectionRecord this process holds indirectly to SDK sandbox processes.
141      */
142     private @Nullable ArraySet<ConnectionRecord> mSdkSandboxConnections;
143 
144     /**
145      * A set of UIDs of all bound clients.
146      */
147     private ArraySet<Integer> mBoundClientUids = new ArraySet<>();
148 
149     /**
150      * The process should schedule a service timeout timer but haven't done so.
151      */
152     private boolean mScheduleServiceTimeoutPending;
153 
154     final ProcessRecord mApp;
155 
156     private final ActivityManagerService mService;
157 
ProcessServiceRecord(ProcessRecord app)158     ProcessServiceRecord(ProcessRecord app) {
159         mApp = app;
160         mService = app.mService;
161     }
162 
setHasClientActivities(boolean hasClientActivities)163     void setHasClientActivities(boolean hasClientActivities) {
164         mHasClientActivities = hasClientActivities;
165         mApp.getWindowProcessController().setHasClientActivities(hasClientActivities);
166     }
167 
hasClientActivities()168     boolean hasClientActivities() {
169         return mHasClientActivities;
170     }
171 
setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes, boolean hasTypeNoneFgs)172     void setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes,
173             boolean hasTypeNoneFgs) {
174         // hasForegroundServices should be the same as "either it has any FGS types, or none types".
175         // We still take this as a parameter because it's used in the callsite...
176         if (ActivityManagerDebugConfig.DEBUG_SERVICE
177                 && hasForegroundServices != ((fgServiceTypes != 0) || hasTypeNoneFgs)) {
178             throw new IllegalStateException("hasForegroundServices mismatch");
179         }
180 
181         mHasForegroundServices = hasForegroundServices;
182         mFgServiceTypes = fgServiceTypes;
183         mHasTypeNoneFgs = hasTypeNoneFgs;
184         mApp.getWindowProcessController().setHasForegroundServices(hasForegroundServices);
185         if (hasForegroundServices) {
186             mApp.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_FOREGROUND_SERVICE);
187         } else {
188             mApp.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_FOREGROUND_SERVICE);
189         }
190     }
191 
192     /**
193      * @return true if this process has any foreground services (even timed-out short-FGS)
194      */
hasForegroundServices()195     boolean hasForegroundServices() {
196         return mHasForegroundServices;
197     }
198 
setHasReportedForegroundServices(boolean hasForegroundServices)199     void setHasReportedForegroundServices(boolean hasForegroundServices) {
200         mRepHasForegroundServices = hasForegroundServices;
201     }
202 
hasReportedForegroundServices()203     boolean hasReportedForegroundServices() {
204         return mRepHasForegroundServices;
205     }
206 
207     /**
208      * Returns the FGS types, but it doesn't tell if the types include "NONE" or not, use
209      * {@link #hasForegroundServices()}
210      */
getForegroundServiceTypes()211     int getForegroundServiceTypes() {
212         return mHasForegroundServices ? mFgServiceTypes : 0;
213     }
214 
areForegroundServiceTypesSame(@erviceInfo.ForegroundServiceType int types, boolean hasTypeNoneFgs)215     boolean areForegroundServiceTypesSame(@ServiceInfo.ForegroundServiceType int types,
216             boolean hasTypeNoneFgs) {
217         return ((getForegroundServiceTypes() & types) == types)
218                 && (mHasTypeNoneFgs == hasTypeNoneFgs);
219     }
220 
221     /**
222      * @return true if the fgs types includes any of the given types.
223      * (wouldn't work for TYPE_NONE, which is 0)
224      */
containsAnyForegroundServiceTypes(@erviceInfo.ForegroundServiceType int types)225     boolean containsAnyForegroundServiceTypes(@ServiceInfo.ForegroundServiceType int types) {
226         return (getForegroundServiceTypes() & types) != 0;
227     }
228 
229     /**
230      * @return true if the process has any FGS that are _not_ a "short" FGS.
231      */
hasNonShortForegroundServices()232     boolean hasNonShortForegroundServices() {
233         if (!mHasForegroundServices) {
234             return false; // Process has no FGS running.
235         }
236         // Does the process has any FGS of TYPE_NONE?
237         if (mHasTypeNoneFgs) {
238             return true;
239         }
240         // If not, we can just check mFgServiceTypes.
241         return mFgServiceTypes != ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE;
242     }
243 
244     /**
245      * @return if this process:
246      * - has at least one short-FGS
247      * - has no other types of FGS
248      * - and all the short-FGSes are procstate-timed out.
249      */
areAllShortForegroundServicesProcstateTimedOut(long nowUptime)250     boolean areAllShortForegroundServicesProcstateTimedOut(long nowUptime) {
251         if (!mHasForegroundServices) { // Process has no FGS?
252             return false;
253         }
254         if (hasNonShortForegroundServices()) {  // Any non-short FGS running?
255             return false;
256         }
257         // Now we need to look at all short-FGS within the process and see if all of them are
258         // procstate-timed-out or not.
259         return !hasUndemotedShortForegroundService(nowUptime);
260     }
261 
hasUndemotedShortForegroundService(long nowUptime)262     boolean hasUndemotedShortForegroundService(long nowUptime) {
263         for (int i = mServices.size() - 1; i >= 0; i--) {
264             final ServiceRecord sr = mServices.valueAt(i);
265             if (!sr.isShortFgs() || !sr.hasShortFgsInfo()) {
266                 continue;
267             }
268             if (sr.getShortFgsInfo().getProcStateDemoteTime() >= nowUptime) {
269                 // This short fgs has not timed out yet.
270                 return true;
271             }
272         }
273         return false;
274     }
275 
276 
getReportedForegroundServiceTypes()277     int getReportedForegroundServiceTypes() {
278         return mRepFgServiceTypes;
279     }
280 
setReportedForegroundServiceTypes(int foregroundServiceTypes)281     void setReportedForegroundServiceTypes(int foregroundServiceTypes) {
282         mRepFgServiceTypes = foregroundServiceTypes;
283     }
284 
getNumForegroundServices()285     int getNumForegroundServices() {
286         int count = 0;
287         for (int i = 0, serviceCount = mServices.size(); i < serviceCount; i++) {
288             if (mServices.valueAt(i).isForeground) {
289                 count++;
290             }
291         }
292         return count;
293     }
294 
updateHasTopStartedAlmostPerceptibleServices()295     void updateHasTopStartedAlmostPerceptibleServices() {
296         mHasTopStartedAlmostPerceptibleServices = false;
297         mLastTopStartedAlmostPerceptibleBindRequestUptimeMs = 0;
298         for (int s = mServices.size() - 1; s >= 0; --s) {
299             final ServiceRecord sr = mServices.valueAt(s);
300             mLastTopStartedAlmostPerceptibleBindRequestUptimeMs = Math.max(
301                     mLastTopStartedAlmostPerceptibleBindRequestUptimeMs,
302                     sr.lastTopAlmostPerceptibleBindRequestUptimeMs);
303             if (!mHasTopStartedAlmostPerceptibleServices && isAlmostPerceptible(sr)) {
304                 mHasTopStartedAlmostPerceptibleServices = true;
305             }
306         }
307     }
308 
isAlmostPerceptible(ServiceRecord record)309     private boolean isAlmostPerceptible(ServiceRecord record) {
310         if (record.lastTopAlmostPerceptibleBindRequestUptimeMs <= 0) {
311             return false;
312         }
313         final ArrayMap<IBinder, ArrayList<ConnectionRecord>> serviceConnections =
314                 record.getConnections();
315         for (int m = serviceConnections.size() - 1; m >= 0; --m) {
316             final ArrayList<ConnectionRecord> clist = serviceConnections.valueAt(m);
317 
318             for (int c = clist.size() - 1; c >= 0; --c) {
319                 final ConnectionRecord cr = clist.get(c);
320                 if (cr.hasFlag(Context.BIND_ALMOST_PERCEPTIBLE)) {
321                     return true;
322                 }
323             }
324         }
325         return false;
326     }
327 
hasTopStartedAlmostPerceptibleServices()328     boolean hasTopStartedAlmostPerceptibleServices() {
329         return mHasTopStartedAlmostPerceptibleServices
330                 || (mLastTopStartedAlmostPerceptibleBindRequestUptimeMs > 0
331                 && SystemClock.uptimeMillis() - mLastTopStartedAlmostPerceptibleBindRequestUptimeMs
332                 < mService.mConstants.mServiceBindAlmostPerceptibleTimeoutMs);
333     }
334 
getConnectionService()335     ServiceRecord getConnectionService() {
336         return mConnectionService;
337     }
338 
setConnectionService(ServiceRecord connectionService)339     void setConnectionService(ServiceRecord connectionService) {
340         mConnectionService = connectionService;
341     }
342 
getConnectionGroup()343     int getConnectionGroup() {
344         return mConnectionGroup;
345     }
346 
setConnectionGroup(int connectionGroup)347     void setConnectionGroup(int connectionGroup) {
348         mConnectionGroup = connectionGroup;
349     }
350 
getConnectionImportance()351     int getConnectionImportance() {
352         return mConnectionImportance;
353     }
354 
setConnectionImportance(int connectionImportance)355     void setConnectionImportance(int connectionImportance) {
356         mConnectionImportance = connectionImportance;
357     }
358 
updateHasAboveClientLocked()359     void updateHasAboveClientLocked() {
360         mHasAboveClient = false;
361         for (int i = mConnections.size() - 1; i >= 0; i--) {
362             ConnectionRecord cr = mConnections.valueAt(i);
363 
364             final boolean isSameProcess = cr.binding.service.app != null
365                     && cr.binding.service.app.mServices == this;
366             if (!isSameProcess && cr.hasFlag(Context.BIND_ABOVE_CLIENT)) {
367                 mHasAboveClient = true;
368                 break;
369             }
370         }
371     }
372 
setHasAboveClient(boolean hasAboveClient)373     void setHasAboveClient(boolean hasAboveClient) {
374         mHasAboveClient = hasAboveClient;
375     }
376 
hasAboveClient()377     boolean hasAboveClient() {
378         return mHasAboveClient;
379     }
380 
modifyRawOomAdj(int adj)381     int modifyRawOomAdj(int adj) {
382         if (mHasAboveClient) {
383             // If this process has bound to any services with BIND_ABOVE_CLIENT,
384             // then we need to drop its adjustment to be lower than the service's
385             // in order to honor the request.  We want to drop it by one adjustment
386             // level...  but there is special meaning applied to various levels so
387             // we will skip some of them.
388             if (adj < ProcessList.FOREGROUND_APP_ADJ) {
389                 // System process will not get dropped, ever
390             } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
391                 adj = ProcessList.VISIBLE_APP_ADJ;
392             } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
393                 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
394             } else if (adj < ProcessList.PERCEPTIBLE_LOW_APP_ADJ) {
395                 adj = ProcessList.PERCEPTIBLE_LOW_APP_ADJ;
396             } else if (Flags.addModifyRawOomAdjServiceLevel() && adj < ProcessList.SERVICE_ADJ) {
397                 adj = ProcessList.SERVICE_ADJ;
398             } else if (adj < ProcessList.CACHED_APP_MIN_ADJ) {
399                 adj = ProcessList.CACHED_APP_MIN_ADJ;
400             } else if (adj < ProcessList.CACHED_APP_MAX_ADJ) {
401                 adj++;
402             }
403         }
404         return adj;
405     }
406 
isTreatedLikeActivity()407     boolean isTreatedLikeActivity() {
408         return mTreatLikeActivity;
409     }
410 
setTreatLikeActivity(boolean treatLikeActivity)411     void setTreatLikeActivity(boolean treatLikeActivity) {
412         mTreatLikeActivity = treatLikeActivity;
413     }
414 
shouldExecServicesFg()415     boolean shouldExecServicesFg() {
416         return mExecServicesFg;
417     }
418 
setExecServicesFg(boolean execServicesFg)419     void setExecServicesFg(boolean execServicesFg) {
420         mExecServicesFg = execServicesFg;
421     }
422 
423     /**
424      * Records a service as running in the process. Note that this method does not actually start
425      * the service, but records the service as started for bookkeeping.
426      *
427      * @return true if the service was added, false otherwise.
428      */
startService(ServiceRecord record)429     boolean startService(ServiceRecord record) {
430         if (record == null) {
431             return false;
432         }
433         boolean added = mServices.add(record);
434         if (added && record.serviceInfo != null) {
435             mApp.getWindowProcessController().onServiceStarted(record.serviceInfo);
436             updateHostingComonentTypeForBindingsLocked();
437         }
438         if (record.lastTopAlmostPerceptibleBindRequestUptimeMs > 0) {
439             mLastTopStartedAlmostPerceptibleBindRequestUptimeMs = Math.max(
440                     mLastTopStartedAlmostPerceptibleBindRequestUptimeMs,
441                     record.lastTopAlmostPerceptibleBindRequestUptimeMs);
442             if (!mHasTopStartedAlmostPerceptibleServices) {
443                 mHasTopStartedAlmostPerceptibleServices = isAlmostPerceptible(record);
444             }
445         }
446         return added;
447     }
448 
449     /**
450      * Records a service as stopped. Note that like {@link #startService(ServiceRecord)} this method
451      * does not actually stop the service, but records the service as stopped for bookkeeping.
452      *
453      * @return true if the service was removed, false otherwise.
454      */
stopService(ServiceRecord record)455     boolean stopService(ServiceRecord record) {
456         final boolean removed = mServices.remove(record);
457         if (record.lastTopAlmostPerceptibleBindRequestUptimeMs > 0) {
458             updateHasTopStartedAlmostPerceptibleServices();
459         }
460         if (removed) {
461             updateHostingComonentTypeForBindingsLocked();
462         }
463         return removed;
464     }
465 
466     /**
467      * The same as calling {@link #stopService(ServiceRecord)} on all current running services.
468      */
stopAllServices()469     void stopAllServices() {
470         mServices.clear();
471         updateHasTopStartedAlmostPerceptibleServices();
472     }
473 
474     /**
475      * Returns the number of services added with {@link #startService(ServiceRecord)} and not yet
476      * removed by a call to {@link #stopService(ServiceRecord)} or {@link #stopAllServices()}.
477      *
478      * @see #startService(ServiceRecord)
479      * @see #stopService(ServiceRecord)
480      */
numberOfRunningServices()481     int numberOfRunningServices() {
482         return mServices.size();
483     }
484 
485     /**
486      * Returns the service at the specified {@code index}.
487      *
488      * @see #numberOfRunningServices()
489      */
getRunningServiceAt(int index)490     ServiceRecord getRunningServiceAt(int index) {
491         return mServices.valueAt(index);
492     }
493 
startExecutingService(ServiceRecord service)494     void startExecutingService(ServiceRecord service) {
495         mExecutingServices.add(service);
496     }
497 
stopExecutingService(ServiceRecord service)498     void stopExecutingService(ServiceRecord service) {
499         mExecutingServices.remove(service);
500     }
501 
stopAllExecutingServices()502     void stopAllExecutingServices() {
503         mExecutingServices.clear();
504     }
505 
getExecutingServiceAt(int index)506     ServiceRecord getExecutingServiceAt(int index) {
507         return mExecutingServices.valueAt(index);
508     }
509 
numberOfExecutingServices()510     int numberOfExecutingServices() {
511         return mExecutingServices.size();
512     }
513 
addConnection(ConnectionRecord connection)514     void addConnection(ConnectionRecord connection) {
515         mConnections.add(connection);
516         addSdkSandboxConnectionIfNecessary(connection);
517     }
518 
removeConnection(ConnectionRecord connection)519     void removeConnection(ConnectionRecord connection) {
520         mConnections.remove(connection);
521         removeSdkSandboxConnectionIfNecessary(connection);
522     }
523 
removeAllConnections()524     void removeAllConnections() {
525         for (int i = 0, size = mConnections.size(); i < size; i++) {
526             removeSdkSandboxConnectionIfNecessary(mConnections.valueAt(i));
527         }
528         mConnections.clear();
529     }
530 
getConnectionAt(int index)531     ConnectionRecord getConnectionAt(int index) {
532         return mConnections.valueAt(index);
533     }
534 
numberOfConnections()535     int numberOfConnections() {
536         return mConnections.size();
537     }
538 
addSdkSandboxConnectionIfNecessary(ConnectionRecord connection)539     private void addSdkSandboxConnectionIfNecessary(ConnectionRecord connection) {
540         final ProcessRecord attributedClient = connection.binding.attributedClient;
541         if (attributedClient != null && connection.binding.service.isSdkSandbox) {
542             if (attributedClient.mServices.mSdkSandboxConnections == null) {
543                 attributedClient.mServices.mSdkSandboxConnections = new ArraySet<>();
544             }
545             attributedClient.mServices.mSdkSandboxConnections.add(connection);
546         }
547     }
548 
removeSdkSandboxConnectionIfNecessary(ConnectionRecord connection)549     private void removeSdkSandboxConnectionIfNecessary(ConnectionRecord connection) {
550         final ProcessRecord attributedClient = connection.binding.attributedClient;
551         if (attributedClient != null && connection.binding.service.isSdkSandbox) {
552             if (attributedClient.mServices.mSdkSandboxConnections != null) {
553                 attributedClient.mServices.mSdkSandboxConnections.remove(connection);
554             }
555         }
556     }
557 
removeAllSdkSandboxConnections()558     void removeAllSdkSandboxConnections() {
559         if (mSdkSandboxConnections != null) {
560             mSdkSandboxConnections.clear();
561         }
562     }
563 
getSdkSandboxConnectionAt(int index)564     ConnectionRecord getSdkSandboxConnectionAt(int index) {
565         return mSdkSandboxConnections != null ? mSdkSandboxConnections.valueAt(index) : null;
566     }
567 
numberOfSdkSandboxConnections()568     int numberOfSdkSandboxConnections() {
569         return mSdkSandboxConnections != null ? mSdkSandboxConnections.size() : 0;
570     }
571 
addBoundClientUid(int clientUid, String clientPackageName, long bindFlags)572     void addBoundClientUid(int clientUid, String clientPackageName, long bindFlags) {
573         mBoundClientUids.add(clientUid);
574         mApp.getWindowProcessController()
575                 .addBoundClientUid(clientUid, clientPackageName, bindFlags);
576     }
577 
updateBoundClientUids()578     void updateBoundClientUids() {
579         clearBoundClientUids();
580         if (mServices.isEmpty()) {
581             return;
582         }
583         // grab a set of clientUids of all mConnections of all services
584         final ArraySet<Integer> boundClientUids = new ArraySet<>();
585         final int serviceCount = mServices.size();
586         WindowProcessController controller = mApp.getWindowProcessController();
587         for (int j = 0; j < serviceCount; j++) {
588             final ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns =
589                     mServices.valueAt(j).getConnections();
590             final int size = conns.size();
591             for (int conni = 0; conni < size; conni++) {
592                 ArrayList<ConnectionRecord> c = conns.valueAt(conni);
593                 for (int i = 0; i < c.size(); i++) {
594                     ConnectionRecord cr = c.get(i);
595                     boundClientUids.add(cr.clientUid);
596                     controller.addBoundClientUid(cr.clientUid, cr.clientPackageName, cr.getFlags());
597                 }
598             }
599         }
600         mBoundClientUids = boundClientUids;
601     }
602 
addBoundClientUidsOfNewService(ServiceRecord sr)603     void addBoundClientUidsOfNewService(ServiceRecord sr) {
604         if (sr == null) {
605             return;
606         }
607         ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns = sr.getConnections();
608         for (int conni = conns.size() - 1; conni >= 0; conni--) {
609             ArrayList<ConnectionRecord> c = conns.valueAt(conni);
610             for (int i = 0; i < c.size(); i++) {
611                 ConnectionRecord cr = c.get(i);
612                 mBoundClientUids.add(cr.clientUid);
613                 mApp.getWindowProcessController()
614                         .addBoundClientUid(cr.clientUid, cr.clientPackageName, cr.getFlags());
615 
616             }
617         }
618     }
619 
clearBoundClientUids()620     void clearBoundClientUids() {
621         mBoundClientUids.clear();
622         mApp.getWindowProcessController().clearBoundClientUids();
623     }
624 
625     @GuardedBy("mService")
updateHostingComonentTypeForBindingsLocked()626     void updateHostingComonentTypeForBindingsLocked() {
627         boolean hasBoundClient = false;
628         for (int i = numberOfRunningServices() - 1; i >= 0; i--) {
629             final ServiceRecord sr = getRunningServiceAt(i);
630             if (sr != null && !sr.getConnections().isEmpty()) {
631                 hasBoundClient = true;
632                 break;
633             }
634         }
635         if (hasBoundClient) {
636             mApp.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE);
637         } else {
638             mApp.mProfile.clearHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE);
639         }
640     }
641 
642     @GuardedBy("mService")
incServiceCrashCountLocked(long now)643     boolean incServiceCrashCountLocked(long now) {
644         final boolean procIsBoundForeground = mApp.mState.getCurProcState()
645                 == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE;
646         boolean tryAgain = false;
647         // Bump up the crash count of any services currently running in the proc.
648         for (int i = numberOfRunningServices() - 1; i >= 0; i--) {
649             // Any services running in the application need to be placed
650             // back in the pending list.
651             ServiceRecord sr = getRunningServiceAt(i);
652             // If the service was restarted a while ago, then reset crash count, else increment it.
653             if (now > sr.restartTime + ActivityManagerConstants.MIN_CRASH_INTERVAL) {
654                 sr.crashCount = 1;
655             } else {
656                 sr.crashCount++;
657             }
658             // Allow restarting for started or bound foreground services that are crashing.
659             // This includes wallpapers.
660             if (sr.crashCount < mService.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
661                     && (sr.isForeground || procIsBoundForeground)) {
662                 tryAgain = true;
663             }
664         }
665         return tryAgain;
666     }
667 
668     @GuardedBy("mService")
onCleanupApplicationRecordLocked()669     void onCleanupApplicationRecordLocked() {
670         mTreatLikeActivity = false;
671         mHasAboveClient = false;
672         setHasClientActivities(false);
673     }
674 
675     @GuardedBy("mService")
noteScheduleServiceTimeoutPending(boolean pending)676     void noteScheduleServiceTimeoutPending(boolean pending) {
677         mScheduleServiceTimeoutPending = pending;
678     }
679 
680     @GuardedBy("mService")
isScheduleServiceTimeoutPending()681     boolean isScheduleServiceTimeoutPending() {
682         return mScheduleServiceTimeoutPending;
683     }
684 
onProcessUnfrozen()685     void onProcessUnfrozen() {
686         synchronized (mService) {
687             scheduleServiceTimeoutIfNeededLocked();
688         }
689     }
690 
onProcessFrozenCancelled()691     void onProcessFrozenCancelled() {
692         synchronized (mService) {
693             scheduleServiceTimeoutIfNeededLocked();
694         }
695     }
696 
697     @GuardedBy("mService")
scheduleServiceTimeoutIfNeededLocked()698     private void scheduleServiceTimeoutIfNeededLocked() {
699         if (!serviceBindingOomAdjPolicy()) {
700             return;
701         }
702         if (mScheduleServiceTimeoutPending && mExecutingServices.size() > 0) {
703             mService.mServices.scheduleServiceTimeoutLocked(mApp);
704             // We'll need to reset the executingStart since the app was frozen.
705             final long now = SystemClock.uptimeMillis();
706             for (int i = 0, size = mExecutingServices.size(); i < size; i++) {
707                 mExecutingServices.valueAt(i).executingStart = now;
708             }
709         }
710     }
711 
dump(PrintWriter pw, String prefix, long nowUptime)712     void dump(PrintWriter pw, String prefix, long nowUptime) {
713         if (mHasForegroundServices || mApp.mState.getForcingToImportant() != null) {
714             pw.print(prefix); pw.print("mHasForegroundServices="); pw.print(mHasForegroundServices);
715             pw.print(" forcingToImportant="); pw.println(mApp.mState.getForcingToImportant());
716         }
717         if (mHasTopStartedAlmostPerceptibleServices
718                 || mLastTopStartedAlmostPerceptibleBindRequestUptimeMs > 0) {
719             pw.print(prefix); pw.print("mHasTopStartedAlmostPerceptibleServices=");
720             pw.print(mHasTopStartedAlmostPerceptibleServices);
721             pw.print(" mLastTopStartedAlmostPerceptibleBindRequestUptimeMs=");
722             pw.println(mLastTopStartedAlmostPerceptibleBindRequestUptimeMs);
723         }
724         if (mHasClientActivities || mHasAboveClient || mTreatLikeActivity) {
725             pw.print(prefix); pw.print("hasClientActivities="); pw.print(mHasClientActivities);
726             pw.print(" hasAboveClient="); pw.print(mHasAboveClient);
727             pw.print(" treatLikeActivity="); pw.println(mTreatLikeActivity);
728         }
729         if (mConnectionService != null || mConnectionGroup != 0) {
730             pw.print(prefix); pw.print("connectionGroup="); pw.print(mConnectionGroup);
731             pw.print(" Importance="); pw.print(mConnectionImportance);
732             pw.print(" Service="); pw.println(mConnectionService);
733         }
734         if (mAllowlistManager) {
735             pw.print(prefix); pw.print("allowlistManager="); pw.println(mAllowlistManager);
736         }
737         if (mServices.size() > 0) {
738             pw.print(prefix); pw.println("Services:");
739             for (int i = 0, size = mServices.size(); i < size; i++) {
740                 pw.print(prefix); pw.print("  - "); pw.println(mServices.valueAt(i));
741             }
742         }
743         if (mExecutingServices.size() > 0) {
744             pw.print(prefix); pw.print("Executing Services (fg=");
745             pw.print(mExecServicesFg); pw.println(")");
746             for (int i = 0, size = mExecutingServices.size(); i < size; i++) {
747                 pw.print(prefix); pw.print("  - "); pw.println(mExecutingServices.valueAt(i));
748             }
749         }
750         if (mConnections.size() > 0) {
751             pw.print(prefix); pw.println("mConnections:");
752             for (int i = 0, size = mConnections.size(); i < size; i++) {
753                 pw.print(prefix); pw.print("  - "); pw.println(mConnections.valueAt(i));
754             }
755         }
756         if (serviceBindingOomAdjPolicy()) {
757             pw.print(prefix);
758             pw.print("scheduleServiceTimeoutPending=");
759             pw.println(mScheduleServiceTimeoutPending);
760         }
761     }
762 }
763