1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.am; 18 19 import static android.app.ActivityManagerInternal.OOM_ADJ_REASON_ACTIVITY; 20 21 import static com.android.internal.util.Preconditions.checkArgument; 22 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 23 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 24 import static com.android.server.am.ActivityManagerService.MY_PID; 25 26 import static java.util.Objects.requireNonNull; 27 28 import android.annotation.NonNull; 29 import android.annotation.Nullable; 30 import android.app.ActivityManager; 31 import android.app.ApplicationExitInfo; 32 import android.app.ApplicationExitInfo.Reason; 33 import android.app.ApplicationExitInfo.SubReason; 34 import android.app.BackgroundStartPrivileges; 35 import android.app.IApplicationThread; 36 import android.content.pm.ApplicationInfo; 37 import android.content.pm.PackageManagerInternal; 38 import android.content.pm.ProcessInfo; 39 import android.content.pm.VersionedPackage; 40 import android.content.res.CompatibilityInfo; 41 import android.os.Binder; 42 import android.os.Bundle; 43 import android.os.IBinder; 44 import android.os.Process; 45 import android.os.RemoteException; 46 import android.os.SystemClock; 47 import android.os.Trace; 48 import android.os.UserHandle; 49 import android.server.ServerProtoEnums; 50 import android.system.OsConstants; 51 import android.util.ArrayMap; 52 import android.util.ArraySet; 53 import android.util.DebugUtils; 54 import android.util.EventLog; 55 import android.util.Slog; 56 import android.util.TimeUtils; 57 import android.util.proto.ProtoOutputStream; 58 59 import com.android.internal.annotations.CompositeRWLock; 60 import com.android.internal.annotations.GuardedBy; 61 import com.android.internal.annotations.VisibleForTesting; 62 import com.android.internal.app.procstats.ProcessState; 63 import com.android.internal.app.procstats.ProcessStats; 64 import com.android.internal.os.Zygote; 65 import com.android.server.FgThread; 66 import com.android.server.wm.WindowProcessController; 67 import com.android.server.wm.WindowProcessListener; 68 69 import java.io.PrintWriter; 70 import java.util.Arrays; 71 import java.util.List; 72 73 /** 74 * Full information about a particular process that 75 * is currently running. 76 */ 77 class ProcessRecord implements WindowProcessListener { 78 static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM; 79 80 final ActivityManagerService mService; // where we came from 81 private final ActivityManagerGlobalLock mProcLock; 82 83 // ========================================================= 84 // Basic info of the process, immutable or semi-immutable over 85 // the lifecycle of the process 86 // ========================================================= 87 volatile ApplicationInfo info; // all about the first app in the process 88 final ProcessInfo processInfo; // if non-null, process-specific manifest info 89 final boolean isolated; // true if this is a special isolated process 90 public final boolean isSdkSandbox; // true if this is an SDK sandbox process 91 final boolean appZygote; // true if this is forked from the app zygote 92 final int uid; // uid of process; may be different from 'info' if isolated 93 final int userId; // user of process. 94 final String processName; // name of the process 95 final String sdkSandboxClientAppPackage; // if this is an sdk sandbox process, name of the 96 // app package for which it is running 97 final String sdkSandboxClientAppVolumeUuid; // uuid of the app for which the sandbox is running 98 99 /** 100 * Overall state of process's uid. 101 */ 102 @CompositeRWLock({"mService", "mProcLock"}) 103 private UidRecord mUidRecord; 104 105 /** 106 * List of packages running in the process. 107 */ 108 private final PackageList mPkgList = new PackageList(this); 109 110 /** 111 * Additional packages we have a dependency on. 112 */ 113 @CompositeRWLock({"mService", "mProcLock"}) 114 private ArraySet<String> mPkgDeps; 115 116 /** 117 * The process of this application; 0 if none. 118 */ 119 @CompositeRWLock({"mService", "mProcLock"}) 120 int mPid; 121 122 /** 123 * The process ID which will be set when we're killing this process. 124 */ 125 @GuardedBy("mService") 126 private int mDyingPid; 127 128 /** 129 * The gids this process was launched with. 130 */ 131 @GuardedBy("mService") 132 private int[] mGids; 133 134 /** 135 * The ABI this process was launched with. 136 */ 137 @GuardedBy("mService") 138 private String mRequiredAbi; 139 140 /** 141 * The instruction set this process was launched with. 142 */ 143 @GuardedBy("mService") 144 private String mInstructionSet; 145 146 /** 147 * The actual proc... may be null only if 'persistent' is true 148 * (in which case we are in the process of launching the app). 149 */ 150 @CompositeRWLock({"mService", "mProcLock"}) 151 private IApplicationThread mThread; 152 153 /** 154 * Instance of {@link #mThread} that will always meet the {@code oneway} 155 * contract, possibly by using {@link SameProcessApplicationThread}. 156 */ 157 @CompositeRWLock({"mService", "mProcLock"}) 158 private IApplicationThread mOnewayThread; 159 160 /** 161 * Always keep this application running? 162 */ 163 private volatile boolean mPersistent; 164 165 /** 166 * Caching of toShortString() result. 167 * <p>Note: No lock here, it doesn't matter in case of race condition</p> 168 */ 169 private String mShortStringName; 170 171 /** 172 * Caching of toString() result. 173 * <p>Note: No lock here, it doesn't matter in case of race condition</p> 174 */ 175 private String mStringName; 176 177 /** 178 * Process start is pending. 179 */ 180 @GuardedBy("mService") 181 private boolean mPendingStart; 182 183 /** 184 * Process finish attach application is pending. 185 */ 186 @GuardedBy("mService") 187 private boolean mPendingFinishAttach; 188 189 /** 190 * Seq no. Indicating the latest process start associated with this process record. 191 */ 192 @GuardedBy("mService") 193 private long mStartSeq; 194 195 /** 196 * Params used in starting this process. 197 */ 198 private volatile HostingRecord mHostingRecord; 199 200 /** 201 * Selinux info of this process. 202 */ 203 private volatile String mSeInfo; 204 205 /** 206 * When the process is started. (before zygote fork) 207 */ 208 private volatile long mStartUptime; 209 210 /** 211 * When the process is started. (before zygote fork) 212 */ 213 private volatile long mStartElapsedTime; 214 215 /** 216 * When the process was sent the bindApplication request 217 */ 218 private volatile long mBindApplicationTime; 219 220 /** 221 * This will be same as {@link #uid} usually except for some apps used during factory testing. 222 */ 223 private volatile int mStartUid; 224 225 /** 226 * Indicates how the external storage was mounted for this process. 227 */ 228 private volatile int mMountMode; 229 230 /** 231 * True if Android/obb and Android/data need to be bind mount. 232 */ 233 private volatile boolean mBindMountPending; 234 235 /** 236 * True when proc was started in user unlocked state. 237 */ 238 @GuardedBy("mProcLock") 239 private boolean mUnlocked; 240 241 /** 242 * TID for RenderThread. 243 */ 244 @GuardedBy("mProcLock") 245 private int mRenderThreadTid; 246 247 /** 248 * Last used compatibility mode. 249 */ 250 @GuardedBy("mService") 251 private CompatibilityInfo mCompat; 252 253 /** 254 * Set of disabled compat changes for the process (all others are enabled). 255 */ 256 @GuardedBy("mService") 257 private long[] mDisabledCompatChanges; 258 259 /** 260 * Who is watching for the death. 261 */ 262 @GuardedBy("mService") 263 private IBinder.DeathRecipient mDeathRecipient; 264 265 /** 266 * Set to currently active instrumentation running in process. 267 */ 268 @CompositeRWLock({"mService", "mProcLock"}) 269 private ActiveInstrumentation mInstr; 270 271 /** 272 * True when proc has been killed by activity manager, not for RAM. 273 */ 274 @CompositeRWLock({"mService", "mProcLock"}) 275 private boolean mKilledByAm; 276 277 /** 278 * True once we know the process has been killed. 279 */ 280 @CompositeRWLock({"mService", "mProcLock"}) 281 private boolean mKilled; 282 283 /** 284 * The timestamp in uptime when this process was killed. 285 */ 286 @CompositeRWLock({"mService", "mProcLock"}) 287 private long mKillTime; 288 289 /** 290 * Process is waiting to be killed when in the bg, and reason. 291 */ 292 @GuardedBy("mService") 293 private String mWaitingToKill; 294 295 /** 296 * Whether this process should be killed and removed from process list. 297 * It is set when the package is force-stopped or the process has crashed too many times. 298 */ 299 private volatile boolean mRemoved; 300 301 /** 302 * Was app launched for debugging? 303 */ 304 @GuardedBy("mService") 305 private boolean mDebugging; 306 307 /** 308 * Has process show wait for debugger dialog? 309 */ 310 @GuardedBy("mProcLock") 311 private boolean mWaitedForDebugger; 312 313 /** 314 * For managing the LRU list. 315 */ 316 @CompositeRWLock({"mService", "mProcLock"}) 317 private long mLastActivityTime; 318 319 /** 320 * Set to true when process was launched with a wrapper attached. 321 */ 322 @GuardedBy("mService") 323 private boolean mUsingWrapper; 324 325 /** 326 * Sequence id for identifying LRU update cycles. 327 */ 328 @GuardedBy("mService") 329 private int mLruSeq; 330 331 /** 332 * Class to run on start if this is a special isolated process. 333 */ 334 @GuardedBy("mService") 335 private String mIsolatedEntryPoint; 336 337 /** 338 * Arguments to pass to isolatedEntryPoint's main(). 339 */ 340 @GuardedBy("mService") 341 private String[] mIsolatedEntryPointArgs; 342 343 /** 344 * Process is currently hosting a backup agent for backup or restore. 345 */ 346 @GuardedBy("mService") 347 private boolean mInFullBackup; 348 349 /** 350 * A set of tokens that currently contribute to this process being temporarily allowed 351 * to start certain components (eg. activities or foreground services) even if it's not 352 * in the foreground. 353 */ 354 @GuardedBy("mBackgroundStartPrivileges") 355 private final ArrayMap<Binder, BackgroundStartPrivileges> mBackgroundStartPrivileges = 356 new ArrayMap<>(); 357 358 /** 359 * The merged BackgroundStartPrivileges based on what's in {@link #mBackgroundStartPrivileges}. 360 * This is lazily generated using {@link #getBackgroundStartPrivileges()}. 361 */ 362 @Nullable 363 @GuardedBy("mBackgroundStartPrivileges") 364 private BackgroundStartPrivileges mBackgroundStartPrivilegesMerged = 365 BackgroundStartPrivileges.NONE; 366 367 /** 368 * Controller for driving the process state on the window manager side. 369 */ 370 private final WindowProcessController mWindowProcessController; 371 372 /** 373 * Profiling info of the process, such as PSS, cpu, etc. 374 */ 375 final ProcessProfileRecord mProfile; 376 377 /** 378 * All about the services in this process. 379 */ 380 final ProcessServiceRecord mServices; 381 382 /** 383 * All about the providers in this process. 384 */ 385 final ProcessProviderRecord mProviders; 386 387 /** 388 * All about the receivers in this process. 389 */ 390 final ProcessReceiverRecord mReceivers; 391 392 /** 393 * All about the error state(crash, ANR) in this process. 394 */ 395 final ProcessErrorStateRecord mErrorState; 396 397 /** 398 * All about the process state info (proc state, oom adj score) in this process. 399 */ 400 final ProcessStateRecord mState; 401 402 /** 403 * All about the state info of the optimizer when the process is cached. 404 */ 405 final ProcessCachedOptimizerRecord mOptRecord; 406 407 /** 408 * The preceding instance of the process, which would exist when the previous process is killed 409 * but not fully dead yet; in this case, the new instance of the process should be held until 410 * this preceding instance is fully dead. 411 */ 412 volatile ProcessRecord mPredecessor; 413 414 /** 415 * The succeeding instance of the process, which is going to be started after this process 416 * is killed successfully. 417 */ 418 volatile ProcessRecord mSuccessor; 419 420 /** 421 * The routine to start its successor process. 422 * 423 * <p>Note: It should be accessed from process start thread only.</p> 424 */ 425 Runnable mSuccessorStartRunnable; 426 427 /** 428 * Whether or not the process group of this process has been created. 429 */ 430 volatile boolean mProcessGroupCreated; 431 432 /** 433 * Whether or not we should skip the process group creation. 434 */ 435 volatile boolean mSkipProcessGroupCreation; 436 setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, long startUptime, long startElapsedTime)437 void setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, 438 long startUptime, long startElapsedTime) { 439 this.mStartUid = startUid; 440 this.mHostingRecord = hostingRecord; 441 this.mSeInfo = seInfo; 442 this.mStartUptime = startUptime; 443 this.mStartElapsedTime = startElapsedTime; 444 } 445 446 @GuardedBy({"mService", "mProcLock"}) dump(PrintWriter pw, String prefix)447 void dump(PrintWriter pw, String prefix) { 448 final long nowUptime = SystemClock.uptimeMillis(); 449 final long nowElapsedTime = SystemClock.elapsedRealtime(); 450 451 pw.print(prefix); pw.print("user #"); pw.print(userId); 452 pw.print(" uid="); pw.print(info.uid); 453 if (uid != info.uid) { 454 pw.print(" ISOLATED uid="); pw.print(uid); 455 } 456 pw.print(" gids={"); 457 if (mGids != null) { 458 for (int gi = 0; gi < mGids.length; gi++) { 459 if (gi != 0) pw.print(", "); 460 pw.print(mGids[gi]); 461 462 } 463 } 464 pw.println("}"); 465 if (processInfo != null) { 466 pw.print(prefix); pw.println("processInfo:"); 467 if (processInfo.deniedPermissions != null) { 468 for (int i = 0; i < processInfo.deniedPermissions.size(); i++) { 469 pw.print(prefix); pw.print(" deny: "); 470 pw.println(processInfo.deniedPermissions.valueAt(i)); 471 } 472 } 473 if (processInfo.gwpAsanMode != ApplicationInfo.GWP_ASAN_DEFAULT) { 474 pw.print(prefix); pw.println(" gwpAsanMode=" + processInfo.gwpAsanMode); 475 } 476 if (processInfo.memtagMode != ApplicationInfo.MEMTAG_DEFAULT) { 477 pw.print(prefix); pw.println(" memtagMode=" + processInfo.memtagMode); 478 } 479 } 480 pw.print(prefix); pw.print("mRequiredAbi="); pw.print(mRequiredAbi); 481 pw.print(" instructionSet="); pw.println(mInstructionSet); 482 if (info.className != null) { 483 pw.print(prefix); pw.print("class="); pw.println(info.className); 484 } 485 if (info.manageSpaceActivityName != null) { 486 pw.print(prefix); pw.print("manageSpaceActivityName="); 487 pw.println(info.manageSpaceActivityName); 488 } 489 490 pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir); 491 pw.print(" publicDir="); pw.print(info.publicSourceDir); 492 pw.print(" data="); pw.println(info.dataDir); 493 mPkgList.dump(pw, prefix); 494 if (mPkgDeps != null) { 495 pw.print(prefix); pw.print("packageDependencies={"); 496 for (int i = 0; i < mPkgDeps.size(); i++) { 497 if (i > 0) pw.print(", "); 498 pw.print(mPkgDeps.valueAt(i)); 499 } 500 pw.println("}"); 501 } 502 pw.print(prefix); pw.print("compat="); pw.println(mCompat); 503 if (mInstr != null) { 504 pw.print(prefix); pw.print("mInstr="); pw.println(mInstr); 505 } 506 pw.print(prefix); pw.print("thread="); pw.println(mThread); 507 pw.print(prefix); pw.print("pid="); pw.println(mPid); 508 pw.print(prefix); pw.print("lastActivityTime="); 509 TimeUtils.formatDuration(mLastActivityTime, nowUptime, pw); 510 pw.print(prefix); pw.print("startUptimeTime="); 511 TimeUtils.formatDuration(mStartElapsedTime, nowUptime, pw); 512 pw.print(prefix); pw.print("startElapsedTime="); 513 TimeUtils.formatDuration(mStartElapsedTime, nowElapsedTime, pw); 514 pw.println(); 515 if (mPersistent || mRemoved) { 516 pw.print(prefix); pw.print("persistent="); pw.print(mPersistent); 517 pw.print(" removed="); pw.println(mRemoved); 518 } 519 if (mDebugging) { 520 pw.print(prefix); pw.print("mDebugging="); pw.println(mDebugging); 521 } 522 if (mPendingStart) { 523 pw.print(prefix); pw.print("pendingStart="); pw.println(mPendingStart); 524 } 525 pw.print(prefix); pw.print("startSeq="); pw.println(mStartSeq); 526 pw.print(prefix); pw.print("mountMode="); pw.println( 527 DebugUtils.valueToString(Zygote.class, "MOUNT_EXTERNAL_", mMountMode)); 528 if (mKilled || mKilledByAm || mWaitingToKill != null) { 529 pw.print(prefix); pw.print("killed="); pw.print(mKilled); 530 pw.print(" killedByAm="); pw.print(mKilledByAm); 531 pw.print(" waitingToKill="); pw.println(mWaitingToKill); 532 } 533 if (mIsolatedEntryPoint != null || mIsolatedEntryPointArgs != null) { 534 pw.print(prefix); pw.print("isolatedEntryPoint="); pw.println(mIsolatedEntryPoint); 535 pw.print(prefix); pw.print("isolatedEntryPointArgs="); 536 pw.println(Arrays.toString(mIsolatedEntryPointArgs)); 537 } 538 if (mState.getSetProcState() > ActivityManager.PROCESS_STATE_SERVICE) { 539 mProfile.dumpCputime(pw, prefix); 540 } 541 mProfile.dumpPss(pw, prefix, nowUptime); 542 mState.dump(pw, prefix, nowUptime); 543 mErrorState.dump(pw, prefix, nowUptime); 544 mServices.dump(pw, prefix, nowUptime); 545 mProviders.dump(pw, prefix, nowUptime); 546 mReceivers.dump(pw, prefix, nowUptime); 547 mOptRecord.dump(pw, prefix, nowUptime); 548 mWindowProcessController.dump(pw, prefix); 549 } 550 ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid)551 ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, 552 int _uid) { 553 this(_service, _info, _processName, _uid, null, -1, null); 554 } 555 ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid, String _sdkSandboxClientAppPackage, int _definingUid, String _definingProcessName)556 ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, 557 int _uid, String _sdkSandboxClientAppPackage, int _definingUid, 558 String _definingProcessName) { 559 mService = _service; 560 mProcLock = _service.mProcLock; 561 info = _info; 562 ProcessInfo procInfo = null; 563 if (_service.mPackageManagerInt != null) { 564 if (_definingUid > 0) { 565 ArrayMap<String, ProcessInfo> processes = 566 _service.mPackageManagerInt.getProcessesForUid(_definingUid); 567 if (processes != null) procInfo = processes.get(_definingProcessName); 568 } else { 569 ArrayMap<String, ProcessInfo> processes = 570 _service.mPackageManagerInt.getProcessesForUid(_uid); 571 if (processes != null) procInfo = processes.get(_processName); 572 } 573 if (procInfo != null && procInfo.deniedPermissions == null 574 && procInfo.gwpAsanMode == ApplicationInfo.GWP_ASAN_DEFAULT 575 && procInfo.memtagMode == ApplicationInfo.MEMTAG_DEFAULT 576 && procInfo.nativeHeapZeroInitialized == ApplicationInfo.ZEROINIT_DEFAULT) { 577 // If this process hasn't asked for permissions to be denied, or for a 578 // non-default GwpAsan mode, or any other non-default setting, then we don't 579 // care about it. 580 procInfo = null; 581 } 582 } 583 processInfo = procInfo; 584 isolated = Process.isIsolated(_uid); 585 isSdkSandbox = Process.isSdkSandboxUid(_uid); 586 appZygote = (UserHandle.getAppId(_uid) >= Process.FIRST_APP_ZYGOTE_ISOLATED_UID 587 && UserHandle.getAppId(_uid) <= Process.LAST_APP_ZYGOTE_ISOLATED_UID); 588 uid = _uid; 589 userId = UserHandle.getUserId(_uid); 590 processName = _processName; 591 sdkSandboxClientAppPackage = _sdkSandboxClientAppPackage; 592 if (isSdkSandbox) { 593 final ApplicationInfo clientInfo = getClientInfoForSdkSandbox(); 594 sdkSandboxClientAppVolumeUuid = clientInfo != null 595 ? clientInfo.volumeUuid : null; 596 } else { 597 sdkSandboxClientAppVolumeUuid = null; 598 } 599 mPersistent = false; 600 mRemoved = false; 601 mProfile = new ProcessProfileRecord(this); 602 mServices = new ProcessServiceRecord(this); 603 mProviders = new ProcessProviderRecord(this); 604 mReceivers = new ProcessReceiverRecord(this); 605 mErrorState = new ProcessErrorStateRecord(this); 606 mState = new ProcessStateRecord(this); 607 mOptRecord = new ProcessCachedOptimizerRecord(this); 608 final long now = SystemClock.uptimeMillis(); 609 mProfile.init(now); 610 mOptRecord.init(now); 611 mState.init(now); 612 mWindowProcessController = new WindowProcessController( 613 mService.mActivityTaskManager, info, processName, uid, userId, this, this); 614 mPkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.longVersionCode)); 615 } 616 617 @GuardedBy(anyOf = {"mService", "mProcLock"}) getUidRecord()618 UidRecord getUidRecord() { 619 return mUidRecord; 620 } 621 622 @GuardedBy({"mService", "mProcLock"}) setUidRecord(UidRecord uidRecord)623 void setUidRecord(UidRecord uidRecord) { 624 mUidRecord = uidRecord; 625 } 626 getPkgList()627 PackageList getPkgList() { 628 return mPkgList; 629 } 630 631 @GuardedBy(anyOf = {"mService", "mProcLock"}) getPkgDeps()632 ArraySet<String> getPkgDeps() { 633 return mPkgDeps; 634 } 635 636 @GuardedBy({"mService", "mProcLock"}) setPkgDeps(ArraySet<String> pkgDeps)637 void setPkgDeps(ArraySet<String> pkgDeps) { 638 mPkgDeps = pkgDeps; 639 } 640 641 @GuardedBy(anyOf = {"mService", "mProcLock"}) getPid()642 int getPid() { 643 return mPid; 644 } 645 646 @GuardedBy({"mService", "mProcLock"}) setPid(int pid)647 void setPid(int pid) { 648 mPid = pid; 649 mWindowProcessController.setPid(pid); 650 mShortStringName = null; 651 mStringName = null; 652 synchronized (mProfile.mProfilerLock) { 653 mProfile.setPid(pid); 654 } 655 } 656 657 @GuardedBy({"mService", "mProcLock"}) getSetAdj()658 int getSetAdj() { 659 return mState.getSetAdj(); 660 } 661 662 @GuardedBy(anyOf = {"mService", "mProcLock"}) getThread()663 IApplicationThread getThread() { 664 return mThread; 665 } 666 667 @GuardedBy(anyOf = {"mService", "mProcLock"}) getOnewayThread()668 IApplicationThread getOnewayThread() { 669 return mOnewayThread; 670 } 671 672 @GuardedBy(anyOf = {"mService", "mProcLock"}) getCurProcState()673 int getCurProcState() { 674 return mState.getCurProcState(); 675 } 676 677 @GuardedBy(anyOf = {"mService", "mProcLock"}) getSetProcState()678 int getSetProcState() { 679 return mState.getSetProcState(); 680 } 681 682 @GuardedBy({"mService", "mProcLock"}) makeActive(IApplicationThread thread, ProcessStatsService tracker)683 public void makeActive(IApplicationThread thread, ProcessStatsService tracker) { 684 mProfile.onProcessActive(thread, tracker); 685 mThread = thread; 686 if (mPid == Process.myPid()) { 687 mOnewayThread = new SameProcessApplicationThread(thread, FgThread.getHandler()); 688 } else { 689 mOnewayThread = thread; 690 } 691 mWindowProcessController.setThread(thread); 692 } 693 694 @GuardedBy({"mService", "mProcLock"}) makeInactive(ProcessStatsService tracker)695 public void makeInactive(ProcessStatsService tracker) { 696 mThread = null; 697 mOnewayThread = null; 698 mWindowProcessController.setThread(null); 699 mProfile.onProcessInactive(tracker); 700 } 701 702 @GuardedBy("mService") getDyingPid()703 int getDyingPid() { 704 return mDyingPid; 705 } 706 707 @GuardedBy("mService") setDyingPid(int dyingPid)708 void setDyingPid(int dyingPid) { 709 mDyingPid = dyingPid; 710 } 711 712 @GuardedBy("mService") getGids()713 int[] getGids() { 714 return mGids; 715 } 716 717 @GuardedBy("mService") setGids(int[] gids)718 void setGids(int[] gids) { 719 mGids = gids; 720 } 721 722 @GuardedBy("mService") getRequiredAbi()723 String getRequiredAbi() { 724 return mRequiredAbi; 725 } 726 727 @GuardedBy("mService") setRequiredAbi(String requiredAbi)728 void setRequiredAbi(String requiredAbi) { 729 mRequiredAbi = requiredAbi; 730 mWindowProcessController.setRequiredAbi(requiredAbi); 731 } 732 733 @GuardedBy("mService") getInstructionSet()734 String getInstructionSet() { 735 return mInstructionSet; 736 } 737 738 @GuardedBy("mService") setInstructionSet(String instructionSet)739 void setInstructionSet(String instructionSet) { 740 mInstructionSet = instructionSet; 741 } 742 setPersistent(boolean persistent)743 void setPersistent(boolean persistent) { 744 mPersistent = persistent; 745 mWindowProcessController.setPersistent(persistent); 746 } 747 isPersistent()748 boolean isPersistent() { 749 return mPersistent; 750 } 751 752 @GuardedBy("mService") isPendingStart()753 boolean isPendingStart() { 754 return mPendingStart; 755 } 756 757 @GuardedBy("mService") setPendingStart(boolean pendingStart)758 void setPendingStart(boolean pendingStart) { 759 mPendingStart = pendingStart; 760 } 761 762 @GuardedBy("mService") setPendingFinishAttach(boolean pendingFinishAttach)763 void setPendingFinishAttach(boolean pendingFinishAttach) { 764 mPendingFinishAttach = pendingFinishAttach; 765 } 766 767 @GuardedBy("mService") isPendingFinishAttach()768 boolean isPendingFinishAttach() { 769 return mPendingFinishAttach; 770 } 771 772 @GuardedBy("mService") isThreadReady()773 boolean isThreadReady() { 774 return mThread != null && !mPendingFinishAttach; 775 } 776 777 @GuardedBy("mService") getStartSeq()778 long getStartSeq() { 779 return mStartSeq; 780 } 781 782 @GuardedBy("mService") setStartSeq(long startSeq)783 void setStartSeq(long startSeq) { 784 mStartSeq = startSeq; 785 } 786 getHostingRecord()787 HostingRecord getHostingRecord() { 788 return mHostingRecord; 789 } 790 setHostingRecord(HostingRecord hostingRecord)791 void setHostingRecord(HostingRecord hostingRecord) { 792 mHostingRecord = hostingRecord; 793 } 794 getSeInfo()795 String getSeInfo() { 796 return mSeInfo; 797 } 798 setSeInfo(String seInfo)799 void setSeInfo(String seInfo) { 800 mSeInfo = seInfo; 801 } 802 getStartUptime()803 long getStartUptime() { 804 return mStartUptime; 805 } 806 807 /** 808 * Same as {@link #getStartUptime()}. 809 * @deprecated use {@link #getStartUptime()} instead for clarity. 810 */ 811 @Deprecated getStartTime()812 long getStartTime() { 813 return mStartUptime; 814 } 815 getStartElapsedTime()816 long getStartElapsedTime() { 817 return mStartElapsedTime; 818 } 819 getBindApplicationTime()820 long getBindApplicationTime() { 821 return mBindApplicationTime; 822 } 823 setBindApplicationTime(long bindApplicationTime)824 void setBindApplicationTime(long bindApplicationTime) { 825 mBindApplicationTime = bindApplicationTime; 826 } 827 getStartUid()828 int getStartUid() { 829 return mStartUid; 830 } 831 setStartUid(int startUid)832 void setStartUid(int startUid) { 833 mStartUid = startUid; 834 } 835 getMountMode()836 int getMountMode() { 837 return mMountMode; 838 } 839 setMountMode(int mountMode)840 void setMountMode(int mountMode) { 841 mMountMode = mountMode; 842 } 843 isBindMountPending()844 boolean isBindMountPending() { 845 return mBindMountPending; 846 } 847 setBindMountPending(boolean bindMountPending)848 void setBindMountPending(boolean bindMountPending) { 849 mBindMountPending = bindMountPending; 850 } 851 852 @GuardedBy("mProcLock") isUnlocked()853 boolean isUnlocked() { 854 return mUnlocked; 855 } 856 857 @GuardedBy("mProcLock") setUnlocked(boolean unlocked)858 void setUnlocked(boolean unlocked) { 859 mUnlocked = unlocked; 860 } 861 862 @GuardedBy("mProcLock") getRenderThreadTid()863 int getRenderThreadTid() { 864 return mRenderThreadTid; 865 } 866 867 @GuardedBy("mProcLock") setRenderThreadTid(int renderThreadTid)868 void setRenderThreadTid(int renderThreadTid) { 869 mRenderThreadTid = renderThreadTid; 870 } 871 872 @GuardedBy("mService") getCompat()873 CompatibilityInfo getCompat() { 874 return mCompat; 875 } 876 877 @GuardedBy("mService") setCompat(CompatibilityInfo compat)878 void setCompat(CompatibilityInfo compat) { 879 mCompat = compat; 880 } 881 882 @GuardedBy("mService") getDisabledCompatChanges()883 long[] getDisabledCompatChanges() { 884 return mDisabledCompatChanges; 885 } 886 887 @GuardedBy("mService") setDisabledCompatChanges(long[] disabledCompatChanges)888 void setDisabledCompatChanges(long[] disabledCompatChanges) { 889 mDisabledCompatChanges = disabledCompatChanges; 890 } 891 892 @GuardedBy("mService") unlinkDeathRecipient()893 void unlinkDeathRecipient() { 894 if (mDeathRecipient != null && mThread != null) { 895 mThread.asBinder().unlinkToDeath(mDeathRecipient, 0); 896 } 897 mDeathRecipient = null; 898 } 899 900 @GuardedBy("mService") setDeathRecipient(IBinder.DeathRecipient deathRecipient)901 void setDeathRecipient(IBinder.DeathRecipient deathRecipient) { 902 mDeathRecipient = deathRecipient; 903 } 904 905 @GuardedBy("mService") getDeathRecipient()906 IBinder.DeathRecipient getDeathRecipient() { 907 return mDeathRecipient; 908 } 909 910 @GuardedBy({"mService", "mProcLock"}) setActiveInstrumentation(ActiveInstrumentation instr)911 void setActiveInstrumentation(ActiveInstrumentation instr) { 912 mInstr = instr; 913 boolean isInstrumenting = instr != null; 914 mWindowProcessController.setInstrumenting( 915 isInstrumenting, 916 isInstrumenting ? instr.mSourceUid : -1, 917 isInstrumenting && instr.mHasBackgroundActivityStartsPermission); 918 } 919 920 @GuardedBy(anyOf = {"mService", "mProcLock"}) getActiveInstrumentation()921 ActiveInstrumentation getActiveInstrumentation() { 922 return mInstr; 923 } 924 925 @GuardedBy(anyOf = {"mService", "mProcLock"}) isKilledByAm()926 boolean isKilledByAm() { 927 return mKilledByAm; 928 } 929 930 @GuardedBy({"mService", "mProcLock"}) setKilledByAm(boolean killedByAm)931 void setKilledByAm(boolean killedByAm) { 932 mKilledByAm = killedByAm; 933 } 934 935 @GuardedBy(anyOf = {"mService", "mProcLock"}) isKilled()936 boolean isKilled() { 937 return mKilled; 938 } 939 940 @GuardedBy({"mService", "mProcLock"}) setKilled(boolean killed)941 void setKilled(boolean killed) { 942 mKilled = killed; 943 } 944 945 @GuardedBy(anyOf = {"mService", "mProcLock"}) getKillTime()946 long getKillTime() { 947 return mKillTime; 948 } 949 950 @GuardedBy({"mService", "mProcLock"}) setKillTime(long killTime)951 void setKillTime(long killTime) { 952 mKillTime = killTime; 953 } 954 955 @GuardedBy("mService") getWaitingToKill()956 String getWaitingToKill() { 957 return mWaitingToKill; 958 } 959 960 @GuardedBy("mService") setWaitingToKill(String waitingToKill)961 void setWaitingToKill(String waitingToKill) { 962 mWaitingToKill = waitingToKill; 963 } 964 965 @Override isRemoved()966 public boolean isRemoved() { 967 return mRemoved; 968 } 969 setRemoved(boolean removed)970 void setRemoved(boolean removed) { 971 mRemoved = removed; 972 } 973 974 @GuardedBy("mService") isDebugging()975 boolean isDebugging() { 976 return mDebugging; 977 } 978 979 @Nullable getClientInfoForSdkSandbox()980 public ApplicationInfo getClientInfoForSdkSandbox() { 981 if (!isSdkSandbox || sdkSandboxClientAppPackage == null) { 982 throw new IllegalStateException( 983 "getClientInfoForSdkSandbox called for non-sandbox process" 984 ); 985 } 986 PackageManagerInternal pm = mService.getPackageManagerInternal(); 987 return pm.getApplicationInfo( 988 sdkSandboxClientAppPackage, /* flags */0, Process.SYSTEM_UID, userId); 989 } 990 isDebuggable()991 public boolean isDebuggable() { 992 if ((info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 993 return true; 994 } 995 if (isSdkSandbox) { 996 ApplicationInfo clientInfo = getClientInfoForSdkSandbox(); 997 return clientInfo != null && (clientInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 998 } 999 return false; 1000 } 1001 1002 @GuardedBy("mService") setDebugging(boolean debugging)1003 void setDebugging(boolean debugging) { 1004 mDebugging = debugging; 1005 mWindowProcessController.setDebugging(debugging); 1006 } 1007 1008 @GuardedBy("mProcLock") hasWaitedForDebugger()1009 boolean hasWaitedForDebugger() { 1010 return mWaitedForDebugger; 1011 } 1012 1013 @GuardedBy("mProcLock") setWaitedForDebugger(boolean waitedForDebugger)1014 void setWaitedForDebugger(boolean waitedForDebugger) { 1015 mWaitedForDebugger = waitedForDebugger; 1016 } 1017 1018 @GuardedBy(anyOf = {"mService", "mProcLock"}) getLastActivityTime()1019 long getLastActivityTime() { 1020 return mLastActivityTime; 1021 } 1022 1023 @GuardedBy({"mService", "mProcLock"}) setLastActivityTime(long lastActivityTime)1024 void setLastActivityTime(long lastActivityTime) { 1025 mLastActivityTime = lastActivityTime; 1026 } 1027 1028 @GuardedBy("mService") isUsingWrapper()1029 boolean isUsingWrapper() { 1030 return mUsingWrapper; 1031 } 1032 1033 @GuardedBy("mService") setUsingWrapper(boolean usingWrapper)1034 void setUsingWrapper(boolean usingWrapper) { 1035 mUsingWrapper = usingWrapper; 1036 mWindowProcessController.setUsingWrapper(usingWrapper); 1037 } 1038 1039 @GuardedBy("mService") getLruSeq()1040 int getLruSeq() { 1041 return mLruSeq; 1042 } 1043 1044 @GuardedBy("mService") setLruSeq(int lruSeq)1045 void setLruSeq(int lruSeq) { 1046 mLruSeq = lruSeq; 1047 } 1048 1049 @GuardedBy("mService") getIsolatedEntryPoint()1050 String getIsolatedEntryPoint() { 1051 return mIsolatedEntryPoint; 1052 } 1053 1054 @GuardedBy("mService") setIsolatedEntryPoint(String isolatedEntryPoint)1055 void setIsolatedEntryPoint(String isolatedEntryPoint) { 1056 mIsolatedEntryPoint = isolatedEntryPoint; 1057 } 1058 1059 @GuardedBy("mService") getIsolatedEntryPointArgs()1060 String[] getIsolatedEntryPointArgs() { 1061 return mIsolatedEntryPointArgs; 1062 } 1063 1064 @GuardedBy("mService") setIsolatedEntryPointArgs(String[] isolatedEntryPointArgs)1065 void setIsolatedEntryPointArgs(String[] isolatedEntryPointArgs) { 1066 mIsolatedEntryPointArgs = isolatedEntryPointArgs; 1067 } 1068 1069 @GuardedBy("mService") isInFullBackup()1070 boolean isInFullBackup() { 1071 return mInFullBackup; 1072 } 1073 1074 @GuardedBy("mService") setInFullBackup(boolean inFullBackup)1075 void setInFullBackup(boolean inFullBackup) { 1076 mInFullBackup = inFullBackup; 1077 } 1078 1079 @GuardedBy("mService") setCached(boolean cached)1080 public void setCached(boolean cached) { 1081 mState.setCached(cached); 1082 } 1083 1084 @Override 1085 @GuardedBy("mService") isCached()1086 public boolean isCached() { 1087 return mState.isCached(); 1088 } 1089 hasActivities()1090 boolean hasActivities() { 1091 return mWindowProcessController.hasActivities(); 1092 } 1093 hasActivitiesOrRecentTasks()1094 boolean hasActivitiesOrRecentTasks() { 1095 return mWindowProcessController.hasActivitiesOrRecentTasks(); 1096 } 1097 hasRecentTasks()1098 boolean hasRecentTasks() { 1099 return mWindowProcessController.hasRecentTasks(); 1100 } 1101 1102 @GuardedBy("mService") getApplicationInfo()1103 public ApplicationInfo getApplicationInfo() { 1104 return info; 1105 } 1106 1107 @GuardedBy({"mService", "mProcLock"}) onCleanupApplicationRecordLSP(ProcessStatsService processStats, boolean allowRestart, boolean unlinkDeath)1108 boolean onCleanupApplicationRecordLSP(ProcessStatsService processStats, boolean allowRestart, 1109 boolean unlinkDeath) { 1110 mErrorState.onCleanupApplicationRecordLSP(); 1111 1112 resetPackageList(processStats); 1113 if (unlinkDeath) { 1114 unlinkDeathRecipient(); 1115 } 1116 makeInactive(processStats); 1117 setWaitingToKill(null); 1118 1119 mState.onCleanupApplicationRecordLSP(); 1120 mServices.onCleanupApplicationRecordLocked(); 1121 mReceivers.onCleanupApplicationRecordLocked(); 1122 1123 return mProviders.onCleanupApplicationRecordLocked(allowRestart); 1124 } 1125 1126 /** 1127 * This method returns true if any of the activities within the process record are interesting 1128 * to the user. See HistoryRecord.isInterestingToUserLocked() 1129 */ isInterestingToUserLocked()1130 public boolean isInterestingToUserLocked() { 1131 if (mWindowProcessController.isInterestingToUser()) { 1132 return true; 1133 } 1134 1135 return mServices.hasForegroundServices(); 1136 } 1137 1138 /** 1139 * Let an app process throw an exception on a binder thread, which typically crashes the 1140 * process, unless it has an unhandled exception handler. 1141 * 1142 * See {@link ActivityThread#throwRemoteServiceException}. 1143 * 1144 * @param message exception message 1145 * @param exceptionTypeId ID defined in {@link android.app.RemoteServiceException} or one 1146 * of its subclasses. 1147 */ 1148 @GuardedBy("mService") scheduleCrashLocked(String message, int exceptionTypeId, @Nullable Bundle extras)1149 void scheduleCrashLocked(String message, int exceptionTypeId, @Nullable Bundle extras) { 1150 // Checking killedbyAm should keep it from showing the crash dialog if the process 1151 // was already dead for a good / normal reason. 1152 if (!mKilledByAm) { 1153 if (mThread != null) { 1154 if (mPid == Process.myPid()) { 1155 Slog.w(TAG, "scheduleCrash: trying to crash system process!"); 1156 return; 1157 } 1158 final long ident = Binder.clearCallingIdentity(); 1159 try { 1160 mThread.scheduleCrash(message, exceptionTypeId, extras); 1161 } catch (RemoteException e) { 1162 // If it's already dead our work is done. If it's wedged just kill it. 1163 // We won't get the crash dialog or the error reporting. 1164 killLocked("scheduleCrash for '" + message + "' failed", 1165 ApplicationExitInfo.REASON_CRASH, true); 1166 } finally { 1167 Binder.restoreCallingIdentity(ident); 1168 } 1169 } 1170 } 1171 } 1172 1173 @GuardedBy("mService") killLocked(String reason, @Reason int reasonCode, boolean noisy)1174 void killLocked(String reason, @Reason int reasonCode, boolean noisy) { 1175 killLocked(reason, reasonCode, ApplicationExitInfo.SUBREASON_UNKNOWN, noisy, true); 1176 } 1177 1178 @GuardedBy("mService") killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, boolean noisy)1179 void killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, 1180 boolean noisy) { 1181 killLocked(reason, reason, reasonCode, subReason, noisy, true); 1182 } 1183 1184 @GuardedBy("mService") killLocked(String reason, String description, @Reason int reasonCode, @SubReason int subReason, boolean noisy)1185 void killLocked(String reason, String description, @Reason int reasonCode, 1186 @SubReason int subReason, boolean noisy) { 1187 killLocked(reason, description, reasonCode, subReason, noisy, true); 1188 } 1189 1190 @GuardedBy("mService") killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, boolean noisy, boolean asyncKPG)1191 void killLocked(String reason, @Reason int reasonCode, @SubReason int subReason, 1192 boolean noisy, boolean asyncKPG) { 1193 killLocked(reason, reason, reasonCode, subReason, noisy, asyncKPG); 1194 } 1195 1196 @GuardedBy("mService") killLocked(String reason, String description, @Reason int reasonCode, @SubReason int subReason, boolean noisy, boolean asyncKPG)1197 void killLocked(String reason, String description, @Reason int reasonCode, 1198 @SubReason int subReason, boolean noisy, boolean asyncKPG) { 1199 if (!mKilledByAm) { 1200 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill"); 1201 if (reasonCode == ApplicationExitInfo.REASON_ANR 1202 && mErrorState.getAnrAnnotation() != null) { 1203 description = description + ": " + mErrorState.getAnrAnnotation(); 1204 } 1205 if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) { 1206 mService.reportUidInfoMessageLocked(TAG, 1207 "Killing " + toShortString() + " (adj " + mState.getSetAdj() 1208 + "): " + reason, info.uid); 1209 } 1210 // Since the process is getting killed, reset the freezable related state. 1211 mOptRecord.setPendingFreeze(false); 1212 mOptRecord.setFrozen(false); 1213 if (mPid > 0) { 1214 mService.mProcessList.noteAppKill(this, reasonCode, subReason, description); 1215 EventLog.writeEvent(EventLogTags.AM_KILL, 1216 userId, mPid, processName, mState.getSetAdj(), reason); 1217 Process.killProcessQuiet(mPid); 1218 killProcessGroupIfNecessaryLocked(asyncKPG); 1219 } else { 1220 mPendingStart = false; 1221 } 1222 if (!mPersistent) { 1223 synchronized (mProcLock) { 1224 mKilled = true; 1225 mKilledByAm = true; 1226 mKillTime = SystemClock.uptimeMillis(); 1227 } 1228 } 1229 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 1230 } 1231 } 1232 1233 @GuardedBy("mService") killProcessGroupIfNecessaryLocked(boolean async)1234 void killProcessGroupIfNecessaryLocked(boolean async) { 1235 final boolean killProcessGroup; 1236 if (mHostingRecord != null 1237 && (mHostingRecord.usesWebviewZygote() || mHostingRecord.usesAppZygote())) { 1238 synchronized (ProcessRecord.this) { 1239 killProcessGroup = mProcessGroupCreated; 1240 if (!killProcessGroup) { 1241 // The process group hasn't been created, request to skip it. 1242 mSkipProcessGroupCreation = true; 1243 } 1244 } 1245 } else { 1246 killProcessGroup = true; 1247 } 1248 if (killProcessGroup) { 1249 if (async) { 1250 ProcessList.killProcessGroup(uid, mPid); 1251 } else { 1252 Process.sendSignalToProcessGroup(uid, mPid, OsConstants.SIGKILL); 1253 } 1254 } 1255 } 1256 1257 @Override dumpDebug(ProtoOutputStream proto, long fieldId)1258 public void dumpDebug(ProtoOutputStream proto, long fieldId) { 1259 dumpDebug(proto, fieldId, -1); 1260 } 1261 dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex)1262 public void dumpDebug(ProtoOutputStream proto, long fieldId, int lruIndex) { 1263 long token = proto.start(fieldId); 1264 proto.write(ProcessRecordProto.PID, mPid); 1265 proto.write(ProcessRecordProto.PROCESS_NAME, processName); 1266 proto.write(ProcessRecordProto.UID, info.uid); 1267 if (UserHandle.getAppId(info.uid) >= Process.FIRST_APPLICATION_UID) { 1268 proto.write(ProcessRecordProto.USER_ID, userId); 1269 proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid)); 1270 } 1271 if (uid != info.uid) { 1272 proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid)); 1273 } 1274 proto.write(ProcessRecordProto.PERSISTENT, mPersistent); 1275 if (lruIndex >= 0) { 1276 proto.write(ProcessRecordProto.LRU_INDEX, lruIndex); 1277 } 1278 proto.end(token); 1279 } 1280 toShortString()1281 public String toShortString() { 1282 final String shortStringName = mShortStringName; 1283 if (shortStringName != null) { 1284 return shortStringName; 1285 } 1286 StringBuilder sb = new StringBuilder(128); 1287 toShortString(sb); 1288 return mShortStringName = sb.toString(); 1289 } 1290 toShortString(StringBuilder sb)1291 void toShortString(StringBuilder sb) { 1292 sb.append(mPid); 1293 sb.append(':'); 1294 sb.append(processName); 1295 sb.append('/'); 1296 if (info.uid < Process.FIRST_APPLICATION_UID) { 1297 sb.append(uid); 1298 } else { 1299 sb.append('u'); 1300 sb.append(userId); 1301 int appId = UserHandle.getAppId(info.uid); 1302 if (appId >= Process.FIRST_APPLICATION_UID) { 1303 sb.append('a'); 1304 sb.append(appId - Process.FIRST_APPLICATION_UID); 1305 } else { 1306 sb.append('s'); 1307 sb.append(appId); 1308 } 1309 if (uid != info.uid) { 1310 sb.append('i'); 1311 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID); 1312 } 1313 } 1314 } 1315 toString()1316 public String toString() { 1317 final String stringName = mStringName; 1318 if (stringName != null) { 1319 return stringName; 1320 } 1321 StringBuilder sb = new StringBuilder(128); 1322 sb.append("ProcessRecord{"); 1323 sb.append(Integer.toHexString(System.identityHashCode(this))); 1324 sb.append(' '); 1325 toShortString(sb); 1326 sb.append('}'); 1327 return mStringName = sb.toString(); 1328 } 1329 1330 /* 1331 * Return true if package has been added false if not 1332 */ addPackage(String pkg, long versionCode, ProcessStatsService tracker)1333 public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) { 1334 synchronized (tracker.mLock) { 1335 synchronized (mPkgList) { 1336 if (!mPkgList.containsKey(pkg)) { 1337 ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder( 1338 versionCode); 1339 final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker(); 1340 if (baseProcessTracker != null) { 1341 tracker.updateProcessStateHolderLocked(holder, pkg, info.uid, versionCode, 1342 processName); 1343 mPkgList.put(pkg, holder); 1344 if (holder.state != baseProcessTracker) { 1345 holder.state.makeActive(); 1346 } 1347 } else { 1348 mPkgList.put(pkg, holder); 1349 } 1350 return true; 1351 } 1352 } 1353 } 1354 return false; 1355 } 1356 onProcessFrozen()1357 void onProcessFrozen() { 1358 mProfile.onProcessFrozen(); 1359 } 1360 onProcessUnfrozen()1361 void onProcessUnfrozen() { 1362 mProfile.onProcessUnfrozen(); 1363 } 1364 1365 1366 /* 1367 * Delete all packages from list except the package indicated in info 1368 */ resetPackageList(ProcessStatsService tracker)1369 public void resetPackageList(ProcessStatsService tracker) { 1370 synchronized (tracker.mLock) { 1371 final ProcessState baseProcessTracker = mProfile.getBaseProcessTracker(); 1372 synchronized (mPkgList) { 1373 final int numOfPkgs = mPkgList.size(); 1374 if (baseProcessTracker != null) { 1375 long now = SystemClock.uptimeMillis(); 1376 baseProcessTracker.setState(ProcessStats.STATE_NOTHING, 1377 tracker.getMemFactorLocked(), now, mPkgList.getPackageListLocked()); 1378 if (numOfPkgs != 1) { 1379 mPkgList.forEachPackageProcessStats(holder -> { 1380 if (holder.state != null && holder.state != baseProcessTracker) { 1381 holder.state.makeInactive(); 1382 } 1383 }); 1384 mPkgList.clear(); 1385 ProcessStats.ProcessStateHolder holder = 1386 new ProcessStats.ProcessStateHolder(info.longVersionCode); 1387 tracker.updateProcessStateHolderLocked(holder, info.packageName, info.uid, 1388 info.longVersionCode, processName); 1389 mPkgList.put(info.packageName, holder); 1390 if (holder.state != baseProcessTracker) { 1391 holder.state.makeActive(); 1392 } 1393 } 1394 } else if (numOfPkgs != 1) { 1395 mPkgList.clear(); 1396 mPkgList.put(info.packageName, 1397 new ProcessStats.ProcessStateHolder(info.longVersionCode)); 1398 } 1399 } 1400 } 1401 } 1402 getPackageList()1403 String[] getPackageList() { 1404 return mPkgList.getPackageList(); 1405 } 1406 getPackageListWithVersionCode()1407 List<VersionedPackage> getPackageListWithVersionCode() { 1408 return mPkgList.getPackageListWithVersionCode(); 1409 } 1410 getWindowProcessController()1411 WindowProcessController getWindowProcessController() { 1412 return mWindowProcessController; 1413 } 1414 1415 /** 1416 * Allows background activity starts using token {@param entity}. Optionally, you can provide 1417 * {@param originatingToken} if you have one such originating token, this is useful for tracing 1418 * back the grant in the case of the notification token. 1419 */ addOrUpdateBackgroundStartPrivileges(@onNull Binder entity, @NonNull BackgroundStartPrivileges backgroundStartPrivileges)1420 void addOrUpdateBackgroundStartPrivileges(@NonNull Binder entity, 1421 @NonNull BackgroundStartPrivileges backgroundStartPrivileges) { 1422 requireNonNull(entity, "entity"); 1423 requireNonNull(backgroundStartPrivileges, "backgroundStartPrivileges"); 1424 checkArgument(backgroundStartPrivileges.allowsAny(), 1425 "backgroundStartPrivileges does not allow anything"); 1426 mWindowProcessController.addOrUpdateBackgroundStartPrivileges(entity, 1427 backgroundStartPrivileges); 1428 setBackgroundStartPrivileges(entity, backgroundStartPrivileges); 1429 } 1430 removeBackgroundStartPrivileges(@onNull Binder entity)1431 void removeBackgroundStartPrivileges(@NonNull Binder entity) { 1432 requireNonNull(entity, "entity"); 1433 mWindowProcessController.removeBackgroundStartPrivileges(entity); 1434 setBackgroundStartPrivileges(entity, null); 1435 } 1436 1437 @NonNull getBackgroundStartPrivileges()1438 BackgroundStartPrivileges getBackgroundStartPrivileges() { 1439 synchronized (mBackgroundStartPrivileges) { 1440 if (mBackgroundStartPrivilegesMerged == null) { 1441 // Lazily generate the merged version when it's actually needed. 1442 mBackgroundStartPrivilegesMerged = BackgroundStartPrivileges.NONE; 1443 for (int i = mBackgroundStartPrivileges.size() - 1; i >= 0; --i) { 1444 mBackgroundStartPrivilegesMerged = 1445 mBackgroundStartPrivilegesMerged.merge( 1446 mBackgroundStartPrivileges.valueAt(i)); 1447 } 1448 } 1449 return mBackgroundStartPrivilegesMerged; 1450 } 1451 } 1452 setBackgroundStartPrivileges(@onNull Binder entity, @Nullable BackgroundStartPrivileges backgroundStartPrivileges)1453 private void setBackgroundStartPrivileges(@NonNull Binder entity, 1454 @Nullable BackgroundStartPrivileges backgroundStartPrivileges) { 1455 synchronized (mBackgroundStartPrivileges) { 1456 final boolean changed; 1457 if (backgroundStartPrivileges == null) { 1458 changed = mBackgroundStartPrivileges.remove(entity) != null; 1459 } else { 1460 final BackgroundStartPrivileges oldBsp = 1461 mBackgroundStartPrivileges.put(entity, backgroundStartPrivileges); 1462 // BackgroundStartPrivileges tries to reuse the same object and avoid creating 1463 // additional objects. For now, we just compare the reference to see if something 1464 // has changed. 1465 // TODO: actually compare the individual values to see if there's a change 1466 changed = backgroundStartPrivileges != oldBsp; 1467 } 1468 if (changed) { 1469 mBackgroundStartPrivilegesMerged = null; 1470 } 1471 } 1472 } 1473 1474 @Override clearProfilerIfNeeded()1475 public void clearProfilerIfNeeded() { 1476 synchronized (mService.mAppProfiler.mProfilerLock) { 1477 mService.mAppProfiler.clearProfilerLPf(); 1478 } 1479 } 1480 1481 @Override updateServiceConnectionActivities()1482 public void updateServiceConnectionActivities() { 1483 synchronized (mService) { 1484 mService.mServices.updateServiceConnectionActivitiesLocked(mServices); 1485 } 1486 } 1487 1488 @Override setPendingUiClean(boolean pendingUiClean)1489 public void setPendingUiClean(boolean pendingUiClean) { 1490 synchronized (mProcLock) { 1491 mProfile.setPendingUiClean(pendingUiClean); 1492 } 1493 } 1494 1495 @Override setPendingUiCleanAndForceProcessStateUpTo(int newState)1496 public void setPendingUiCleanAndForceProcessStateUpTo(int newState) { 1497 synchronized (mService) { 1498 setPendingUiClean(true); 1499 mState.forceProcessStateUpTo(newState); 1500 } 1501 } 1502 1503 @Override updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, boolean updateOomAdj)1504 public void updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, 1505 boolean updateOomAdj) { 1506 synchronized (mService) { 1507 if (updateServiceConnectionActivities) { 1508 mService.mServices.updateServiceConnectionActivitiesLocked(mServices); 1509 } 1510 if (mThread == null) { 1511 // Only update lru and oom-adj if the process is alive. Because it may be called 1512 // when cleaning up the last activity from handling process died, the dead process 1513 // should not be added to lru list again. 1514 return; 1515 } 1516 mService.updateLruProcessLocked(this, activityChange, null /* client */); 1517 if (updateOomAdj) { 1518 mService.updateOomAdjLocked(this, OOM_ADJ_REASON_ACTIVITY); 1519 } 1520 } 1521 } 1522 1523 /** 1524 * Returns the total time (in milliseconds) spent executing in both user and system code. 1525 * Safe to call without lock held. 1526 */ 1527 @Override getCpuTime()1528 public long getCpuTime() { 1529 return mService.mAppProfiler.getCpuTimeForPid(mPid); 1530 } 1531 getCpuDelayTime()1532 public long getCpuDelayTime() { 1533 return mService.mAppProfiler.getCpuDelayTimeForPid(mPid); 1534 } 1535 1536 @Override onStartActivity(int topProcessState, boolean setProfileProc, String packageName, long versionCode)1537 public void onStartActivity(int topProcessState, boolean setProfileProc, String packageName, 1538 long versionCode) { 1539 synchronized (mService) { 1540 mWaitingToKill = null; 1541 if (setProfileProc) { 1542 synchronized (mService.mAppProfiler.mProfilerLock) { 1543 mService.mAppProfiler.setProfileProcLPf(this); 1544 } 1545 } 1546 if (packageName != null) { 1547 addPackage(packageName, versionCode, mService.mProcessStats); 1548 } 1549 1550 // Update oom adj first, we don't want the additional states are involved in this round. 1551 updateProcessInfo(false /* updateServiceConnectionActivities */, 1552 true /* activityChange */, true /* updateOomAdj */); 1553 setPendingUiClean(true); 1554 mState.setHasShownUi(true); 1555 mState.forceProcessStateUpTo(topProcessState); 1556 } 1557 } 1558 1559 @Override appDied(String reason)1560 public void appDied(String reason) { 1561 synchronized (mService) { 1562 mService.appDiedLocked(this, reason); 1563 } 1564 } 1565 1566 @Override setRunningRemoteAnimation(boolean runningRemoteAnimation)1567 public void setRunningRemoteAnimation(boolean runningRemoteAnimation) { 1568 if (mPid == Process.myPid()) { 1569 Slog.wtf(TAG, "system can't run remote animation"); 1570 return; 1571 } 1572 synchronized (mService) { 1573 mState.setRunningRemoteAnimation(runningRemoteAnimation); 1574 } 1575 } 1576 getInputDispatchingTimeoutMillis()1577 public long getInputDispatchingTimeoutMillis() { 1578 return mWindowProcessController.getInputDispatchingTimeoutMillis(); 1579 } 1580 getProcessClassEnum()1581 public int getProcessClassEnum() { 1582 if (mPid == MY_PID) { 1583 return ServerProtoEnums.SYSTEM_SERVER; 1584 } 1585 if (info == null) { 1586 return ServerProtoEnums.ERROR_SOURCE_UNKNOWN; 1587 } 1588 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? ServerProtoEnums.SYSTEM_APP : 1589 ServerProtoEnums.DATA_APP; 1590 } 1591 1592 /** Non-private access is for tests only. */ 1593 @VisibleForTesting getLruProcessList()1594 List<ProcessRecord> getLruProcessList() { 1595 return mService.mProcessList.getLruProcessesLOSP(); 1596 } 1597 } 1598