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