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 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 169 UriPermissionOwner getUriPermissionsLocked() { 170 if (uriPermissions == null) { 171 uriPermissions = new UriPermissionOwner(sr.ams.mUgmInternal, this); 172 } 173 return uriPermissions; 174 } 175 176 void removeUriPermissionsLocked() { 177 if (uriPermissions != null) { 178 uriPermissions.removeUriPermissions(); 179 uriPermissions = null; 180 } 181 } 182 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 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 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 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 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 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 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 522 public void forceClearTracker() { 523 if (tracker != null) { 524 tracker.clearCurrentOwner(this, true); 525 tracker = null; 526 } 527 } 528 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 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 600 ArrayMap<IBinder, ArrayList<ConnectionRecord>> getConnections() { 601 return connections; 602 } 603 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 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 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 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 */ 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 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 */ 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 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 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 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 761 public void resetRestartCounter() { 762 restartCount = 0; 763 restartDelay = 0; 764 restartTime = 0; 765 } 766 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 780 public int getLastStartId() { 781 return lastStartId; 782 } 783 784 public int makeNextStartId() { 785 lastStartId++; 786 if (lastStartId < 1) { 787 lastStartId = 1; 788 } 789 return lastStartId; 790 } 791 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 ams.mHandler.post(new Runnable() { 802 public void run() { 803 NotificationManagerInternal nm = LocalServices.getService( 804 NotificationManagerInternal.class); 805 if (nm == null) { 806 return; 807 } 808 Notification localForegroundNoti = _foregroundNoti; 809 try { 810 if (localForegroundNoti.getSmallIcon() == null) { 811 // It is not correct for the caller to not supply a notification 812 // icon, but this used to be able to slip through, so for 813 // those dirty apps we will create a notification clearly 814 // blaming the app. 815 Slog.v(TAG, "Attempted to start a foreground service (" 816 + shortInstanceName 817 + ") with a broken notification (no icon: " 818 + localForegroundNoti 819 + ")"); 820 821 CharSequence appName = appInfo.loadLabel( 822 ams.mContext.getPackageManager()); 823 if (appName == null) { 824 appName = appInfo.packageName; 825 } 826 Context ctx = null; 827 try { 828 ctx = ams.mContext.createPackageContextAsUser( 829 appInfo.packageName, 0, new UserHandle(userId)); 830 831 Notification.Builder notiBuilder = new Notification.Builder(ctx, 832 localForegroundNoti.getChannelId()); 833 834 // it's ugly, but it clearly identifies the app 835 notiBuilder.setSmallIcon(appInfo.icon); 836 837 // mark as foreground 838 notiBuilder.setFlag(Notification.FLAG_FOREGROUND_SERVICE, true); 839 840 Intent runningIntent = new Intent( 841 Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 842 runningIntent.setData(Uri.fromParts("package", 843 appInfo.packageName, null)); 844 PendingIntent pi = PendingIntent.getActivityAsUser(ams.mContext, 0, 845 runningIntent, PendingIntent.FLAG_UPDATE_CURRENT, null, 846 UserHandle.of(userId)); 847 notiBuilder.setColor(ams.mContext.getColor( 848 com.android.internal 849 .R.color.system_notification_accent_color)); 850 notiBuilder.setContentTitle( 851 ams.mContext.getString( 852 com.android.internal.R.string 853 .app_running_notification_title, 854 appName)); 855 notiBuilder.setContentText( 856 ams.mContext.getString( 857 com.android.internal.R.string 858 .app_running_notification_text, 859 appName)); 860 notiBuilder.setContentIntent(pi); 861 862 localForegroundNoti = notiBuilder.build(); 863 } catch (PackageManager.NameNotFoundException e) { 864 } 865 } 866 if (nm.getNotificationChannel(localPackageName, appUid, 867 localForegroundNoti.getChannelId()) == null) { 868 int targetSdkVersion = Build.VERSION_CODES.O_MR1; 869 try { 870 final ApplicationInfo applicationInfo = 871 ams.mContext.getPackageManager().getApplicationInfoAsUser( 872 appInfo.packageName, 0, userId); 873 targetSdkVersion = applicationInfo.targetSdkVersion; 874 } catch (PackageManager.NameNotFoundException e) { 875 } 876 if (targetSdkVersion >= Build.VERSION_CODES.O_MR1) { 877 throw new RuntimeException( 878 "invalid channel for service notification: " 879 + foregroundNoti); 880 } 881 } 882 if (localForegroundNoti.getSmallIcon() == null) { 883 // Notifications whose icon is 0 are defined to not show 884 // a notification, silently ignoring it. We don't want to 885 // just ignore it, we want to prevent the service from 886 // being foreground. 887 throw new RuntimeException("invalid service notification: " 888 + foregroundNoti); 889 } 890 nm.enqueueNotification(localPackageName, localPackageName, 891 appUid, appPid, null, localForegroundId, localForegroundNoti, 892 userId); 893 894 foregroundNoti = localForegroundNoti; // save it for amending next time 895 } catch (RuntimeException e) { 896 Slog.w(TAG, "Error showing notification for service", e); 897 // If it gave us a garbage notification, it doesn't 898 // get to be foreground. 899 ams.setServiceForeground(instanceName, ServiceRecord.this, 900 0, null, 0, 0); 901 ams.crashApplication(appUid, appPid, localPackageName, -1, 902 "Bad notification for startForeground: " + e); 903 } 904 } 905 }); 906 } 907 } 908 909 public void cancelNotification() { 910 // Do asynchronous communication with notification manager to 911 // avoid deadlocks. 912 final String localPackageName = packageName; 913 final int localForegroundId = foregroundId; 914 ams.mHandler.post(new Runnable() { 915 public void run() { 916 INotificationManager inm = NotificationManager.getService(); 917 if (inm == null) { 918 return; 919 } 920 try { 921 inm.cancelNotificationWithTag(localPackageName, null, 922 localForegroundId, userId); 923 } catch (RuntimeException e) { 924 Slog.w(TAG, "Error canceling notification for service", e); 925 } catch (RemoteException e) { 926 } 927 } 928 }); 929 } 930 931 public void stripForegroundServiceFlagFromNotification() { 932 if (foregroundId == 0) { 933 return; 934 } 935 936 final int localForegroundId = foregroundId; 937 final int localUserId = userId; 938 final String localPackageName = packageName; 939 940 // Do asynchronous communication with notification manager to 941 // avoid deadlocks. 942 ams.mHandler.post(new Runnable() { 943 @Override 944 public void run() { 945 NotificationManagerInternal nmi = LocalServices.getService( 946 NotificationManagerInternal.class); 947 if (nmi == null) { 948 return; 949 } 950 nmi.removeForegroundServiceFlagFromNotification(localPackageName, localForegroundId, 951 localUserId); 952 } 953 }); 954 } 955 956 public void clearDeliveredStartsLocked() { 957 for (int i=deliveredStarts.size()-1; i>=0; i--) { 958 deliveredStarts.get(i).removeUriPermissionsLocked(); 959 } 960 deliveredStarts.clear(); 961 } 962 963 public String toString() { 964 if (stringName != null) { 965 return stringName; 966 } 967 StringBuilder sb = new StringBuilder(128); 968 sb.append("ServiceRecord{") 969 .append(Integer.toHexString(System.identityHashCode(this))) 970 .append(" u").append(userId) 971 .append(' ').append(shortInstanceName).append('}'); 972 return stringName = sb.toString(); 973 } 974 975 public ComponentName getComponentName() { 976 return name; 977 } 978 } 979