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