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