1 /* 2 * Copyright (C) 2012 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.*; 20 21 import java.io.FileDescriptor; 22 import java.io.IOException; 23 import java.io.PrintWriter; 24 import java.io.StringWriter; 25 import java.util.ArrayList; 26 import java.util.HashSet; 27 import java.util.Iterator; 28 import java.util.List; 29 import java.util.Set; 30 31 import android.app.ActivityThread; 32 import android.app.AppOpsManager; 33 import android.os.Build; 34 import android.os.DeadObjectException; 35 import android.os.Handler; 36 import android.os.Looper; 37 import android.os.SystemProperties; 38 import android.os.TransactionTooLargeException; 39 import android.util.ArrayMap; 40 import android.util.ArraySet; 41 42 import com.android.internal.app.ProcessStats; 43 import com.android.internal.os.BatteryStatsImpl; 44 import com.android.internal.os.TransferPipe; 45 import com.android.internal.util.FastPrintWriter; 46 import com.android.server.am.ActivityManagerService.ItemMatcher; 47 import com.android.server.am.ActivityManagerService.NeededUriGrants; 48 49 import android.app.ActivityManager; 50 import android.app.AppGlobals; 51 import android.app.IApplicationThread; 52 import android.app.IServiceConnection; 53 import android.app.Notification; 54 import android.app.PendingIntent; 55 import android.app.Service; 56 import android.content.ComponentName; 57 import android.content.Context; 58 import android.content.Intent; 59 import android.content.pm.ApplicationInfo; 60 import android.content.pm.PackageManager; 61 import android.content.pm.ResolveInfo; 62 import android.content.pm.ServiceInfo; 63 import android.os.Binder; 64 import android.os.IBinder; 65 import android.os.Message; 66 import android.os.Process; 67 import android.os.RemoteException; 68 import android.os.SystemClock; 69 import android.os.UserHandle; 70 import android.util.EventLog; 71 import android.util.Slog; 72 import android.util.SparseArray; 73 import android.util.TimeUtils; 74 75 public final class ActiveServices { 76 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM; 77 private static final String TAG_MU = TAG + POSTFIX_MU; 78 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 79 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING; 80 81 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE; 82 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE; 83 84 private static final boolean LOG_SERVICE_START_STOP = false; 85 86 // How long we wait for a service to finish executing. 87 static final int SERVICE_TIMEOUT = 20*1000; 88 89 // How long we wait for a service to finish executing. 90 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10; 91 92 // How long a service needs to be running until restarting its process 93 // is no longer considered to be a relaunch of the service. 94 static final int SERVICE_RESTART_DURATION = 1*1000; 95 96 // How long a service needs to be running until it will start back at 97 // SERVICE_RESTART_DURATION after being killed. 98 static final int SERVICE_RESET_RUN_DURATION = 60*1000; 99 100 // Multiplying factor to increase restart duration time by, for each time 101 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION. 102 static final int SERVICE_RESTART_DURATION_FACTOR = 4; 103 104 // The minimum amount of time between restarting services that we allow. 105 // That is, when multiple services are restarting, we won't allow each 106 // to restart less than this amount of time from the last one. 107 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000; 108 109 // Maximum amount of time for there to be no activity on a service before 110 // we consider it non-essential and allow its process to go on the 111 // LRU background list. 112 static final int MAX_SERVICE_INACTIVITY = 30*60*1000; 113 114 // How long we wait for a background started service to stop itself before 115 // allowing the next pending start to run. 116 static final int BG_START_TIMEOUT = 15*1000; 117 118 final ActivityManagerService mAm; 119 120 // Maximum number of services that we allow to start in the background 121 // at the same time. 122 final int mMaxStartingBackground; 123 124 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>(); 125 126 /** 127 * All currently bound service connections. Keys are the IBinder of 128 * the client's IServiceConnection. 129 */ 130 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>(); 131 132 /** 133 * List of services that we have been asked to start, 134 * but haven't yet been able to. It is used to hold start requests 135 * while waiting for their corresponding application thread to get 136 * going. 137 */ 138 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>(); 139 140 /** 141 * List of services that are scheduled to restart following a crash. 142 */ 143 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>(); 144 145 /** 146 * List of services that are in the process of being destroyed. 147 */ 148 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>(); 149 150 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */ 151 private ArrayList<ServiceRecord> mTmpCollectionResults = null; 152 153 /** Amount of time to allow a last ANR message to exist before freeing the memory. */ 154 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours 155 156 String mLastAnrDump; 157 158 final Runnable mLastAnrDumpClearer = new Runnable() { 159 @Override public void run() { 160 synchronized (mAm) { 161 mLastAnrDump = null; 162 } 163 } 164 }; 165 166 /** 167 * Information about services for a single user. 168 */ 169 class ServiceMap extends Handler { 170 final int mUserId; 171 final ArrayMap<ComponentName, ServiceRecord> mServicesByName 172 = new ArrayMap<ComponentName, ServiceRecord>(); 173 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent 174 = new ArrayMap<Intent.FilterComparison, ServiceRecord>(); 175 176 final ArrayList<ServiceRecord> mDelayedStartList 177 = new ArrayList<ServiceRecord>(); 178 /* XXX eventually I'd like to have this based on processes instead of services. 179 * That is, if we try to start two services in a row both running in the same 180 * process, this should be one entry in mStartingBackground for that one process 181 * that remains until all services in it are done. 182 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap 183 = new ArrayMap<ProcessRecord, DelayingProcess>(); 184 final ArrayList<DelayingProcess> mStartingProcessList 185 = new ArrayList<DelayingProcess>(); 186 */ 187 188 final ArrayList<ServiceRecord> mStartingBackground 189 = new ArrayList<ServiceRecord>(); 190 191 static final int MSG_BG_START_TIMEOUT = 1; 192 ServiceMap(Looper looper, int userId)193 ServiceMap(Looper looper, int userId) { 194 super(looper); 195 mUserId = userId; 196 } 197 198 @Override handleMessage(Message msg)199 public void handleMessage(Message msg) { 200 switch (msg.what) { 201 case MSG_BG_START_TIMEOUT: { 202 synchronized (mAm) { 203 rescheduleDelayedStarts(); 204 } 205 } break; 206 } 207 } 208 ensureNotStartingBackground(ServiceRecord r)209 void ensureNotStartingBackground(ServiceRecord r) { 210 if (mStartingBackground.remove(r)) { 211 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 212 "No longer background starting: " + r); 213 rescheduleDelayedStarts(); 214 } 215 if (mDelayedStartList.remove(r)) { 216 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r); 217 } 218 } 219 rescheduleDelayedStarts()220 void rescheduleDelayedStarts() { 221 removeMessages(MSG_BG_START_TIMEOUT); 222 final long now = SystemClock.uptimeMillis(); 223 for (int i=0, N=mStartingBackground.size(); i<N; i++) { 224 ServiceRecord r = mStartingBackground.get(i); 225 if (r.startingBgTimeout <= now) { 226 Slog.i(TAG, "Waited long enough for: " + r); 227 mStartingBackground.remove(i); 228 N--; 229 i--; 230 } 231 } 232 while (mDelayedStartList.size() > 0 233 && mStartingBackground.size() < mMaxStartingBackground) { 234 ServiceRecord r = mDelayedStartList.remove(0); 235 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 236 "REM FR DELAY LIST (exec next): " + r); 237 if (r.pendingStarts.size() <= 0) { 238 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested 239 + " delayedStop=" + r.delayedStop); 240 } 241 if (DEBUG_DELAYED_SERVICE) { 242 if (mDelayedStartList.size() > 0) { 243 Slog.v(TAG_SERVICE, "Remaining delayed list:"); 244 for (int i=0; i<mDelayedStartList.size(); i++) { 245 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i)); 246 } 247 } 248 } 249 r.delayed = false; 250 try { 251 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true); 252 } catch (TransactionTooLargeException e) { 253 // Ignore, nobody upstack cares. 254 } 255 } 256 if (mStartingBackground.size() > 0) { 257 ServiceRecord next = mStartingBackground.get(0); 258 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now; 259 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next 260 + ", can delay others up to " + when); 261 Message msg = obtainMessage(MSG_BG_START_TIMEOUT); 262 sendMessageAtTime(msg, when); 263 } 264 if (mStartingBackground.size() < mMaxStartingBackground) { 265 mAm.backgroundServicesFinishedLocked(mUserId); 266 } 267 } 268 } 269 ActiveServices(ActivityManagerService service)270 public ActiveServices(ActivityManagerService service) { 271 mAm = service; 272 int maxBg = 0; 273 try { 274 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0")); 275 } catch(RuntimeException e) { 276 } 277 mMaxStartingBackground = maxBg > 0 278 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8; 279 } 280 getServiceByName(ComponentName name, int callingUser)281 ServiceRecord getServiceByName(ComponentName name, int callingUser) { 282 // TODO: Deal with global services 283 if (DEBUG_MU) 284 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser); 285 return getServiceMap(callingUser).mServicesByName.get(name); 286 } 287 hasBackgroundServices(int callingUser)288 boolean hasBackgroundServices(int callingUser) { 289 ServiceMap smap = mServiceMap.get(callingUser); 290 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false; 291 } 292 getServiceMap(int callingUser)293 private ServiceMap getServiceMap(int callingUser) { 294 ServiceMap smap = mServiceMap.get(callingUser); 295 if (smap == null) { 296 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser); 297 mServiceMap.put(callingUser, smap); 298 } 299 return smap; 300 } 301 getServices(int callingUser)302 ArrayMap<ComponentName, ServiceRecord> getServices(int callingUser) { 303 return getServiceMap(callingUser).mServicesByName; 304 } 305 startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int callingPid, int callingUid, String callingPackage, int userId)306 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType, 307 int callingPid, int callingUid, String callingPackage, int userId) 308 throws TransactionTooLargeException { 309 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service 310 + " type=" + resolvedType + " args=" + service.getExtras()); 311 312 final boolean callerFg; 313 if (caller != null) { 314 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); 315 if (callerApp == null) { 316 throw new SecurityException( 317 "Unable to find app for caller " + caller 318 + " (pid=" + Binder.getCallingPid() 319 + ") when starting service " + service); 320 } 321 callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE; 322 } else { 323 callerFg = true; 324 } 325 326 327 ServiceLookupResult res = 328 retrieveServiceLocked(service, resolvedType, callingPackage, 329 callingPid, callingUid, userId, true, callerFg); 330 if (res == null) { 331 return null; 332 } 333 if (res.record == null) { 334 return new ComponentName("!", res.permission != null 335 ? res.permission : "private to package"); 336 } 337 338 ServiceRecord r = res.record; 339 340 if (!mAm.getUserManagerLocked().exists(r.userId)) { 341 Slog.d(TAG, "Trying to start service with non-existent user! " + r.userId); 342 return null; 343 } 344 345 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked( 346 callingUid, r.packageName, service, service.getFlags(), null, r.userId); 347 if (unscheduleServiceRestartLocked(r, callingUid, false)) { 348 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r); 349 } 350 r.lastActivity = SystemClock.uptimeMillis(); 351 r.startRequested = true; 352 r.delayedStop = false; 353 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(), 354 service, neededGrants)); 355 356 final ServiceMap smap = getServiceMap(r.userId); 357 boolean addToStarting = false; 358 if (!callerFg && r.app == null && mAm.mStartedUsers.get(r.userId) != null) { 359 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false); 360 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) { 361 // If this is not coming from a foreground caller, then we may want 362 // to delay the start if there are already other background services 363 // that are starting. This is to avoid process start spam when lots 364 // of applications are all handling things like connectivity broadcasts. 365 // We only do this for cached processes, because otherwise an application 366 // can have assumptions about calling startService() for a service to run 367 // in its own process, and for that process to not be killed before the 368 // service is started. This is especially the case for receivers, which 369 // may start a service in onReceive() to do some additional work and have 370 // initialized some global state as part of that. 371 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of " 372 + r + " in " + proc); 373 if (r.delayed) { 374 // This service is already scheduled for a delayed start; just leave 375 // it still waiting. 376 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r); 377 return r.name; 378 } 379 if (smap.mStartingBackground.size() >= mMaxStartingBackground) { 380 // Something else is starting, delay! 381 Slog.i(TAG_SERVICE, "Delaying start of: " + r); 382 smap.mDelayedStartList.add(r); 383 r.delayed = true; 384 return r.name; 385 } 386 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r); 387 addToStarting = true; 388 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 389 // We slightly loosen when we will enqueue this new service as a background 390 // starting service we are waiting for, to also include processes that are 391 // currently running other services or receivers. 392 addToStarting = true; 393 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 394 "Not delaying, but counting as bg: " + r); 395 } else if (DEBUG_DELAYED_STARTS) { 396 StringBuilder sb = new StringBuilder(128); 397 sb.append("Not potential delay (state=").append(proc.curProcState) 398 .append(' ').append(proc.adjType); 399 String reason = proc.makeAdjReason(); 400 if (reason != null) { 401 sb.append(' '); 402 sb.append(reason); 403 } 404 sb.append("): "); 405 sb.append(r.toString()); 406 Slog.v(TAG_SERVICE, sb.toString()); 407 } 408 } else if (DEBUG_DELAYED_STARTS) { 409 if (callerFg) { 410 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid=" 411 + callingUid + " pid=" + callingPid + "): " + r); 412 } else if (r.app != null) { 413 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r); 414 } else { 415 Slog.v(TAG_SERVICE, 416 "Not potential delay (user " + r.userId + " not started): " + r); 417 } 418 } 419 420 return startServiceInnerLocked(smap, service, r, callerFg, addToStarting); 421 } 422 startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, boolean callerFg, boolean addToStarting)423 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r, 424 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException { 425 ProcessStats.ServiceState stracker = r.getTracker(); 426 if (stracker != null) { 427 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity); 428 } 429 r.callStart = false; 430 synchronized (r.stats.getBatteryStats()) { 431 r.stats.startRunningLocked(); 432 } 433 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false); 434 if (error != null) { 435 return new ComponentName("!!", error); 436 } 437 438 if (r.startRequested && addToStarting) { 439 boolean first = smap.mStartingBackground.size() == 0; 440 smap.mStartingBackground.add(r); 441 r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT; 442 if (DEBUG_DELAYED_SERVICE) { 443 RuntimeException here = new RuntimeException("here"); 444 here.fillInStackTrace(); 445 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here); 446 } else if (DEBUG_DELAYED_STARTS) { 447 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r); 448 } 449 if (first) { 450 smap.rescheduleDelayedStarts(); 451 } 452 } else if (callerFg) { 453 smap.ensureNotStartingBackground(r); 454 } 455 456 return r.name; 457 } 458 stopServiceLocked(ServiceRecord service)459 private void stopServiceLocked(ServiceRecord service) { 460 if (service.delayed) { 461 // If service isn't actually running, but is is being held in the 462 // delayed list, then we need to keep it started but note that it 463 // should be stopped once no longer delayed. 464 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service); 465 service.delayedStop = true; 466 return; 467 } 468 synchronized (service.stats.getBatteryStats()) { 469 service.stats.stopRunningLocked(); 470 } 471 service.startRequested = false; 472 if (service.tracker != null) { 473 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(), 474 SystemClock.uptimeMillis()); 475 } 476 service.callStart = false; 477 bringDownServiceIfNeededLocked(service, false, false); 478 } 479 stopServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int userId)480 int stopServiceLocked(IApplicationThread caller, Intent service, 481 String resolvedType, int userId) { 482 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service 483 + " type=" + resolvedType); 484 485 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); 486 if (caller != null && callerApp == null) { 487 throw new SecurityException( 488 "Unable to find app for caller " + caller 489 + " (pid=" + Binder.getCallingPid() 490 + ") when stopping service " + service); 491 } 492 493 // If this service is active, make sure it is stopped. 494 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null, 495 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false); 496 if (r != null) { 497 if (r.record != null) { 498 final long origId = Binder.clearCallingIdentity(); 499 try { 500 stopServiceLocked(r.record); 501 } finally { 502 Binder.restoreCallingIdentity(origId); 503 } 504 return 1; 505 } 506 return -1; 507 } 508 509 return 0; 510 } 511 peekServiceLocked(Intent service, String resolvedType, String callingPackage)512 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) { 513 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage, 514 Binder.getCallingPid(), Binder.getCallingUid(), 515 UserHandle.getCallingUserId(), false, false); 516 517 IBinder ret = null; 518 if (r != null) { 519 // r.record is null if findServiceLocked() failed the caller permission check 520 if (r.record == null) { 521 throw new SecurityException( 522 "Permission Denial: Accessing service" 523 + " from pid=" + Binder.getCallingPid() 524 + ", uid=" + Binder.getCallingUid() 525 + " requires " + r.permission); 526 } 527 IntentBindRecord ib = r.record.bindings.get(r.record.intent); 528 if (ib != null) { 529 ret = ib.binder; 530 } 531 } 532 533 return ret; 534 } 535 stopServiceTokenLocked(ComponentName className, IBinder token, int startId)536 boolean stopServiceTokenLocked(ComponentName className, IBinder token, 537 int startId) { 538 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className 539 + " " + token + " startId=" + startId); 540 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId()); 541 if (r != null) { 542 if (startId >= 0) { 543 // Asked to only stop if done with all work. Note that 544 // to avoid leaks, we will take this as dropping all 545 // start items up to and including this one. 546 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false); 547 if (si != null) { 548 while (r.deliveredStarts.size() > 0) { 549 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0); 550 cur.removeUriPermissionsLocked(); 551 if (cur == si) { 552 break; 553 } 554 } 555 } 556 557 if (r.getLastStartId() != startId) { 558 return false; 559 } 560 561 if (r.deliveredStarts.size() > 0) { 562 Slog.w(TAG, "stopServiceToken startId " + startId 563 + " is last, but have " + r.deliveredStarts.size() 564 + " remaining args"); 565 } 566 } 567 568 synchronized (r.stats.getBatteryStats()) { 569 r.stats.stopRunningLocked(); 570 } 571 r.startRequested = false; 572 if (r.tracker != null) { 573 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(), 574 SystemClock.uptimeMillis()); 575 } 576 r.callStart = false; 577 final long origId = Binder.clearCallingIdentity(); 578 bringDownServiceIfNeededLocked(r, false, false); 579 Binder.restoreCallingIdentity(origId); 580 return true; 581 } 582 return false; 583 } 584 setServiceForegroundLocked(ComponentName className, IBinder token, int id, Notification notification, boolean removeNotification)585 public void setServiceForegroundLocked(ComponentName className, IBinder token, 586 int id, Notification notification, boolean removeNotification) { 587 final int userId = UserHandle.getCallingUserId(); 588 final long origId = Binder.clearCallingIdentity(); 589 try { 590 ServiceRecord r = findServiceLocked(className, token, userId); 591 if (r != null) { 592 if (id != 0) { 593 if (notification == null) { 594 throw new IllegalArgumentException("null notification"); 595 } 596 if (r.foregroundId != id) { 597 r.cancelNotification(); 598 r.foregroundId = id; 599 } 600 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE; 601 r.foregroundNoti = notification; 602 r.isForeground = true; 603 r.postNotification(); 604 if (r.app != null) { 605 updateServiceForegroundLocked(r.app, true); 606 } 607 getServiceMap(r.userId).ensureNotStartingBackground(r); 608 } else { 609 if (r.isForeground) { 610 r.isForeground = false; 611 if (r.app != null) { 612 mAm.updateLruProcessLocked(r.app, false, null); 613 updateServiceForegroundLocked(r.app, true); 614 } 615 } 616 if (removeNotification) { 617 r.cancelNotification(); 618 r.foregroundId = 0; 619 r.foregroundNoti = null; 620 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) { 621 r.stripForegroundServiceFlagFromNotification(); 622 } 623 } 624 } 625 } finally { 626 Binder.restoreCallingIdentity(origId); 627 } 628 } 629 updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj)630 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) { 631 boolean anyForeground = false; 632 for (int i=proc.services.size()-1; i>=0; i--) { 633 ServiceRecord sr = proc.services.valueAt(i); 634 if (sr.isForeground) { 635 anyForeground = true; 636 break; 637 } 638 } 639 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj); 640 } 641 updateServiceConnectionActivitiesLocked(ProcessRecord clientProc)642 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) { 643 ArraySet<ProcessRecord> updatedProcesses = null; 644 for (int i=0; i<clientProc.connections.size(); i++) { 645 final ConnectionRecord conn = clientProc.connections.valueAt(i); 646 final ProcessRecord proc = conn.binding.service.app; 647 if (proc == null || proc == clientProc) { 648 continue; 649 } else if (updatedProcesses == null) { 650 updatedProcesses = new ArraySet<>(); 651 } else if (updatedProcesses.contains(proc)) { 652 continue; 653 } 654 updatedProcesses.add(proc); 655 updateServiceClientActivitiesLocked(proc, null, false); 656 } 657 } 658 updateServiceClientActivitiesLocked(ProcessRecord proc, ConnectionRecord modCr, boolean updateLru)659 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc, 660 ConnectionRecord modCr, boolean updateLru) { 661 if (modCr != null && modCr.binding.client != null) { 662 if (modCr.binding.client.activities.size() <= 0) { 663 // This connection is from a client without activities, so adding 664 // and removing is not interesting. 665 return false; 666 } 667 } 668 669 boolean anyClientActivities = false; 670 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) { 671 ServiceRecord sr = proc.services.valueAt(i); 672 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) { 673 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni); 674 for (int cri=clist.size()-1; cri>=0; cri--) { 675 ConnectionRecord cr = clist.get(cri); 676 if (cr.binding.client == null || cr.binding.client == proc) { 677 // Binding to ourself is not interesting. 678 continue; 679 } 680 if (cr.binding.client.activities.size() > 0) { 681 anyClientActivities = true; 682 break; 683 } 684 } 685 } 686 } 687 if (anyClientActivities != proc.hasClientActivities) { 688 proc.hasClientActivities = anyClientActivities; 689 if (updateLru) { 690 mAm.updateLruProcessLocked(proc, anyClientActivities, null); 691 } 692 return true; 693 } 694 return false; 695 } 696 bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)697 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, 698 String resolvedType, IServiceConnection connection, int flags, 699 String callingPackage, int userId) throws TransactionTooLargeException { 700 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service 701 + " type=" + resolvedType + " conn=" + connection.asBinder() 702 + " flags=0x" + Integer.toHexString(flags)); 703 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller); 704 if (callerApp == null) { 705 throw new SecurityException( 706 "Unable to find app for caller " + caller 707 + " (pid=" + Binder.getCallingPid() 708 + ") when binding service " + service); 709 } 710 711 ActivityRecord activity = null; 712 if (token != null) { 713 activity = ActivityRecord.isInStackLocked(token); 714 if (activity == null) { 715 Slog.w(TAG, "Binding with unknown activity: " + token); 716 return 0; 717 } 718 } 719 720 int clientLabel = 0; 721 PendingIntent clientIntent = null; 722 723 if (callerApp.info.uid == Process.SYSTEM_UID) { 724 // Hacky kind of thing -- allow system stuff to tell us 725 // what they are, so we can report this elsewhere for 726 // others to know why certain services are running. 727 try { 728 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT); 729 } catch (RuntimeException e) { 730 } 731 if (clientIntent != null) { 732 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0); 733 if (clientLabel != 0) { 734 // There are no useful extras in the intent, trash them. 735 // System code calling with this stuff just needs to know 736 // this will happen. 737 service = service.cloneFilter(); 738 } 739 } 740 } 741 742 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 743 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 744 "BIND_TREAT_LIKE_ACTIVITY"); 745 } 746 747 final boolean callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE; 748 749 ServiceLookupResult res = 750 retrieveServiceLocked(service, resolvedType, callingPackage, 751 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg); 752 if (res == null) { 753 return 0; 754 } 755 if (res.record == null) { 756 return -1; 757 } 758 ServiceRecord s = res.record; 759 760 final long origId = Binder.clearCallingIdentity(); 761 762 try { 763 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) { 764 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: " 765 + s); 766 } 767 768 if ((flags&Context.BIND_AUTO_CREATE) != 0) { 769 s.lastActivity = SystemClock.uptimeMillis(); 770 if (!s.hasAutoCreateConnections()) { 771 // This is the first binding, let the tracker know. 772 ProcessStats.ServiceState stracker = s.getTracker(); 773 if (stracker != null) { 774 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(), 775 s.lastActivity); 776 } 777 } 778 } 779 780 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, 781 s.appInfo.uid, s.name, s.processName); 782 783 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp); 784 ConnectionRecord c = new ConnectionRecord(b, activity, 785 connection, flags, clientLabel, clientIntent); 786 787 IBinder binder = connection.asBinder(); 788 ArrayList<ConnectionRecord> clist = s.connections.get(binder); 789 if (clist == null) { 790 clist = new ArrayList<ConnectionRecord>(); 791 s.connections.put(binder, clist); 792 } 793 clist.add(c); 794 b.connections.add(c); 795 if (activity != null) { 796 if (activity.connections == null) { 797 activity.connections = new HashSet<ConnectionRecord>(); 798 } 799 activity.connections.add(c); 800 } 801 b.client.connections.add(c); 802 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) { 803 b.client.hasAboveClient = true; 804 } 805 if (s.app != null) { 806 updateServiceClientActivitiesLocked(s.app, c, true); 807 } 808 clist = mServiceConnections.get(binder); 809 if (clist == null) { 810 clist = new ArrayList<ConnectionRecord>(); 811 mServiceConnections.put(binder, clist); 812 } 813 clist.add(c); 814 815 if ((flags&Context.BIND_AUTO_CREATE) != 0) { 816 s.lastActivity = SystemClock.uptimeMillis(); 817 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) { 818 return 0; 819 } 820 } 821 822 if (s.app != null) { 823 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 824 s.app.treatLikeActivity = true; 825 } 826 // This could have made the service more important. 827 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities 828 || s.app.treatLikeActivity, b.client); 829 mAm.updateOomAdjLocked(s.app); 830 } 831 832 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b 833 + ": received=" + b.intent.received 834 + " apps=" + b.intent.apps.size() 835 + " doRebind=" + b.intent.doRebind); 836 837 if (s.app != null && b.intent.received) { 838 // Service is already running, so we can immediately 839 // publish the connection. 840 try { 841 c.conn.connected(s.name, b.intent.binder); 842 } catch (Exception e) { 843 Slog.w(TAG, "Failure sending service " + s.shortName 844 + " to connection " + c.conn.asBinder() 845 + " (in " + c.binding.client.processName + ")", e); 846 } 847 848 // If this is the first app connected back to this binding, 849 // and the service had previously asked to be told when 850 // rebound, then do so. 851 if (b.intent.apps.size() == 1 && b.intent.doRebind) { 852 requestServiceBindingLocked(s, b.intent, callerFg, true); 853 } 854 } else if (!b.intent.requested) { 855 requestServiceBindingLocked(s, b.intent, callerFg, false); 856 } 857 858 getServiceMap(s.userId).ensureNotStartingBackground(s); 859 860 } finally { 861 Binder.restoreCallingIdentity(origId); 862 } 863 864 return 1; 865 } 866 publishServiceLocked(ServiceRecord r, Intent intent, IBinder service)867 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) { 868 final long origId = Binder.clearCallingIdentity(); 869 try { 870 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r 871 + " " + intent + ": " + service); 872 if (r != null) { 873 Intent.FilterComparison filter 874 = new Intent.FilterComparison(intent); 875 IntentBindRecord b = r.bindings.get(filter); 876 if (b != null && !b.received) { 877 b.binder = service; 878 b.requested = true; 879 b.received = true; 880 for (int conni=r.connections.size()-1; conni>=0; conni--) { 881 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni); 882 for (int i=0; i<clist.size(); i++) { 883 ConnectionRecord c = clist.get(i); 884 if (!filter.equals(c.binding.intent.intent)) { 885 if (DEBUG_SERVICE) Slog.v( 886 TAG_SERVICE, "Not publishing to: " + c); 887 if (DEBUG_SERVICE) Slog.v( 888 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent); 889 if (DEBUG_SERVICE) Slog.v( 890 TAG_SERVICE, "Published intent: " + intent); 891 continue; 892 } 893 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c); 894 try { 895 c.conn.connected(r.name, service); 896 } catch (Exception e) { 897 Slog.w(TAG, "Failure sending service " + r.name + 898 " to connection " + c.conn.asBinder() + 899 " (in " + c.binding.client.processName + ")", e); 900 } 901 } 902 } 903 } 904 905 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false); 906 } 907 } finally { 908 Binder.restoreCallingIdentity(origId); 909 } 910 } 911 unbindServiceLocked(IServiceConnection connection)912 boolean unbindServiceLocked(IServiceConnection connection) { 913 IBinder binder = connection.asBinder(); 914 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder); 915 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder); 916 if (clist == null) { 917 Slog.w(TAG, "Unbind failed: could not find connection for " 918 + connection.asBinder()); 919 return false; 920 } 921 922 final long origId = Binder.clearCallingIdentity(); 923 try { 924 while (clist.size() > 0) { 925 ConnectionRecord r = clist.get(0); 926 removeConnectionLocked(r, null, null); 927 if (clist.size() > 0 && clist.get(0) == r) { 928 // In case it didn't get removed above, do it now. 929 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder); 930 clist.remove(0); 931 } 932 933 if (r.binding.service.app != null) { 934 // This could have made the service less important. 935 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 936 r.binding.service.app.treatLikeActivity = true; 937 mAm.updateLruProcessLocked(r.binding.service.app, 938 r.binding.service.app.hasClientActivities 939 || r.binding.service.app.treatLikeActivity, null); 940 } 941 mAm.updateOomAdjLocked(r.binding.service.app); 942 } 943 } 944 } finally { 945 Binder.restoreCallingIdentity(origId); 946 } 947 948 return true; 949 } 950 unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind)951 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) { 952 final long origId = Binder.clearCallingIdentity(); 953 try { 954 if (r != null) { 955 Intent.FilterComparison filter 956 = new Intent.FilterComparison(intent); 957 IntentBindRecord b = r.bindings.get(filter); 958 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r 959 + " at " + b + ": apps=" 960 + (b != null ? b.apps.size() : 0)); 961 962 boolean inDestroying = mDestroyingServices.contains(r); 963 if (b != null) { 964 if (b.apps.size() > 0 && !inDestroying) { 965 // Applications have already bound since the last 966 // unbind, so just rebind right here. 967 boolean inFg = false; 968 for (int i=b.apps.size()-1; i>=0; i--) { 969 ProcessRecord client = b.apps.valueAt(i).client; 970 if (client != null && client.setSchedGroup 971 != Process.THREAD_GROUP_BG_NONINTERACTIVE) { 972 inFg = true; 973 break; 974 } 975 } 976 try { 977 requestServiceBindingLocked(r, b, inFg, true); 978 } catch (TransactionTooLargeException e) { 979 // Don't pass this back to ActivityThread, it's unrelated. 980 } 981 } else { 982 // Note to tell the service the next time there is 983 // a new client. 984 b.doRebind = true; 985 } 986 } 987 988 serviceDoneExecutingLocked(r, inDestroying, false); 989 } 990 } finally { 991 Binder.restoreCallingIdentity(origId); 992 } 993 } 994 findServiceLocked(ComponentName name, IBinder token, int userId)995 private final ServiceRecord findServiceLocked(ComponentName name, 996 IBinder token, int userId) { 997 ServiceRecord r = getServiceByName(name, userId); 998 return r == token ? r : null; 999 } 1000 1001 private final class ServiceLookupResult { 1002 final ServiceRecord record; 1003 final String permission; 1004 ServiceLookupResult(ServiceRecord _record, String _permission)1005 ServiceLookupResult(ServiceRecord _record, String _permission) { 1006 record = _record; 1007 permission = _permission; 1008 } 1009 } 1010 1011 private class ServiceRestarter implements Runnable { 1012 private ServiceRecord mService; 1013 setService(ServiceRecord service)1014 void setService(ServiceRecord service) { 1015 mService = service; 1016 } 1017 run()1018 public void run() { 1019 synchronized(mAm) { 1020 performServiceRestartLocked(mService); 1021 } 1022 } 1023 } 1024 retrieveServiceLocked(Intent service, String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, boolean createIfNeeded, boolean callingFromFg)1025 private ServiceLookupResult retrieveServiceLocked(Intent service, 1026 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId, 1027 boolean createIfNeeded, boolean callingFromFg) { 1028 ServiceRecord r = null; 1029 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service 1030 + " type=" + resolvedType + " callingUid=" + callingUid); 1031 1032 userId = mAm.handleIncomingUser(callingPid, callingUid, userId, 1033 false, ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null); 1034 1035 ServiceMap smap = getServiceMap(userId); 1036 final ComponentName comp = service.getComponent(); 1037 if (comp != null) { 1038 r = smap.mServicesByName.get(comp); 1039 } 1040 if (r == null) { 1041 Intent.FilterComparison filter = new Intent.FilterComparison(service); 1042 r = smap.mServicesByIntent.get(filter); 1043 } 1044 if (r == null) { 1045 try { 1046 ResolveInfo rInfo = 1047 AppGlobals.getPackageManager().resolveService( 1048 service, resolvedType, 1049 ActivityManagerService.STOCK_PM_FLAGS, userId); 1050 ServiceInfo sInfo = 1051 rInfo != null ? rInfo.serviceInfo : null; 1052 if (sInfo == null) { 1053 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId + 1054 ": not found"); 1055 return null; 1056 } 1057 ComponentName name = new ComponentName( 1058 sInfo.applicationInfo.packageName, sInfo.name); 1059 if (userId > 0) { 1060 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo, 1061 sInfo.name, sInfo.flags) 1062 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) { 1063 userId = 0; 1064 smap = getServiceMap(0); 1065 } 1066 sInfo = new ServiceInfo(sInfo); 1067 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId); 1068 } 1069 r = smap.mServicesByName.get(name); 1070 if (r == null && createIfNeeded) { 1071 Intent.FilterComparison filter 1072 = new Intent.FilterComparison(service.cloneFilter()); 1073 ServiceRestarter res = new ServiceRestarter(); 1074 BatteryStatsImpl.Uid.Pkg.Serv ss = null; 1075 BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics(); 1076 synchronized (stats) { 1077 ss = stats.getServiceStatsLocked( 1078 sInfo.applicationInfo.uid, sInfo.packageName, 1079 sInfo.name); 1080 } 1081 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res); 1082 res.setService(r); 1083 smap.mServicesByName.put(name, r); 1084 smap.mServicesByIntent.put(filter, r); 1085 1086 // Make sure this component isn't in the pending list. 1087 for (int i=mPendingServices.size()-1; i>=0; i--) { 1088 ServiceRecord pr = mPendingServices.get(i); 1089 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid 1090 && pr.name.equals(name)) { 1091 mPendingServices.remove(i); 1092 } 1093 } 1094 } 1095 } catch (RemoteException ex) { 1096 // pm is in same process, this will never happen. 1097 } 1098 } 1099 if (r != null) { 1100 if (mAm.checkComponentPermission(r.permission, 1101 callingPid, callingUid, r.appInfo.uid, r.exported) 1102 != PackageManager.PERMISSION_GRANTED) { 1103 if (!r.exported) { 1104 Slog.w(TAG, "Permission Denial: Accessing service " + r.name 1105 + " from pid=" + callingPid 1106 + ", uid=" + callingUid 1107 + " that is not exported from uid " + r.appInfo.uid); 1108 return new ServiceLookupResult(null, "not exported from uid " 1109 + r.appInfo.uid); 1110 } 1111 Slog.w(TAG, "Permission Denial: Accessing service " + r.name 1112 + " from pid=" + callingPid 1113 + ", uid=" + callingUid 1114 + " requires " + r.permission); 1115 return new ServiceLookupResult(null, r.permission); 1116 } else if (r.permission != null && callingPackage != null) { 1117 final int opCode = AppOpsManager.permissionToOpCode(r.permission); 1118 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation( 1119 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) { 1120 Slog.w(TAG, "Appop Denial: Accessing service " + r.name 1121 + " from pid=" + callingPid 1122 + ", uid=" + callingUid 1123 + " requires appop " + AppOpsManager.opToName(opCode)); 1124 return null; 1125 } 1126 } 1127 1128 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid, 1129 resolvedType, r.appInfo)) { 1130 return null; 1131 } 1132 return new ServiceLookupResult(r, null); 1133 } 1134 return null; 1135 } 1136 bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why)1137 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) { 1138 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING " 1139 + why + " of " + r + " in app " + r.app); 1140 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING " 1141 + why + " of " + r.shortName); 1142 long now = SystemClock.uptimeMillis(); 1143 if (r.executeNesting == 0) { 1144 r.executeFg = fg; 1145 ProcessStats.ServiceState stracker = r.getTracker(); 1146 if (stracker != null) { 1147 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now); 1148 } 1149 if (r.app != null) { 1150 r.app.executingServices.add(r); 1151 r.app.execServicesFg |= fg; 1152 if (r.app.executingServices.size() == 1) { 1153 scheduleServiceTimeoutLocked(r.app); 1154 } 1155 } 1156 } else if (r.app != null && fg && !r.app.execServicesFg) { 1157 r.app.execServicesFg = true; 1158 scheduleServiceTimeoutLocked(r.app); 1159 } 1160 r.executeFg |= fg; 1161 r.executeNesting++; 1162 r.executingStart = now; 1163 } 1164 requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind)1165 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, 1166 boolean execInFg, boolean rebind) throws TransactionTooLargeException { 1167 if (r.app == null || r.app.thread == null) { 1168 // If service is not currently running, can't yet bind. 1169 return false; 1170 } 1171 if ((!i.requested || rebind) && i.apps.size() > 0) { 1172 try { 1173 bumpServiceExecutingLocked(r, execInFg, "bind"); 1174 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); 1175 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind, 1176 r.app.repProcState); 1177 if (!rebind) { 1178 i.requested = true; 1179 } 1180 i.hasBound = true; 1181 i.doRebind = false; 1182 } catch (TransactionTooLargeException e) { 1183 // Keep the executeNesting count accurate. 1184 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e); 1185 final boolean inDestroying = mDestroyingServices.contains(r); 1186 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 1187 throw e; 1188 } catch (RemoteException e) { 1189 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r); 1190 // Keep the executeNesting count accurate. 1191 final boolean inDestroying = mDestroyingServices.contains(r); 1192 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 1193 return false; 1194 } 1195 } 1196 return true; 1197 } 1198 scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel)1199 private final boolean scheduleServiceRestartLocked(ServiceRecord r, 1200 boolean allowCancel) { 1201 boolean canceled = false; 1202 1203 ServiceMap smap = getServiceMap(r.userId); 1204 if (smap.mServicesByName.get(r.name) != r) { 1205 ServiceRecord cur = smap.mServicesByName.get(r.name); 1206 Slog.wtf(TAG, "Attempting to schedule restart of " + r 1207 + " when found in map: " + cur); 1208 return false; 1209 } 1210 1211 final long now = SystemClock.uptimeMillis(); 1212 1213 if ((r.serviceInfo.applicationInfo.flags 1214 &ApplicationInfo.FLAG_PERSISTENT) == 0) { 1215 long minDuration = SERVICE_RESTART_DURATION; 1216 long resetTime = SERVICE_RESET_RUN_DURATION; 1217 1218 // Any delivered but not yet finished starts should be put back 1219 // on the pending list. 1220 final int N = r.deliveredStarts.size(); 1221 if (N > 0) { 1222 for (int i=N-1; i>=0; i--) { 1223 ServiceRecord.StartItem si = r.deliveredStarts.get(i); 1224 si.removeUriPermissionsLocked(); 1225 if (si.intent == null) { 1226 // We'll generate this again if needed. 1227 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT 1228 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) { 1229 r.pendingStarts.add(0, si); 1230 long dur = SystemClock.uptimeMillis() - si.deliveredTime; 1231 dur *= 2; 1232 if (minDuration < dur) minDuration = dur; 1233 if (resetTime < dur) resetTime = dur; 1234 } else { 1235 Slog.w(TAG, "Canceling start item " + si.intent + " in service " 1236 + r.name); 1237 canceled = true; 1238 } 1239 } 1240 r.deliveredStarts.clear(); 1241 } 1242 1243 r.totalRestartCount++; 1244 if (r.restartDelay == 0) { 1245 r.restartCount++; 1246 r.restartDelay = minDuration; 1247 } else { 1248 // If it has been a "reasonably long time" since the service 1249 // was started, then reset our restart duration back to 1250 // the beginning, so we don't infinitely increase the duration 1251 // on a service that just occasionally gets killed (which is 1252 // a normal case, due to process being killed to reclaim memory). 1253 if (now > (r.restartTime+resetTime)) { 1254 r.restartCount = 1; 1255 r.restartDelay = minDuration; 1256 } else { 1257 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR; 1258 if (r.restartDelay < minDuration) { 1259 r.restartDelay = minDuration; 1260 } 1261 } 1262 } 1263 1264 r.nextRestartTime = now + r.restartDelay; 1265 1266 // Make sure that we don't end up restarting a bunch of services 1267 // all at the same time. 1268 boolean repeat; 1269 do { 1270 repeat = false; 1271 for (int i=mRestartingServices.size()-1; i>=0; i--) { 1272 ServiceRecord r2 = mRestartingServices.get(i); 1273 if (r2 != r && r.nextRestartTime 1274 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN) 1275 && r.nextRestartTime 1276 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) { 1277 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN; 1278 r.restartDelay = r.nextRestartTime - now; 1279 repeat = true; 1280 break; 1281 } 1282 } 1283 } while (repeat); 1284 1285 } else { 1286 // Persistent processes are immediately restarted, so there is no 1287 // reason to hold of on restarting their services. 1288 r.totalRestartCount++; 1289 r.restartCount = 0; 1290 r.restartDelay = 0; 1291 r.nextRestartTime = now; 1292 } 1293 1294 if (!mRestartingServices.contains(r)) { 1295 r.createdFromFg = false; 1296 mRestartingServices.add(r); 1297 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now); 1298 } 1299 1300 r.cancelNotification(); 1301 1302 mAm.mHandler.removeCallbacks(r.restarter); 1303 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime); 1304 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay; 1305 Slog.w(TAG, "Scheduling restart of crashed service " 1306 + r.shortName + " in " + r.restartDelay + "ms"); 1307 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART, 1308 r.userId, r.shortName, r.restartDelay); 1309 1310 return canceled; 1311 } 1312 performServiceRestartLocked(ServiceRecord r)1313 final void performServiceRestartLocked(ServiceRecord r) { 1314 if (!mRestartingServices.contains(r)) { 1315 return; 1316 } 1317 try { 1318 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true); 1319 } catch (TransactionTooLargeException e) { 1320 // Ignore, it's been logged and nothing upstack cares. 1321 } 1322 } 1323 unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, boolean force)1324 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid, 1325 boolean force) { 1326 if (!force && r.restartDelay == 0) { 1327 return false; 1328 } 1329 // Remove from the restarting list; if the service is currently on the 1330 // restarting list, or the call is coming from another app, then this 1331 // service has become of much more interest so we reset the restart interval. 1332 boolean removed = mRestartingServices.remove(r); 1333 if (removed || callingUid != r.appInfo.uid) { 1334 r.resetRestartCounter(); 1335 } 1336 if (removed) { 1337 clearRestartingIfNeededLocked(r); 1338 } 1339 mAm.mHandler.removeCallbacks(r.restarter); 1340 return true; 1341 } 1342 clearRestartingIfNeededLocked(ServiceRecord r)1343 private void clearRestartingIfNeededLocked(ServiceRecord r) { 1344 if (r.restartTracker != null) { 1345 // If this is the last restarting record with this tracker, then clear 1346 // the tracker's restarting state. 1347 boolean stillTracking = false; 1348 for (int i=mRestartingServices.size()-1; i>=0; i--) { 1349 if (mRestartingServices.get(i).restartTracker == r.restartTracker) { 1350 stillTracking = true; 1351 break; 1352 } 1353 } 1354 if (!stillTracking) { 1355 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(), 1356 SystemClock.uptimeMillis()); 1357 r.restartTracker = null; 1358 } 1359 } 1360 } 1361 bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting)1362 private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, 1363 boolean whileRestarting) throws TransactionTooLargeException { 1364 //Slog.i(TAG, "Bring up service:"); 1365 //r.dump(" "); 1366 1367 if (r.app != null && r.app.thread != null) { 1368 sendServiceArgsLocked(r, execInFg, false); 1369 return null; 1370 } 1371 1372 if (!whileRestarting && r.restartDelay > 0) { 1373 // If waiting for a restart, then do nothing. 1374 return null; 1375 } 1376 1377 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent); 1378 1379 // We are now bringing the service up, so no longer in the 1380 // restarting state. 1381 if (mRestartingServices.remove(r)) { 1382 r.resetRestartCounter(); 1383 clearRestartingIfNeededLocked(r); 1384 } 1385 1386 // Make sure this service is no longer considered delayed, we are starting it now. 1387 if (r.delayed) { 1388 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r); 1389 getServiceMap(r.userId).mDelayedStartList.remove(r); 1390 r.delayed = false; 1391 } 1392 1393 // Make sure that the user who owns this service is started. If not, 1394 // we don't want to allow it to run. 1395 if (mAm.mStartedUsers.get(r.userId) == null) { 1396 String msg = "Unable to launch app " 1397 + r.appInfo.packageName + "/" 1398 + r.appInfo.uid + " for service " 1399 + r.intent.getIntent() + ": user " + r.userId + " is stopped"; 1400 Slog.w(TAG, msg); 1401 bringDownServiceLocked(r); 1402 return msg; 1403 } 1404 1405 // Service is now being launched, its package can't be stopped. 1406 try { 1407 AppGlobals.getPackageManager().setPackageStoppedState( 1408 r.packageName, false, r.userId); 1409 } catch (RemoteException e) { 1410 } catch (IllegalArgumentException e) { 1411 Slog.w(TAG, "Failed trying to unstop package " 1412 + r.packageName + ": " + e); 1413 } 1414 1415 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0; 1416 final String procName = r.processName; 1417 ProcessRecord app; 1418 1419 if (!isolated) { 1420 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false); 1421 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid 1422 + " app=" + app); 1423 if (app != null && app.thread != null) { 1424 try { 1425 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats); 1426 realStartServiceLocked(r, app, execInFg); 1427 return null; 1428 } catch (TransactionTooLargeException e) { 1429 throw e; 1430 } catch (RemoteException e) { 1431 Slog.w(TAG, "Exception when starting service " + r.shortName, e); 1432 } 1433 1434 // If a dead object exception was thrown -- fall through to 1435 // restart the application. 1436 } 1437 } else { 1438 // If this service runs in an isolated process, then each time 1439 // we call startProcessLocked() we will get a new isolated 1440 // process, starting another process if we are currently waiting 1441 // for a previous process to come up. To deal with this, we store 1442 // in the service any current isolated process it is running in or 1443 // waiting to have come up. 1444 app = r.isolatedProc; 1445 } 1446 1447 // Not running -- get it started, and enqueue this service record 1448 // to be executed when the app comes up. 1449 if (app == null) { 1450 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags, 1451 "service", r.name, false, isolated, false)) == null) { 1452 String msg = "Unable to launch app " 1453 + r.appInfo.packageName + "/" 1454 + r.appInfo.uid + " for service " 1455 + r.intent.getIntent() + ": process is bad"; 1456 Slog.w(TAG, msg); 1457 bringDownServiceLocked(r); 1458 return msg; 1459 } 1460 if (isolated) { 1461 r.isolatedProc = app; 1462 } 1463 } 1464 1465 if (!mPendingServices.contains(r)) { 1466 mPendingServices.add(r); 1467 } 1468 1469 if (r.delayedStop) { 1470 // Oh and hey we've already been asked to stop! 1471 r.delayedStop = false; 1472 if (r.startRequested) { 1473 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 1474 "Applying delayed stop (in bring up): " + r); 1475 stopServiceLocked(r); 1476 } 1477 } 1478 1479 return null; 1480 } 1481 requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)1482 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg) 1483 throws TransactionTooLargeException { 1484 for (int i=r.bindings.size()-1; i>=0; i--) { 1485 IntentBindRecord ibr = r.bindings.valueAt(i); 1486 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) { 1487 break; 1488 } 1489 } 1490 } 1491 realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg)1492 private final void realStartServiceLocked(ServiceRecord r, 1493 ProcessRecord app, boolean execInFg) throws RemoteException { 1494 if (app.thread == null) { 1495 throw new RemoteException(); 1496 } 1497 if (DEBUG_MU) 1498 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid 1499 + ", ProcessRecord.uid = " + app.uid); 1500 r.app = app; 1501 r.restartTime = r.lastActivity = SystemClock.uptimeMillis(); 1502 1503 final boolean newService = app.services.add(r); 1504 bumpServiceExecutingLocked(r, execInFg, "create"); 1505 mAm.updateLruProcessLocked(app, false, null); 1506 mAm.updateOomAdjLocked(); 1507 1508 boolean created = false; 1509 try { 1510 if (LOG_SERVICE_START_STOP) { 1511 String nameTerm; 1512 int lastPeriod = r.shortName.lastIndexOf('.'); 1513 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName; 1514 EventLogTags.writeAmCreateService( 1515 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid); 1516 } 1517 synchronized (r.stats.getBatteryStats()) { 1518 r.stats.startLaunchedLocked(); 1519 } 1520 mAm.ensurePackageDexOpt(r.serviceInfo.packageName); 1521 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE); 1522 app.thread.scheduleCreateService(r, r.serviceInfo, 1523 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo), 1524 app.repProcState); 1525 r.postNotification(); 1526 created = true; 1527 } catch (DeadObjectException e) { 1528 Slog.w(TAG, "Application dead when creating service " + r); 1529 mAm.appDiedLocked(app); 1530 throw e; 1531 } finally { 1532 if (!created) { 1533 // Keep the executeNesting count accurate. 1534 final boolean inDestroying = mDestroyingServices.contains(r); 1535 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 1536 1537 // Cleanup. 1538 if (newService) { 1539 app.services.remove(r); 1540 r.app = null; 1541 } 1542 1543 // Retry. 1544 if (!inDestroying) { 1545 scheduleServiceRestartLocked(r, false); 1546 } 1547 } 1548 } 1549 1550 requestServiceBindingsLocked(r, execInFg); 1551 1552 updateServiceClientActivitiesLocked(app, null, true); 1553 1554 // If the service is in the started state, and there are no 1555 // pending arguments, then fake up one so its onStartCommand() will 1556 // be called. 1557 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) { 1558 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(), 1559 null, null)); 1560 } 1561 1562 sendServiceArgsLocked(r, execInFg, true); 1563 1564 if (r.delayed) { 1565 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r); 1566 getServiceMap(r.userId).mDelayedStartList.remove(r); 1567 r.delayed = false; 1568 } 1569 1570 if (r.delayedStop) { 1571 // Oh and hey we've already been asked to stop! 1572 r.delayedStop = false; 1573 if (r.startRequested) { 1574 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, 1575 "Applying delayed stop (from start): " + r); 1576 stopServiceLocked(r); 1577 } 1578 } 1579 } 1580 sendServiceArgsLocked(ServiceRecord r, boolean execInFg, boolean oomAdjusted)1581 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg, 1582 boolean oomAdjusted) throws TransactionTooLargeException { 1583 final int N = r.pendingStarts.size(); 1584 if (N == 0) { 1585 return; 1586 } 1587 1588 while (r.pendingStarts.size() > 0) { 1589 Exception caughtException = null; 1590 ServiceRecord.StartItem si; 1591 try { 1592 si = r.pendingStarts.remove(0); 1593 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: " 1594 + r + " " + r.intent + " args=" + si.intent); 1595 if (si.intent == null && N > 1) { 1596 // If somehow we got a dummy null intent in the middle, 1597 // then skip it. DO NOT skip a null intent when it is 1598 // the only one in the list -- this is to support the 1599 // onStartCommand(null) case. 1600 continue; 1601 } 1602 si.deliveredTime = SystemClock.uptimeMillis(); 1603 r.deliveredStarts.add(si); 1604 si.deliveryCount++; 1605 if (si.neededGrants != null) { 1606 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants, 1607 si.getUriPermissionsLocked()); 1608 } 1609 bumpServiceExecutingLocked(r, execInFg, "start"); 1610 if (!oomAdjusted) { 1611 oomAdjusted = true; 1612 mAm.updateOomAdjLocked(r.app); 1613 } 1614 int flags = 0; 1615 if (si.deliveryCount > 1) { 1616 flags |= Service.START_FLAG_RETRY; 1617 } 1618 if (si.doneExecutingCount > 0) { 1619 flags |= Service.START_FLAG_REDELIVERY; 1620 } 1621 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent); 1622 } catch (TransactionTooLargeException e) { 1623 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent=" 1624 + si.intent); 1625 caughtException = e; 1626 } catch (RemoteException e) { 1627 // Remote process gone... we'll let the normal cleanup take care of this. 1628 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r); 1629 caughtException = e; 1630 } catch (Exception e) { 1631 Slog.w(TAG, "Unexpected exception", e); 1632 caughtException = e; 1633 } 1634 1635 if (caughtException != null) { 1636 // Keep nesting count correct 1637 final boolean inDestroying = mDestroyingServices.contains(r); 1638 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 1639 if (caughtException instanceof TransactionTooLargeException) { 1640 throw (TransactionTooLargeException)caughtException; 1641 } 1642 break; 1643 } 1644 } 1645 } 1646 isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn)1647 private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) { 1648 // Are we still explicitly being asked to run? 1649 if (r.startRequested) { 1650 return true; 1651 } 1652 1653 // Is someone still bound to us keepign us running? 1654 if (!knowConn) { 1655 hasConn = r.hasAutoCreateConnections(); 1656 } 1657 if (hasConn) { 1658 return true; 1659 } 1660 1661 return false; 1662 } 1663 bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, boolean hasConn)1664 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn, 1665 boolean hasConn) { 1666 //Slog.i(TAG, "Bring down service:"); 1667 //r.dump(" "); 1668 1669 if (isServiceNeeded(r, knowConn, hasConn)) { 1670 return; 1671 } 1672 1673 // Are we in the process of launching? 1674 if (mPendingServices.contains(r)) { 1675 return; 1676 } 1677 1678 bringDownServiceLocked(r); 1679 } 1680 bringDownServiceLocked(ServiceRecord r)1681 private final void bringDownServiceLocked(ServiceRecord r) { 1682 //Slog.i(TAG, "Bring down service:"); 1683 //r.dump(" "); 1684 1685 // Report to all of the connections that the service is no longer 1686 // available. 1687 for (int conni=r.connections.size()-1; conni>=0; conni--) { 1688 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni); 1689 for (int i=0; i<c.size(); i++) { 1690 ConnectionRecord cr = c.get(i); 1691 // There is still a connection to the service that is 1692 // being brought down. Mark it as dead. 1693 cr.serviceDead = true; 1694 try { 1695 cr.conn.connected(r.name, null); 1696 } catch (Exception e) { 1697 Slog.w(TAG, "Failure disconnecting service " + r.name + 1698 " to connection " + c.get(i).conn.asBinder() + 1699 " (in " + c.get(i).binding.client.processName + ")", e); 1700 } 1701 } 1702 } 1703 1704 // Tell the service that it has been unbound. 1705 if (r.app != null && r.app.thread != null) { 1706 for (int i=r.bindings.size()-1; i>=0; i--) { 1707 IntentBindRecord ibr = r.bindings.valueAt(i); 1708 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr 1709 + ": hasBound=" + ibr.hasBound); 1710 if (ibr.hasBound) { 1711 try { 1712 bumpServiceExecutingLocked(r, false, "bring down unbind"); 1713 mAm.updateOomAdjLocked(r.app); 1714 ibr.hasBound = false; 1715 r.app.thread.scheduleUnbindService(r, 1716 ibr.intent.getIntent()); 1717 } catch (Exception e) { 1718 Slog.w(TAG, "Exception when unbinding service " 1719 + r.shortName, e); 1720 serviceProcessGoneLocked(r); 1721 } 1722 } 1723 } 1724 } 1725 1726 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent); 1727 r.destroyTime = SystemClock.uptimeMillis(); 1728 if (LOG_SERVICE_START_STOP) { 1729 EventLogTags.writeAmDestroyService( 1730 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1); 1731 } 1732 1733 final ServiceMap smap = getServiceMap(r.userId); 1734 smap.mServicesByName.remove(r.name); 1735 smap.mServicesByIntent.remove(r.intent); 1736 r.totalRestartCount = 0; 1737 unscheduleServiceRestartLocked(r, 0, true); 1738 1739 // Also make sure it is not on the pending list. 1740 for (int i=mPendingServices.size()-1; i>=0; i--) { 1741 if (mPendingServices.get(i) == r) { 1742 mPendingServices.remove(i); 1743 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r); 1744 } 1745 } 1746 1747 r.cancelNotification(); 1748 r.isForeground = false; 1749 r.foregroundId = 0; 1750 r.foregroundNoti = null; 1751 1752 // Clear start entries. 1753 r.clearDeliveredStartsLocked(); 1754 r.pendingStarts.clear(); 1755 1756 if (r.app != null) { 1757 synchronized (r.stats.getBatteryStats()) { 1758 r.stats.stopLaunchedLocked(); 1759 } 1760 r.app.services.remove(r); 1761 if (r.app.thread != null) { 1762 updateServiceForegroundLocked(r.app, false); 1763 try { 1764 bumpServiceExecutingLocked(r, false, "destroy"); 1765 mDestroyingServices.add(r); 1766 r.destroying = true; 1767 mAm.updateOomAdjLocked(r.app); 1768 r.app.thread.scheduleStopService(r); 1769 } catch (Exception e) { 1770 Slog.w(TAG, "Exception when destroying service " 1771 + r.shortName, e); 1772 serviceProcessGoneLocked(r); 1773 } 1774 } else { 1775 if (DEBUG_SERVICE) Slog.v( 1776 TAG_SERVICE, "Removed service that has no process: " + r); 1777 } 1778 } else { 1779 if (DEBUG_SERVICE) Slog.v( 1780 TAG_SERVICE, "Removed service that is not running: " + r); 1781 } 1782 1783 if (r.bindings.size() > 0) { 1784 r.bindings.clear(); 1785 } 1786 1787 if (r.restarter instanceof ServiceRestarter) { 1788 ((ServiceRestarter)r.restarter).setService(null); 1789 } 1790 1791 int memFactor = mAm.mProcessStats.getMemFactorLocked(); 1792 long now = SystemClock.uptimeMillis(); 1793 if (r.tracker != null) { 1794 r.tracker.setStarted(false, memFactor, now); 1795 r.tracker.setBound(false, memFactor, now); 1796 if (r.executeNesting == 0) { 1797 r.tracker.clearCurrentOwner(r, false); 1798 r.tracker = null; 1799 } 1800 } 1801 1802 smap.ensureNotStartingBackground(r); 1803 } 1804 removeConnectionLocked( ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct)1805 void removeConnectionLocked( 1806 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) { 1807 IBinder binder = c.conn.asBinder(); 1808 AppBindRecord b = c.binding; 1809 ServiceRecord s = b.service; 1810 ArrayList<ConnectionRecord> clist = s.connections.get(binder); 1811 if (clist != null) { 1812 clist.remove(c); 1813 if (clist.size() == 0) { 1814 s.connections.remove(binder); 1815 } 1816 } 1817 b.connections.remove(c); 1818 if (c.activity != null && c.activity != skipAct) { 1819 if (c.activity.connections != null) { 1820 c.activity.connections.remove(c); 1821 } 1822 } 1823 if (b.client != skipApp) { 1824 b.client.connections.remove(c); 1825 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) { 1826 b.client.updateHasAboveClientLocked(); 1827 } 1828 if (s.app != null) { 1829 updateServiceClientActivitiesLocked(s.app, c, true); 1830 } 1831 } 1832 clist = mServiceConnections.get(binder); 1833 if (clist != null) { 1834 clist.remove(c); 1835 if (clist.size() == 0) { 1836 mServiceConnections.remove(binder); 1837 } 1838 } 1839 1840 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name); 1841 1842 if (b.connections.size() == 0) { 1843 b.intent.apps.remove(b.client); 1844 } 1845 1846 if (!c.serviceDead) { 1847 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent 1848 + ": shouldUnbind=" + b.intent.hasBound); 1849 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0 1850 && b.intent.hasBound) { 1851 try { 1852 bumpServiceExecutingLocked(s, false, "unbind"); 1853 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0 1854 && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) { 1855 // If this service's process is not already in the cached list, 1856 // then update it in the LRU list here because this may be causing 1857 // it to go down there and we want it to start out near the top. 1858 mAm.updateLruProcessLocked(s.app, false, null); 1859 } 1860 mAm.updateOomAdjLocked(s.app); 1861 b.intent.hasBound = false; 1862 // Assume the client doesn't want to know about a rebind; 1863 // we will deal with that later if it asks for one. 1864 b.intent.doRebind = false; 1865 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent()); 1866 } catch (Exception e) { 1867 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e); 1868 serviceProcessGoneLocked(s); 1869 } 1870 } 1871 1872 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) { 1873 boolean hasAutoCreate = s.hasAutoCreateConnections(); 1874 if (!hasAutoCreate) { 1875 if (s.tracker != null) { 1876 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(), 1877 SystemClock.uptimeMillis()); 1878 } 1879 } 1880 bringDownServiceIfNeededLocked(s, true, hasAutoCreate); 1881 } 1882 } 1883 } 1884 serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res)1885 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) { 1886 boolean inDestroying = mDestroyingServices.contains(r); 1887 if (r != null) { 1888 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) { 1889 // This is a call from a service start... take care of 1890 // book-keeping. 1891 r.callStart = true; 1892 switch (res) { 1893 case Service.START_STICKY_COMPATIBILITY: 1894 case Service.START_STICKY: { 1895 // We are done with the associated start arguments. 1896 r.findDeliveredStart(startId, true); 1897 // Don't stop if killed. 1898 r.stopIfKilled = false; 1899 break; 1900 } 1901 case Service.START_NOT_STICKY: { 1902 // We are done with the associated start arguments. 1903 r.findDeliveredStart(startId, true); 1904 if (r.getLastStartId() == startId) { 1905 // There is no more work, and this service 1906 // doesn't want to hang around if killed. 1907 r.stopIfKilled = true; 1908 } 1909 break; 1910 } 1911 case Service.START_REDELIVER_INTENT: { 1912 // We'll keep this item until they explicitly 1913 // call stop for it, but keep track of the fact 1914 // that it was delivered. 1915 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false); 1916 if (si != null) { 1917 si.deliveryCount = 0; 1918 si.doneExecutingCount++; 1919 // Don't stop if killed. 1920 r.stopIfKilled = true; 1921 } 1922 break; 1923 } 1924 case Service.START_TASK_REMOVED_COMPLETE: { 1925 // Special processing for onTaskRemoved(). Don't 1926 // impact normal onStartCommand() processing. 1927 r.findDeliveredStart(startId, true); 1928 break; 1929 } 1930 default: 1931 throw new IllegalArgumentException( 1932 "Unknown service start result: " + res); 1933 } 1934 if (res == Service.START_STICKY_COMPATIBILITY) { 1935 r.callStart = false; 1936 } 1937 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) { 1938 // This is the final call from destroying the service... we should 1939 // actually be getting rid of the service at this point. Do some 1940 // validation of its state, and ensure it will be fully removed. 1941 if (!inDestroying) { 1942 // Not sure what else to do with this... if it is not actually in the 1943 // destroying list, we don't need to make sure to remove it from it. 1944 Slog.wtfStack(TAG, "Service done with onDestroy, but not inDestroying: " 1945 + r); 1946 } else if (r.executeNesting != 1) { 1947 Slog.wtfStack(TAG, "Service done with onDestroy, but executeNesting=" 1948 + r.executeNesting + ": " + r); 1949 // Fake it to keep from ANR due to orphaned entry. 1950 r.executeNesting = 1; 1951 } 1952 } 1953 final long origId = Binder.clearCallingIdentity(); 1954 serviceDoneExecutingLocked(r, inDestroying, inDestroying); 1955 Binder.restoreCallingIdentity(origId); 1956 } else { 1957 Slog.w(TAG, "Done executing unknown service from pid " 1958 + Binder.getCallingPid()); 1959 } 1960 } 1961 serviceProcessGoneLocked(ServiceRecord r)1962 private void serviceProcessGoneLocked(ServiceRecord r) { 1963 if (r.tracker != null) { 1964 int memFactor = mAm.mProcessStats.getMemFactorLocked(); 1965 long now = SystemClock.uptimeMillis(); 1966 r.tracker.setExecuting(false, memFactor, now); 1967 r.tracker.setBound(false, memFactor, now); 1968 r.tracker.setStarted(false, memFactor, now); 1969 } 1970 serviceDoneExecutingLocked(r, true, true); 1971 } 1972 serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, boolean finishing)1973 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying, 1974 boolean finishing) { 1975 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r 1976 + ": nesting=" + r.executeNesting 1977 + ", inDestroying=" + inDestroying + ", app=" + r.app); 1978 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, 1979 "<<< DONE EXECUTING " + r.shortName); 1980 r.executeNesting--; 1981 if (r.executeNesting <= 0) { 1982 if (r.app != null) { 1983 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 1984 "Nesting at 0 of " + r.shortName); 1985 r.app.execServicesFg = false; 1986 r.app.executingServices.remove(r); 1987 if (r.app.executingServices.size() == 0) { 1988 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, 1989 "No more executingServices of " + r.shortName); 1990 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app); 1991 } else if (r.executeFg) { 1992 // Need to re-evaluate whether the app still needs to be in the foreground. 1993 for (int i=r.app.executingServices.size()-1; i>=0; i--) { 1994 if (r.app.executingServices.valueAt(i).executeFg) { 1995 r.app.execServicesFg = true; 1996 break; 1997 } 1998 } 1999 } 2000 if (inDestroying) { 2001 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 2002 "doneExecuting remove destroying " + r); 2003 mDestroyingServices.remove(r); 2004 r.bindings.clear(); 2005 } 2006 mAm.updateOomAdjLocked(r.app); 2007 } 2008 r.executeFg = false; 2009 if (r.tracker != null) { 2010 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(), 2011 SystemClock.uptimeMillis()); 2012 if (finishing) { 2013 r.tracker.clearCurrentOwner(r, false); 2014 r.tracker = null; 2015 } 2016 } 2017 if (finishing) { 2018 if (r.app != null && !r.app.persistent) { 2019 r.app.services.remove(r); 2020 } 2021 r.app = null; 2022 } 2023 } 2024 } 2025 attachApplicationLocked(ProcessRecord proc, String processName)2026 boolean attachApplicationLocked(ProcessRecord proc, String processName) 2027 throws RemoteException { 2028 boolean didSomething = false; 2029 // Collect any services that are waiting for this process to come up. 2030 if (mPendingServices.size() > 0) { 2031 ServiceRecord sr = null; 2032 try { 2033 for (int i=0; i<mPendingServices.size(); i++) { 2034 sr = mPendingServices.get(i); 2035 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid 2036 || !processName.equals(sr.processName))) { 2037 continue; 2038 } 2039 2040 mPendingServices.remove(i); 2041 i--; 2042 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode, 2043 mAm.mProcessStats); 2044 realStartServiceLocked(sr, proc, sr.createdFromFg); 2045 didSomething = true; 2046 } 2047 } catch (RemoteException e) { 2048 Slog.w(TAG, "Exception in new application when starting service " 2049 + sr.shortName, e); 2050 throw e; 2051 } 2052 } 2053 // Also, if there are any services that are waiting to restart and 2054 // would run in this process, now is a good time to start them. It would 2055 // be weird to bring up the process but arbitrarily not let the services 2056 // run at this point just because their restart time hasn't come up. 2057 if (mRestartingServices.size() > 0) { 2058 ServiceRecord sr = null; 2059 for (int i=0; i<mRestartingServices.size(); i++) { 2060 sr = mRestartingServices.get(i); 2061 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid 2062 || !processName.equals(sr.processName))) { 2063 continue; 2064 } 2065 mAm.mHandler.removeCallbacks(sr.restarter); 2066 mAm.mHandler.post(sr.restarter); 2067 } 2068 } 2069 return didSomething; 2070 } 2071 processStartTimedOutLocked(ProcessRecord proc)2072 void processStartTimedOutLocked(ProcessRecord proc) { 2073 for (int i=0; i<mPendingServices.size(); i++) { 2074 ServiceRecord sr = mPendingServices.get(i); 2075 if ((proc.uid == sr.appInfo.uid 2076 && proc.processName.equals(sr.processName)) 2077 || sr.isolatedProc == proc) { 2078 Slog.w(TAG, "Forcing bringing down service: " + sr); 2079 sr.isolatedProc = null; 2080 mPendingServices.remove(i); 2081 i--; 2082 bringDownServiceLocked(sr); 2083 } 2084 } 2085 } 2086 collectPackageServicesLocked(String packageName, Set<String> filterByClasses, boolean evenPersistent, boolean doit, boolean killProcess, ArrayMap<ComponentName, ServiceRecord> services)2087 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses, 2088 boolean evenPersistent, boolean doit, boolean killProcess, 2089 ArrayMap<ComponentName, ServiceRecord> services) { 2090 boolean didSomething = false; 2091 for (int i = services.size() - 1; i >= 0; i--) { 2092 ServiceRecord service = services.valueAt(i); 2093 final boolean sameComponent = packageName == null 2094 || (service.packageName.equals(packageName) 2095 && (filterByClasses == null 2096 || filterByClasses.contains(service.name.getClassName()))); 2097 if (sameComponent 2098 && (service.app == null || evenPersistent || !service.app.persistent)) { 2099 if (!doit) { 2100 return true; 2101 } 2102 didSomething = true; 2103 Slog.i(TAG, " Force stopping service " + service); 2104 if (service.app != null) { 2105 service.app.removed = killProcess; 2106 if (!service.app.persistent) { 2107 service.app.services.remove(service); 2108 } 2109 } 2110 service.app = null; 2111 service.isolatedProc = null; 2112 if (mTmpCollectionResults == null) { 2113 mTmpCollectionResults = new ArrayList<>(); 2114 } 2115 mTmpCollectionResults.add(service); 2116 } 2117 } 2118 return didSomething; 2119 } 2120 bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, int userId, boolean evenPersistent, boolean killProcess, boolean doit)2121 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses, 2122 int userId, boolean evenPersistent, boolean killProcess, boolean doit) { 2123 boolean didSomething = false; 2124 2125 if (mTmpCollectionResults != null) { 2126 mTmpCollectionResults.clear(); 2127 } 2128 2129 if (userId == UserHandle.USER_ALL) { 2130 for (int i = mServiceMap.size() - 1; i >= 0; i--) { 2131 didSomething |= collectPackageServicesLocked(packageName, filterByClasses, 2132 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName); 2133 if (!doit && didSomething) { 2134 return true; 2135 } 2136 } 2137 } else { 2138 ServiceMap smap = mServiceMap.get(userId); 2139 if (smap != null) { 2140 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName; 2141 didSomething = collectPackageServicesLocked(packageName, filterByClasses, 2142 evenPersistent, doit, killProcess, items); 2143 } 2144 } 2145 2146 if (mTmpCollectionResults != null) { 2147 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) { 2148 bringDownServiceLocked(mTmpCollectionResults.get(i)); 2149 } 2150 mTmpCollectionResults.clear(); 2151 } 2152 return didSomething; 2153 } 2154 cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent)2155 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) { 2156 ArrayList<ServiceRecord> services = new ArrayList<>(); 2157 ArrayMap<ComponentName, ServiceRecord> alls = getServices(tr.userId); 2158 for (int i = alls.size() - 1; i >= 0; i--) { 2159 ServiceRecord sr = alls.valueAt(i); 2160 if (sr.packageName.equals(component.getPackageName())) { 2161 services.add(sr); 2162 } 2163 } 2164 2165 // Take care of any running services associated with the app. 2166 for (int i = services.size() - 1; i >= 0; i--) { 2167 ServiceRecord sr = services.get(i); 2168 if (sr.startRequested) { 2169 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) { 2170 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task"); 2171 stopServiceLocked(sr); 2172 } else { 2173 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true, 2174 sr.makeNextStartId(), baseIntent, null)); 2175 if (sr.app != null && sr.app.thread != null) { 2176 // We always run in the foreground, since this is called as 2177 // part of the "remove task" UI operation. 2178 try { 2179 sendServiceArgsLocked(sr, true, false); 2180 } catch (TransactionTooLargeException e) { 2181 // Ignore, keep going. 2182 } 2183 } 2184 } 2185 } 2186 } 2187 } 2188 killServicesLocked(ProcessRecord app, boolean allowRestart)2189 final void killServicesLocked(ProcessRecord app, boolean allowRestart) { 2190 // Report disconnected services. 2191 if (false) { 2192 // XXX we are letting the client link to the service for 2193 // death notifications. 2194 if (app.services.size() > 0) { 2195 Iterator<ServiceRecord> it = app.services.iterator(); 2196 while (it.hasNext()) { 2197 ServiceRecord r = it.next(); 2198 for (int conni=r.connections.size()-1; conni>=0; conni--) { 2199 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni); 2200 for (int i=0; i<cl.size(); i++) { 2201 ConnectionRecord c = cl.get(i); 2202 if (c.binding.client != app) { 2203 try { 2204 //c.conn.connected(r.className, null); 2205 } catch (Exception e) { 2206 // todo: this should be asynchronous! 2207 Slog.w(TAG, "Exception thrown disconnected servce " 2208 + r.shortName 2209 + " from app " + app.processName, e); 2210 } 2211 } 2212 } 2213 } 2214 } 2215 } 2216 } 2217 2218 // Clean up any connections this application has to other services. 2219 for (int i = app.connections.size() - 1; i >= 0; i--) { 2220 ConnectionRecord r = app.connections.valueAt(i); 2221 removeConnectionLocked(r, app, null); 2222 } 2223 updateServiceConnectionActivitiesLocked(app); 2224 app.connections.clear(); 2225 2226 // Clear app state from services. 2227 for (int i = app.services.size() - 1; i >= 0; i--) { 2228 ServiceRecord sr = app.services.valueAt(i); 2229 synchronized (sr.stats.getBatteryStats()) { 2230 sr.stats.stopLaunchedLocked(); 2231 } 2232 if (sr.app != app && sr.app != null && !sr.app.persistent) { 2233 sr.app.services.remove(sr); 2234 } 2235 sr.app = null; 2236 sr.isolatedProc = null; 2237 sr.executeNesting = 0; 2238 sr.forceClearTracker(); 2239 if (mDestroyingServices.remove(sr)) { 2240 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr); 2241 } 2242 2243 final int numClients = sr.bindings.size(); 2244 for (int bindingi=numClients-1; bindingi>=0; bindingi--) { 2245 IntentBindRecord b = sr.bindings.valueAt(bindingi); 2246 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b 2247 + ": shouldUnbind=" + b.hasBound); 2248 b.binder = null; 2249 b.requested = b.received = b.hasBound = false; 2250 // If this binding is coming from a cached process and is asking to keep 2251 // the service created, then we'll kill the cached process as well -- we 2252 // don't want to be thrashing around restarting processes that are only 2253 // there to be cached. 2254 for (int appi=b.apps.size()-1; appi>=0; appi--) { 2255 final ProcessRecord proc = b.apps.keyAt(appi); 2256 // If the process is already gone, skip it. 2257 if (proc.killedByAm || proc.thread == null) { 2258 continue; 2259 } 2260 // Only do this for processes that have an auto-create binding; 2261 // otherwise the binding can be left, because it won't cause the 2262 // service to restart. 2263 final AppBindRecord abind = b.apps.valueAt(appi); 2264 boolean hasCreate = false; 2265 for (int conni=abind.connections.size()-1; conni>=0; conni--) { 2266 ConnectionRecord conn = abind.connections.valueAt(conni); 2267 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT 2268 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) { 2269 hasCreate = true; 2270 break; 2271 } 2272 } 2273 if (!hasCreate) { 2274 continue; 2275 } 2276 // XXX turned off for now until we have more time to get a better policy. 2277 if (false && proc != null && !proc.persistent && proc.thread != null 2278 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID 2279 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 2280 proc.kill("bound to service " + sr.name.flattenToShortString() 2281 + " in dying proc " + (app != null ? app.processName : "??"), true); 2282 } 2283 } 2284 } 2285 } 2286 2287 ServiceMap smap = getServiceMap(app.userId); 2288 2289 // Now do remaining service cleanup. 2290 for (int i=app.services.size()-1; i>=0; i--) { 2291 ServiceRecord sr = app.services.valueAt(i); 2292 2293 // Unless the process is persistent, this process record is going away, 2294 // so make sure the service is cleaned out of it. 2295 if (!app.persistent) { 2296 app.services.removeAt(i); 2297 } 2298 2299 // Sanity check: if the service listed for the app is not one 2300 // we actually are maintaining, just let it drop. 2301 final ServiceRecord curRec = smap.mServicesByName.get(sr.name); 2302 if (curRec != sr) { 2303 if (curRec != null) { 2304 Slog.wtf(TAG, "Service " + sr + " in process " + app 2305 + " not same as in map: " + curRec); 2306 } 2307 continue; 2308 } 2309 2310 // Any services running in the application may need to be placed 2311 // back in the pending list. 2312 if (allowRestart && sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags 2313 &ApplicationInfo.FLAG_PERSISTENT) == 0) { 2314 Slog.w(TAG, "Service crashed " + sr.crashCount 2315 + " times, stopping: " + sr); 2316 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH, 2317 sr.userId, sr.crashCount, sr.shortName, app.pid); 2318 bringDownServiceLocked(sr); 2319 } else if (!allowRestart || !mAm.isUserRunningLocked(sr.userId, false)) { 2320 bringDownServiceLocked(sr); 2321 } else { 2322 boolean canceled = scheduleServiceRestartLocked(sr, true); 2323 2324 // Should the service remain running? Note that in the 2325 // extreme case of so many attempts to deliver a command 2326 // that it failed we also will stop it here. 2327 if (sr.startRequested && (sr.stopIfKilled || canceled)) { 2328 if (sr.pendingStarts.size() == 0) { 2329 sr.startRequested = false; 2330 if (sr.tracker != null) { 2331 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(), 2332 SystemClock.uptimeMillis()); 2333 } 2334 if (!sr.hasAutoCreateConnections()) { 2335 // Whoops, no reason to restart! 2336 bringDownServiceLocked(sr); 2337 } 2338 } 2339 } 2340 } 2341 } 2342 2343 if (!allowRestart) { 2344 app.services.clear(); 2345 2346 // Make sure there are no more restarting services for this process. 2347 for (int i=mRestartingServices.size()-1; i>=0; i--) { 2348 ServiceRecord r = mRestartingServices.get(i); 2349 if (r.processName.equals(app.processName) && 2350 r.serviceInfo.applicationInfo.uid == app.info.uid) { 2351 mRestartingServices.remove(i); 2352 clearRestartingIfNeededLocked(r); 2353 } 2354 } 2355 for (int i=mPendingServices.size()-1; i>=0; i--) { 2356 ServiceRecord r = mPendingServices.get(i); 2357 if (r.processName.equals(app.processName) && 2358 r.serviceInfo.applicationInfo.uid == app.info.uid) { 2359 mPendingServices.remove(i); 2360 } 2361 } 2362 } 2363 2364 // Make sure we have no more records on the stopping list. 2365 int i = mDestroyingServices.size(); 2366 while (i > 0) { 2367 i--; 2368 ServiceRecord sr = mDestroyingServices.get(i); 2369 if (sr.app == app) { 2370 sr.forceClearTracker(); 2371 mDestroyingServices.remove(i); 2372 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr); 2373 } 2374 } 2375 2376 app.executingServices.clear(); 2377 } 2378 makeRunningServiceInfoLocked(ServiceRecord r)2379 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) { 2380 ActivityManager.RunningServiceInfo info = 2381 new ActivityManager.RunningServiceInfo(); 2382 info.service = r.name; 2383 if (r.app != null) { 2384 info.pid = r.app.pid; 2385 } 2386 info.uid = r.appInfo.uid; 2387 info.process = r.processName; 2388 info.foreground = r.isForeground; 2389 info.activeSince = r.createTime; 2390 info.started = r.startRequested; 2391 info.clientCount = r.connections.size(); 2392 info.crashCount = r.crashCount; 2393 info.lastActivityTime = r.lastActivity; 2394 if (r.isForeground) { 2395 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND; 2396 } 2397 if (r.startRequested) { 2398 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED; 2399 } 2400 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) { 2401 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS; 2402 } 2403 if (r.app != null && r.app.persistent) { 2404 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS; 2405 } 2406 2407 for (int conni=r.connections.size()-1; conni>=0; conni--) { 2408 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni); 2409 for (int i=0; i<connl.size(); i++) { 2410 ConnectionRecord conn = connl.get(i); 2411 if (conn.clientLabel != 0) { 2412 info.clientPackage = conn.binding.client.info.packageName; 2413 info.clientLabel = conn.clientLabel; 2414 return info; 2415 } 2416 } 2417 } 2418 return info; 2419 } 2420 getRunningServiceInfoLocked(int maxNum, int flags)2421 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, 2422 int flags) { 2423 ArrayList<ActivityManager.RunningServiceInfo> res 2424 = new ArrayList<ActivityManager.RunningServiceInfo>(); 2425 2426 final int uid = Binder.getCallingUid(); 2427 final long ident = Binder.clearCallingIdentity(); 2428 try { 2429 if (ActivityManager.checkUidPermission( 2430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 2431 uid) == PackageManager.PERMISSION_GRANTED) { 2432 int[] users = mAm.getUsersLocked(); 2433 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) { 2434 ArrayMap<ComponentName, ServiceRecord> alls = getServices(users[ui]); 2435 for (int i=0; i<alls.size() && res.size() < maxNum; i++) { 2436 ServiceRecord sr = alls.valueAt(i); 2437 res.add(makeRunningServiceInfoLocked(sr)); 2438 } 2439 } 2440 2441 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) { 2442 ServiceRecord r = mRestartingServices.get(i); 2443 ActivityManager.RunningServiceInfo info = 2444 makeRunningServiceInfoLocked(r); 2445 info.restarting = r.nextRestartTime; 2446 res.add(info); 2447 } 2448 } else { 2449 int userId = UserHandle.getUserId(uid); 2450 ArrayMap<ComponentName, ServiceRecord> alls = getServices(userId); 2451 for (int i=0; i<alls.size() && res.size() < maxNum; i++) { 2452 ServiceRecord sr = alls.valueAt(i); 2453 res.add(makeRunningServiceInfoLocked(sr)); 2454 } 2455 2456 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) { 2457 ServiceRecord r = mRestartingServices.get(i); 2458 if (r.userId == userId) { 2459 ActivityManager.RunningServiceInfo info = 2460 makeRunningServiceInfoLocked(r); 2461 info.restarting = r.nextRestartTime; 2462 res.add(info); 2463 } 2464 } 2465 } 2466 } finally { 2467 Binder.restoreCallingIdentity(ident); 2468 } 2469 2470 return res; 2471 } 2472 getRunningServiceControlPanelLocked(ComponentName name)2473 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) { 2474 int userId = UserHandle.getUserId(Binder.getCallingUid()); 2475 ServiceRecord r = getServiceByName(name, userId); 2476 if (r != null) { 2477 for (int conni=r.connections.size()-1; conni>=0; conni--) { 2478 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni); 2479 for (int i=0; i<conn.size(); i++) { 2480 if (conn.get(i).clientIntent != null) { 2481 return conn.get(i).clientIntent; 2482 } 2483 } 2484 } 2485 } 2486 return null; 2487 } 2488 serviceTimeout(ProcessRecord proc)2489 void serviceTimeout(ProcessRecord proc) { 2490 String anrMessage = null; 2491 2492 synchronized(mAm) { 2493 if (proc.executingServices.size() == 0 || proc.thread == null) { 2494 return; 2495 } 2496 final long now = SystemClock.uptimeMillis(); 2497 final long maxTime = now - 2498 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT); 2499 ServiceRecord timeout = null; 2500 long nextTime = 0; 2501 for (int i=proc.executingServices.size()-1; i>=0; i--) { 2502 ServiceRecord sr = proc.executingServices.valueAt(i); 2503 if (sr.executingStart < maxTime) { 2504 timeout = sr; 2505 break; 2506 } 2507 if (sr.executingStart > nextTime) { 2508 nextTime = sr.executingStart; 2509 } 2510 } 2511 if (timeout != null && mAm.mLruProcesses.contains(proc)) { 2512 Slog.w(TAG, "Timeout executing service: " + timeout); 2513 StringWriter sw = new StringWriter(); 2514 PrintWriter pw = new FastPrintWriter(sw, false, 1024); 2515 pw.println(timeout); 2516 timeout.dump(pw, " "); 2517 pw.close(); 2518 mLastAnrDump = sw.toString(); 2519 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer); 2520 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS); 2521 anrMessage = "executing service " + timeout.shortName; 2522 } else { 2523 Message msg = mAm.mHandler.obtainMessage( 2524 ActivityManagerService.SERVICE_TIMEOUT_MSG); 2525 msg.obj = proc; 2526 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg 2527 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT)); 2528 } 2529 } 2530 2531 if (anrMessage != null) { 2532 mAm.appNotResponding(proc, null, null, false, anrMessage); 2533 } 2534 } 2535 scheduleServiceTimeoutLocked(ProcessRecord proc)2536 void scheduleServiceTimeoutLocked(ProcessRecord proc) { 2537 if (proc.executingServices.size() == 0 || proc.thread == null) { 2538 return; 2539 } 2540 long now = SystemClock.uptimeMillis(); 2541 Message msg = mAm.mHandler.obtainMessage( 2542 ActivityManagerService.SERVICE_TIMEOUT_MSG); 2543 msg.obj = proc; 2544 mAm.mHandler.sendMessageAtTime(msg, 2545 proc.execServicesFg ? (now+SERVICE_TIMEOUT) : (now+ SERVICE_BACKGROUND_TIMEOUT)); 2546 } 2547 2548 /** 2549 * Prints a list of ServiceRecords (dumpsys activity services) 2550 */ dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)2551 void dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 2552 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 2553 boolean needSep = false; 2554 boolean printedAnything = false; 2555 2556 ItemMatcher matcher = new ItemMatcher(); 2557 matcher.build(args, opti); 2558 2559 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)"); 2560 try { 2561 if (mLastAnrDump != null) { 2562 pw.println(" Last ANR service:"); 2563 pw.print(mLastAnrDump); 2564 pw.println(); 2565 } 2566 int[] users = mAm.getUsersLocked(); 2567 for (int user : users) { 2568 ServiceMap smap = getServiceMap(user); 2569 boolean printed = false; 2570 if (smap.mServicesByName.size() > 0) { 2571 long nowReal = SystemClock.elapsedRealtime(); 2572 needSep = false; 2573 for (int si=0; si<smap.mServicesByName.size(); si++) { 2574 ServiceRecord r = smap.mServicesByName.valueAt(si); 2575 if (!matcher.match(r, r.name)) { 2576 continue; 2577 } 2578 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 2579 continue; 2580 } 2581 if (!printed) { 2582 if (printedAnything) { 2583 pw.println(); 2584 } 2585 pw.println(" User " + user + " active services:"); 2586 printed = true; 2587 } 2588 printedAnything = true; 2589 if (needSep) { 2590 pw.println(); 2591 } 2592 pw.print(" * "); 2593 pw.println(r); 2594 if (dumpAll) { 2595 r.dump(pw, " "); 2596 needSep = true; 2597 } else { 2598 pw.print(" app="); 2599 pw.println(r.app); 2600 pw.print(" created="); 2601 TimeUtils.formatDuration(r.createTime, nowReal, pw); 2602 pw.print(" started="); 2603 pw.print(r.startRequested); 2604 pw.print(" connections="); 2605 pw.println(r.connections.size()); 2606 if (r.connections.size() > 0) { 2607 pw.println(" Connections:"); 2608 for (int conni=0; conni<r.connections.size(); conni++) { 2609 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni); 2610 for (int i = 0; i < clist.size(); i++) { 2611 ConnectionRecord conn = clist.get(i); 2612 pw.print(" "); 2613 pw.print(conn.binding.intent.intent.getIntent() 2614 .toShortString(false, false, false, false)); 2615 pw.print(" -> "); 2616 ProcessRecord proc = conn.binding.client; 2617 pw.println(proc != null ? proc.toShortString() : "null"); 2618 } 2619 } 2620 } 2621 } 2622 if (dumpClient && r.app != null && r.app.thread != null) { 2623 pw.println(" Client:"); 2624 pw.flush(); 2625 try { 2626 TransferPipe tp = new TransferPipe(); 2627 try { 2628 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), 2629 r, args); 2630 tp.setBufferPrefix(" "); 2631 // Short timeout, since blocking here can 2632 // deadlock with the application. 2633 tp.go(fd, 2000); 2634 } finally { 2635 tp.kill(); 2636 } 2637 } catch (IOException e) { 2638 pw.println(" Failure while dumping the service: " + e); 2639 } catch (RemoteException e) { 2640 pw.println(" Got a RemoteException while dumping the service"); 2641 } 2642 needSep = true; 2643 } 2644 } 2645 needSep |= printed; 2646 } 2647 printed = false; 2648 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) { 2649 ServiceRecord r = smap.mDelayedStartList.get(si); 2650 if (!matcher.match(r, r.name)) { 2651 continue; 2652 } 2653 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 2654 continue; 2655 } 2656 if (!printed) { 2657 if (printedAnything) { 2658 pw.println(); 2659 } 2660 pw.println(" User " + user + " delayed start services:"); 2661 printed = true; 2662 } 2663 printedAnything = true; 2664 pw.print(" * Delayed start "); pw.println(r); 2665 } 2666 printed = false; 2667 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) { 2668 ServiceRecord r = smap.mStartingBackground.get(si); 2669 if (!matcher.match(r, r.name)) { 2670 continue; 2671 } 2672 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 2673 continue; 2674 } 2675 if (!printed) { 2676 if (printedAnything) { 2677 pw.println(); 2678 } 2679 pw.println(" User " + user + " starting in background:"); 2680 printed = true; 2681 } 2682 printedAnything = true; 2683 pw.print(" * Starting bg "); pw.println(r); 2684 } 2685 } 2686 } catch (Exception e) { 2687 Slog.w(TAG, "Exception in dumpServicesLocked", e); 2688 } 2689 2690 if (mPendingServices.size() > 0) { 2691 boolean printed = false; 2692 for (int i=0; i<mPendingServices.size(); i++) { 2693 ServiceRecord r = mPendingServices.get(i); 2694 if (!matcher.match(r, r.name)) { 2695 continue; 2696 } 2697 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 2698 continue; 2699 } 2700 printedAnything = true; 2701 if (!printed) { 2702 if (needSep) pw.println(); 2703 needSep = true; 2704 pw.println(" Pending services:"); 2705 printed = true; 2706 } 2707 pw.print(" * Pending "); pw.println(r); 2708 r.dump(pw, " "); 2709 } 2710 needSep = true; 2711 } 2712 2713 if (mRestartingServices.size() > 0) { 2714 boolean printed = false; 2715 for (int i=0; i<mRestartingServices.size(); i++) { 2716 ServiceRecord r = mRestartingServices.get(i); 2717 if (!matcher.match(r, r.name)) { 2718 continue; 2719 } 2720 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 2721 continue; 2722 } 2723 printedAnything = true; 2724 if (!printed) { 2725 if (needSep) pw.println(); 2726 needSep = true; 2727 pw.println(" Restarting services:"); 2728 printed = true; 2729 } 2730 pw.print(" * Restarting "); pw.println(r); 2731 r.dump(pw, " "); 2732 } 2733 needSep = true; 2734 } 2735 2736 if (mDestroyingServices.size() > 0) { 2737 boolean printed = false; 2738 for (int i=0; i< mDestroyingServices.size(); i++) { 2739 ServiceRecord r = mDestroyingServices.get(i); 2740 if (!matcher.match(r, r.name)) { 2741 continue; 2742 } 2743 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) { 2744 continue; 2745 } 2746 printedAnything = true; 2747 if (!printed) { 2748 if (needSep) pw.println(); 2749 needSep = true; 2750 pw.println(" Destroying services:"); 2751 printed = true; 2752 } 2753 pw.print(" * Destroy "); pw.println(r); 2754 r.dump(pw, " "); 2755 } 2756 needSep = true; 2757 } 2758 2759 if (dumpAll) { 2760 boolean printed = false; 2761 for (int ic=0; ic<mServiceConnections.size(); ic++) { 2762 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic); 2763 for (int i=0; i<r.size(); i++) { 2764 ConnectionRecord cr = r.get(i); 2765 if (!matcher.match(cr.binding.service, cr.binding.service.name)) { 2766 continue; 2767 } 2768 if (dumpPackage != null && (cr.binding.client == null 2769 || !dumpPackage.equals(cr.binding.client.info.packageName))) { 2770 continue; 2771 } 2772 printedAnything = true; 2773 if (!printed) { 2774 if (needSep) pw.println(); 2775 needSep = true; 2776 pw.println(" Connection bindings to services:"); 2777 printed = true; 2778 } 2779 pw.print(" * "); pw.println(cr); 2780 cr.dump(pw, " "); 2781 } 2782 } 2783 } 2784 2785 if (!printedAnything) { 2786 pw.println(" (nothing)"); 2787 } 2788 } 2789 2790 /** 2791 * There are three ways to call this: 2792 * - no service specified: dump all the services 2793 * - a flattened component name that matched an existing service was specified as the 2794 * first arg: dump that one service 2795 * - the first arg isn't the flattened component name of an existing service: 2796 * dump all services whose component contains the first arg as a substring 2797 */ dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)2798 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args, 2799 int opti, boolean dumpAll) { 2800 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>(); 2801 2802 synchronized (mAm) { 2803 int[] users = mAm.getUsersLocked(); 2804 if ("all".equals(name)) { 2805 for (int user : users) { 2806 ServiceMap smap = mServiceMap.get(user); 2807 if (smap == null) { 2808 continue; 2809 } 2810 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName; 2811 for (int i=0; i<alls.size(); i++) { 2812 ServiceRecord r1 = alls.valueAt(i); 2813 services.add(r1); 2814 } 2815 } 2816 } else { 2817 ComponentName componentName = name != null 2818 ? ComponentName.unflattenFromString(name) : null; 2819 int objectId = 0; 2820 if (componentName == null) { 2821 // Not a '/' separated full component name; maybe an object ID? 2822 try { 2823 objectId = Integer.parseInt(name, 16); 2824 name = null; 2825 componentName = null; 2826 } catch (RuntimeException e) { 2827 } 2828 } 2829 2830 for (int user : users) { 2831 ServiceMap smap = mServiceMap.get(user); 2832 if (smap == null) { 2833 continue; 2834 } 2835 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName; 2836 for (int i=0; i<alls.size(); i++) { 2837 ServiceRecord r1 = alls.valueAt(i); 2838 if (componentName != null) { 2839 if (r1.name.equals(componentName)) { 2840 services.add(r1); 2841 } 2842 } else if (name != null) { 2843 if (r1.name.flattenToString().contains(name)) { 2844 services.add(r1); 2845 } 2846 } else if (System.identityHashCode(r1) == objectId) { 2847 services.add(r1); 2848 } 2849 } 2850 } 2851 } 2852 } 2853 2854 if (services.size() <= 0) { 2855 return false; 2856 } 2857 2858 boolean needSep = false; 2859 for (int i=0; i<services.size(); i++) { 2860 if (needSep) { 2861 pw.println(); 2862 } 2863 needSep = true; 2864 dumpService("", fd, pw, services.get(i), args, dumpAll); 2865 } 2866 return true; 2867 } 2868 2869 /** 2870 * Invokes IApplicationThread.dumpService() on the thread of the specified service if 2871 * there is a thread associated with the service. 2872 */ dumpService(String prefix, FileDescriptor fd, PrintWriter pw, final ServiceRecord r, String[] args, boolean dumpAll)2873 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw, 2874 final ServiceRecord r, String[] args, boolean dumpAll) { 2875 String innerPrefix = prefix + " "; 2876 synchronized (mAm) { 2877 pw.print(prefix); pw.print("SERVICE "); 2878 pw.print(r.shortName); pw.print(" "); 2879 pw.print(Integer.toHexString(System.identityHashCode(r))); 2880 pw.print(" pid="); 2881 if (r.app != null) pw.println(r.app.pid); 2882 else pw.println("(not running)"); 2883 if (dumpAll) { 2884 r.dump(pw, innerPrefix); 2885 } 2886 } 2887 if (r.app != null && r.app.thread != null) { 2888 pw.print(prefix); pw.println(" Client:"); 2889 pw.flush(); 2890 try { 2891 TransferPipe tp = new TransferPipe(); 2892 try { 2893 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args); 2894 tp.setBufferPrefix(prefix + " "); 2895 tp.go(fd); 2896 } finally { 2897 tp.kill(); 2898 } 2899 } catch (IOException e) { 2900 pw.println(prefix + " Failure while dumping the service: " + e); 2901 } catch (RemoteException e) { 2902 pw.println(prefix + " Got a RemoteException while dumping the service"); 2903 } 2904 } 2905 } 2906 2907 } 2908