1 /* 2 * Copyright (C) 2011 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.ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 20 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 21 import static android.app.ActivityThread.PROC_START_SEQ_IDENT; 22 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AUTO; 23 import static android.os.MessageQueue.OnFileDescriptorEventListener.EVENT_INPUT; 24 import static android.os.Process.SYSTEM_UID; 25 import static android.os.Process.THREAD_PRIORITY_BACKGROUND; 26 import static android.os.Process.ZYGOTE_POLICY_FLAG_EMPTY; 27 import static android.os.Process.getFreeMemory; 28 import static android.os.Process.getTotalMemory; 29 import static android.os.Process.killProcessQuiet; 30 import static android.os.Process.startWebView; 31 32 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_LRU; 33 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PROCESSES; 34 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_PSS; 35 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_UID_OBSERVERS; 36 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 37 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 38 import static com.android.server.am.ActivityManagerService.KILL_APP_ZYGOTE_DELAY_MS; 39 import static com.android.server.am.ActivityManagerService.KILL_APP_ZYGOTE_MSG; 40 import static com.android.server.am.ActivityManagerService.PERSISTENT_MASK; 41 import static com.android.server.am.ActivityManagerService.PROC_START_TIMEOUT; 42 import static com.android.server.am.ActivityManagerService.PROC_START_TIMEOUT_MSG; 43 import static com.android.server.am.ActivityManagerService.PROC_START_TIMEOUT_WITH_WRAPPER; 44 import static com.android.server.am.ActivityManagerService.STOCK_PM_FLAGS; 45 import static com.android.server.am.ActivityManagerService.TAG_LRU; 46 import static com.android.server.am.ActivityManagerService.TAG_PROCESSES; 47 import static com.android.server.am.ActivityManagerService.TAG_PSS; 48 import static com.android.server.am.ActivityManagerService.TAG_UID_OBSERVERS; 49 50 import android.app.ActivityManager; 51 import android.app.ActivityThread; 52 import android.app.AppGlobals; 53 import android.app.AppProtoEnums; 54 import android.app.IApplicationThread; 55 import android.compat.annotation.ChangeId; 56 import android.compat.annotation.Disabled; 57 import android.compat.annotation.EnabledAfter; 58 import android.content.ComponentName; 59 import android.content.Context; 60 import android.content.Intent; 61 import android.content.pm.ApplicationInfo; 62 import android.content.pm.IPackageManager; 63 import android.content.res.Resources; 64 import android.graphics.Point; 65 import android.net.LocalSocket; 66 import android.net.LocalSocketAddress; 67 import android.os.AppZygote; 68 import android.os.Binder; 69 import android.os.Build; 70 import android.os.Bundle; 71 import android.os.Handler; 72 import android.os.IBinder; 73 import android.os.Looper; 74 import android.os.Message; 75 import android.os.Process; 76 import android.os.RemoteException; 77 import android.os.StrictMode; 78 import android.os.SystemClock; 79 import android.os.SystemProperties; 80 import android.os.Trace; 81 import android.os.UserHandle; 82 import android.os.storage.StorageManager; 83 import android.os.storage.StorageManagerInternal; 84 import android.system.Os; 85 import android.text.TextUtils; 86 import android.util.ArrayMap; 87 import android.util.EventLog; 88 import android.util.LongSparseArray; 89 import android.util.Slog; 90 import android.util.SparseArray; 91 import android.util.SparseBooleanArray; 92 import android.util.StatsLog; 93 import android.view.Display; 94 95 import com.android.internal.annotations.GuardedBy; 96 import com.android.internal.annotations.VisibleForTesting; 97 import com.android.internal.app.ProcessMap; 98 import com.android.internal.app.procstats.ProcessStats; 99 import com.android.internal.os.RuntimeInit; 100 import com.android.internal.os.Zygote; 101 import com.android.internal.util.ArrayUtils; 102 import com.android.internal.util.MemInfoReader; 103 import com.android.server.LocalServices; 104 import com.android.server.ServiceThread; 105 import com.android.server.Watchdog; 106 import com.android.server.compat.PlatformCompat; 107 import com.android.server.pm.dex.DexManager; 108 import com.android.server.wm.ActivityServiceConnectionsHolder; 109 import com.android.server.wm.WindowManagerService; 110 111 import dalvik.system.VMRuntime; 112 113 import java.io.File; 114 import java.io.FileDescriptor; 115 import java.io.IOException; 116 import java.io.OutputStream; 117 import java.io.PrintWriter; 118 import java.nio.ByteBuffer; 119 import java.util.ArrayList; 120 import java.util.Arrays; 121 import java.util.BitSet; 122 import java.util.List; 123 124 /** 125 * Activity manager code dealing with processes. 126 */ 127 public final class ProcessList { 128 static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessList" : TAG_AM; 129 130 // The minimum time we allow between crashes, for us to consider this 131 // application to be bad and stop and its services and reject broadcasts. 132 static final int MIN_CRASH_INTERVAL = 60 * 1000; 133 134 // OOM adjustments for processes in various states: 135 136 // Uninitialized value for any major or minor adj fields 137 static final int INVALID_ADJ = -10000; 138 139 // Adjustment used in certain places where we don't know it yet. 140 // (Generally this is something that is going to be cached, but we 141 // don't know the exact value in the cached range to assign yet.) 142 static final int UNKNOWN_ADJ = 1001; 143 144 // This is a process only hosting activities that are not visible, 145 // so it can be killed without any disruption. 146 static final int CACHED_APP_MAX_ADJ = 999; 147 static final int CACHED_APP_MIN_ADJ = 900; 148 149 // This is the oom_adj level that we allow to die first. This cannot be equal to 150 // CACHED_APP_MAX_ADJ unless processes are actively being assigned an oom_score_adj of 151 // CACHED_APP_MAX_ADJ. 152 static final int CACHED_APP_LMK_FIRST_ADJ = 950; 153 154 // Number of levels we have available for different service connection group importance 155 // levels. 156 static final int CACHED_APP_IMPORTANCE_LEVELS = 5; 157 158 // The B list of SERVICE_ADJ -- these are the old and decrepit 159 // services that aren't as shiny and interesting as the ones in the A list. 160 static final int SERVICE_B_ADJ = 800; 161 162 // This is the process of the previous application that the user was in. 163 // This process is kept above other things, because it is very common to 164 // switch back to the previous app. This is important both for recent 165 // task switch (toggling between the two top recent apps) as well as normal 166 // UI flow such as clicking on a URI in the e-mail app to view in the browser, 167 // and then pressing back to return to e-mail. 168 static final int PREVIOUS_APP_ADJ = 700; 169 170 // This is a process holding the home application -- we want to try 171 // avoiding killing it, even if it would normally be in the background, 172 // because the user interacts with it so much. 173 static final int HOME_APP_ADJ = 600; 174 175 // This is a process holding an application service -- killing it will not 176 // have much of an impact as far as the user is concerned. 177 static final int SERVICE_ADJ = 500; 178 179 // This is a process with a heavy-weight application. It is in the 180 // background, but we want to try to avoid killing it. Value set in 181 // system/rootdir/init.rc on startup. 182 static final int HEAVY_WEIGHT_APP_ADJ = 400; 183 184 // This is a process currently hosting a backup operation. Killing it 185 // is not entirely fatal but is generally a bad idea. 186 static final int BACKUP_APP_ADJ = 300; 187 188 // This is a process bound by the system (or other app) that's more important than services but 189 // not so perceptible that it affects the user immediately if killed. 190 static final int PERCEPTIBLE_LOW_APP_ADJ = 250; 191 192 // This is a process only hosting components that are perceptible to the 193 // user, and we really want to avoid killing them, but they are not 194 // immediately visible. An example is background music playback. 195 static final int PERCEPTIBLE_APP_ADJ = 200; 196 197 // This is a process only hosting activities that are visible to the 198 // user, so we'd prefer they don't disappear. 199 static final int VISIBLE_APP_ADJ = 100; 200 static final int VISIBLE_APP_LAYER_MAX = PERCEPTIBLE_APP_ADJ - VISIBLE_APP_ADJ - 1; 201 202 // This is a process that was recently TOP and moved to FGS. Continue to treat it almost 203 // like a foreground app for a while. 204 // @see TOP_TO_FGS_GRACE_PERIOD 205 static final int PERCEPTIBLE_RECENT_FOREGROUND_APP_ADJ = 50; 206 207 // This is the process running the current foreground app. We'd really 208 // rather not kill it! 209 static final int FOREGROUND_APP_ADJ = 0; 210 211 // This is a process that the system or a persistent process has bound to, 212 // and indicated it is important. 213 static final int PERSISTENT_SERVICE_ADJ = -700; 214 215 // This is a system persistent process, such as telephony. Definitely 216 // don't want to kill it, but doing so is not completely fatal. 217 static final int PERSISTENT_PROC_ADJ = -800; 218 219 // The system process runs at the default adjustment. 220 static final int SYSTEM_ADJ = -900; 221 222 // Special code for native processes that are not being managed by the system (so 223 // don't have an oom adj assigned by the system). 224 static final int NATIVE_ADJ = -1000; 225 226 // Memory pages are 4K. 227 static final int PAGE_SIZE = 4 * 1024; 228 229 // Activity manager's version of Process.THREAD_GROUP_BG_NONINTERACTIVE 230 static final int SCHED_GROUP_BACKGROUND = 0; 231 // Activity manager's version of Process.THREAD_GROUP_RESTRICTED 232 static final int SCHED_GROUP_RESTRICTED = 1; 233 // Activity manager's version of Process.THREAD_GROUP_DEFAULT 234 static final int SCHED_GROUP_DEFAULT = 2; 235 // Activity manager's version of Process.THREAD_GROUP_TOP_APP 236 public static final int SCHED_GROUP_TOP_APP = 3; 237 // Activity manager's version of Process.THREAD_GROUP_TOP_APP 238 // Disambiguate between actual top app and processes bound to the top app 239 static final int SCHED_GROUP_TOP_APP_BOUND = 4; 240 241 // The minimum number of cached apps we want to be able to keep around, 242 // without empty apps being able to push them out of memory. 243 static final int MIN_CACHED_APPS = 2; 244 245 // We allow empty processes to stick around for at most 30 minutes. 246 static final long MAX_EMPTY_TIME = 30 * 60 * 1000; 247 248 // Threshold of number of cached+empty where we consider memory critical. 249 static final int TRIM_CRITICAL_THRESHOLD = 3; 250 251 // Threshold of number of cached+empty where we consider memory critical. 252 static final int TRIM_LOW_THRESHOLD = 5; 253 254 // If true, then we pass the flag to ART to load the app image startup cache. 255 private static final String PROPERTY_USE_APP_IMAGE_STARTUP_CACHE = 256 "persist.device_config.runtime_native.use_app_image_startup_cache"; 257 258 // The socket path for zygote to send unsolicited msg. 259 // Must keep sync with com_android_internal_os_Zygote.cpp. 260 private static final String UNSOL_ZYGOTE_MSG_SOCKET_PATH = "/data/system/unsolzygotesocket"; 261 262 // Low Memory Killer Daemon command codes. 263 // These must be kept in sync with lmk_cmd definitions in lmkd.h 264 // 265 // LMK_TARGET <minfree> <minkillprio> ... (up to 6 pairs) 266 // LMK_PROCPRIO <pid> <uid> <prio> 267 // LMK_PROCREMOVE <pid> 268 // LMK_PROCPURGE 269 // LMK_GETKILLCNT 270 // LMK_SUBSCRIBE 271 // LMK_PROCKILL 272 static final byte LMK_TARGET = 0; 273 static final byte LMK_PROCPRIO = 1; 274 static final byte LMK_PROCREMOVE = 2; 275 static final byte LMK_PROCPURGE = 3; 276 static final byte LMK_GETKILLCNT = 4; 277 static final byte LMK_SUBSCRIBE = 5; 278 static final byte LMK_PROCKILL = 6; // Note: this is an unsolicated command 279 280 // Low Memory Killer Daemon command codes. 281 // These must be kept in sync with async_event_type definitions in lmkd.h 282 // 283 static final int LMK_ASYNC_EVENT_KILL = 0; 284 285 // lmkd reconnect delay in msecs 286 private static final long LMKD_RECONNECT_DELAY_MS = 1000; 287 288 /** 289 * Native heap allocations will now have a non-zero tag in the most significant byte. 290 * @see <a href="https://source.android.com/devices/tech/debug/tagged-pointers">Tagged 291 * Pointers</a> 292 */ 293 @ChangeId 294 @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q) 295 private static final long NATIVE_HEAP_POINTER_TAGGING = 135754954; // This is a bug id. 296 297 /** 298 * Enable memory tag checks in non-system apps. This flag will only have an effect on 299 * hardware supporting the ARM Memory Tagging Extension (MTE). 300 */ 301 @ChangeId 302 @Disabled 303 private static final long NATIVE_MEMORY_TAGGING = 135772972; // This is a bug id. 304 305 ActivityManagerService mService = null; 306 307 // To kill process groups asynchronously 308 static KillHandler sKillHandler = null; 309 static ServiceThread sKillThread = null; 310 311 // These are the various interesting memory levels that we will give to 312 // the OOM killer. Note that the OOM killer only supports 6 slots, so we 313 // can't give it a different value for every possible kind of process. 314 private final int[] mOomAdj = new int[] { 315 FOREGROUND_APP_ADJ, VISIBLE_APP_ADJ, PERCEPTIBLE_APP_ADJ, 316 PERCEPTIBLE_LOW_APP_ADJ, CACHED_APP_MIN_ADJ, CACHED_APP_LMK_FIRST_ADJ 317 }; 318 // These are the low-end OOM level limits. This is appropriate for an 319 // HVGA or smaller phone with less than 512MB. Values are in KB. 320 private final int[] mOomMinFreeLow = new int[] { 321 12288, 18432, 24576, 322 36864, 43008, 49152 323 }; 324 // These are the high-end OOM level limits. This is appropriate for a 325 // 1280x800 or larger screen with around 1GB RAM. Values are in KB. 326 private final int[] mOomMinFreeHigh = new int[] { 327 73728, 92160, 110592, 328 129024, 147456, 184320 329 }; 330 // The actual OOM killer memory levels we are using. 331 private final int[] mOomMinFree = new int[mOomAdj.length]; 332 333 private final long mTotalMemMb; 334 335 private long mCachedRestoreLevel; 336 337 private boolean mHaveDisplaySize; 338 339 private static LmkdConnection sLmkdConnection = null; 340 341 private boolean mOomLevelsSet = false; 342 343 /** 344 * Temporary to avoid allocations. Protected by main lock. 345 */ 346 @GuardedBy("mService") 347 final StringBuilder mStringBuilder = new StringBuilder(256); 348 349 /** 350 * A global counter for generating sequence numbers. 351 * This value will be used when incrementing sequence numbers in individual uidRecords. 352 * 353 * Having a global counter ensures that seq numbers are monotonically increasing for a 354 * particular uid even when the uidRecord is re-created. 355 */ 356 @GuardedBy("mService") 357 @VisibleForTesting 358 long mProcStateSeqCounter = 0; 359 360 /** 361 * A global counter for generating sequence numbers to uniquely identify pending process starts. 362 */ 363 @GuardedBy("mService") 364 private long mProcStartSeqCounter = 0; 365 366 /** 367 * Contains {@link ProcessRecord} objects for pending process starts. 368 * 369 * Mapping: {@link #mProcStartSeqCounter} -> {@link ProcessRecord} 370 */ 371 @GuardedBy("mService") 372 final LongSparseArray<ProcessRecord> mPendingStarts = new LongSparseArray<>(); 373 374 /** 375 * List of running applications, sorted by recent usage. 376 * The first entry in the list is the least recently used. 377 */ 378 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>(); 379 380 /** 381 * Where in mLruProcesses that the processes hosting activities start. 382 */ 383 int mLruProcessActivityStart = 0; 384 385 /** 386 * Where in mLruProcesses that the processes hosting services start. 387 * This is after (lower index) than mLruProcessesActivityStart. 388 */ 389 int mLruProcessServiceStart = 0; 390 391 /** 392 * Current sequence id for process LRU updating. 393 */ 394 int mLruSeq = 0; 395 396 ActiveUids mActiveUids; 397 398 /** 399 * The listener who is intereted with the lmkd kills. 400 */ 401 @GuardedBy("mService") 402 private LmkdKillListener mLmkdKillListener = null; 403 404 /** 405 * The currently running isolated processes. 406 */ 407 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<>(); 408 409 /** 410 * The currently running application zygotes. 411 */ 412 final ProcessMap<AppZygote> mAppZygotes = new ProcessMap<AppZygote>(); 413 414 /** 415 * The processes that are forked off an application zygote. 416 */ 417 final ArrayMap<AppZygote, ArrayList<ProcessRecord>> mAppZygoteProcesses = 418 new ArrayMap<AppZygote, ArrayList<ProcessRecord>>(); 419 420 private PlatformCompat mPlatformCompat = null; 421 422 /** 423 * The server socket in system_server, zygote will connect to it 424 * in order to send unsolicited messages to system_server. 425 */ 426 private LocalSocket mSystemServerSocketForZygote; 427 428 /** 429 * Maximum number of bytes that an incoming unsolicited zygote message could be. 430 * To be updated if new message type needs to be supported. 431 */ 432 private static final int MAX_ZYGOTE_UNSOLICITED_MESSAGE_SIZE = 16; 433 434 /** 435 * The buffer to be used to receive the incoming unsolicited zygote message. 436 */ 437 private final byte[] mZygoteUnsolicitedMessage = new byte[MAX_ZYGOTE_UNSOLICITED_MESSAGE_SIZE]; 438 439 /** 440 * The buffer to be used to receive the SIGCHLD data, it includes pid/uid/status. 441 */ 442 private final int[] mZygoteSigChldMessage = new int[3]; 443 444 interface LmkdKillListener { 445 /** 446 * Called when there is a process kill by lmkd. 447 */ onLmkdKillOccurred(int pid, int uid)448 void onLmkdKillOccurred(int pid, int uid); 449 } 450 451 final class IsolatedUidRange { 452 @VisibleForTesting 453 public final int mFirstUid; 454 @VisibleForTesting 455 public final int mLastUid; 456 457 @GuardedBy("ProcessList.this.mService") 458 private final SparseBooleanArray mUidUsed = new SparseBooleanArray(); 459 460 @GuardedBy("ProcessList.this.mService") 461 private int mNextUid; 462 IsolatedUidRange(int firstUid, int lastUid)463 IsolatedUidRange(int firstUid, int lastUid) { 464 mFirstUid = firstUid; 465 mLastUid = lastUid; 466 mNextUid = firstUid; 467 } 468 469 @GuardedBy("ProcessList.this.mService") allocateIsolatedUidLocked(int userId)470 int allocateIsolatedUidLocked(int userId) { 471 int uid; 472 int stepsLeft = (mLastUid - mFirstUid + 1); 473 for (int i = 0; i < stepsLeft; ++i) { 474 if (mNextUid < mFirstUid || mNextUid > mLastUid) { 475 mNextUid = mFirstUid; 476 } 477 uid = UserHandle.getUid(userId, mNextUid); 478 mNextUid++; 479 if (!mUidUsed.get(uid, false)) { 480 mUidUsed.put(uid, true); 481 return uid; 482 } 483 } 484 return -1; 485 } 486 487 @GuardedBy("ProcessList.this.mService") freeIsolatedUidLocked(int uid)488 void freeIsolatedUidLocked(int uid) { 489 mUidUsed.delete(uid); 490 } 491 }; 492 493 /** 494 * A class that allocates ranges of isolated UIDs per application, and keeps track of them. 495 */ 496 final class IsolatedUidRangeAllocator { 497 private final int mFirstUid; 498 private final int mNumUidRanges; 499 private final int mNumUidsPerRange; 500 /** 501 * We map the uid range [mFirstUid, mFirstUid + mNumUidRanges * mNumUidsPerRange) 502 * back to an underlying bitset of [0, mNumUidRanges) and allocate out of that. 503 */ 504 @GuardedBy("ProcessList.this.mService") 505 private final BitSet mAvailableUidRanges; 506 @GuardedBy("ProcessList.this.mService") 507 private final ProcessMap<IsolatedUidRange> mAppRanges = new ProcessMap<IsolatedUidRange>(); 508 IsolatedUidRangeAllocator(int firstUid, int lastUid, int numUidsPerRange)509 IsolatedUidRangeAllocator(int firstUid, int lastUid, int numUidsPerRange) { 510 mFirstUid = firstUid; 511 mNumUidsPerRange = numUidsPerRange; 512 mNumUidRanges = (lastUid - firstUid + 1) / numUidsPerRange; 513 mAvailableUidRanges = new BitSet(mNumUidRanges); 514 // Mark all as available 515 mAvailableUidRanges.set(0, mNumUidRanges); 516 } 517 518 @GuardedBy("ProcessList.this.mService") getIsolatedUidRangeLocked(String processName, int uid)519 IsolatedUidRange getIsolatedUidRangeLocked(String processName, int uid) { 520 return mAppRanges.get(processName, uid); 521 } 522 523 @GuardedBy("ProcessList.this.mService") getOrCreateIsolatedUidRangeLocked(String processName, int uid)524 IsolatedUidRange getOrCreateIsolatedUidRangeLocked(String processName, int uid) { 525 IsolatedUidRange range = getIsolatedUidRangeLocked(processName, uid); 526 if (range == null) { 527 int uidRangeIndex = mAvailableUidRanges.nextSetBit(0); 528 if (uidRangeIndex < 0) { 529 // No free range 530 return null; 531 } 532 mAvailableUidRanges.clear(uidRangeIndex); 533 int actualUid = mFirstUid + uidRangeIndex * mNumUidsPerRange; 534 range = new IsolatedUidRange(actualUid, actualUid + mNumUidsPerRange - 1); 535 mAppRanges.put(processName, uid, range); 536 } 537 return range; 538 } 539 540 @GuardedBy("ProcessList.this.mService") freeUidRangeLocked(ApplicationInfo info)541 void freeUidRangeLocked(ApplicationInfo info) { 542 // Find the UID range 543 IsolatedUidRange range = mAppRanges.get(info.processName, info.uid); 544 if (range != null) { 545 // Map back to starting uid 546 final int uidRangeIndex = (range.mFirstUid - mFirstUid) / mNumUidsPerRange; 547 // Mark it as available in the underlying bitset 548 mAvailableUidRanges.set(uidRangeIndex); 549 // And the map 550 mAppRanges.remove(info.processName, info.uid); 551 } 552 } 553 } 554 555 /** 556 * The available isolated UIDs for processes that are not spawned from an application zygote. 557 */ 558 @VisibleForTesting 559 IsolatedUidRange mGlobalIsolatedUids = new IsolatedUidRange(Process.FIRST_ISOLATED_UID, 560 Process.LAST_ISOLATED_UID); 561 562 /** 563 * An allocator for isolated UID ranges for apps that use an application zygote. 564 */ 565 @VisibleForTesting 566 IsolatedUidRangeAllocator mAppIsolatedUidRangeAllocator = 567 new IsolatedUidRangeAllocator(Process.FIRST_APP_ZYGOTE_ISOLATED_UID, 568 Process.LAST_APP_ZYGOTE_ISOLATED_UID, Process.NUM_UIDS_PER_APP_ZYGOTE); 569 570 /** 571 * Processes that are being forcibly torn down. 572 */ 573 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>(); 574 575 /** 576 * All of the applications we currently have running organized by name. 577 * The keys are strings of the application package name (as 578 * returned by the package manager), and the keys are ApplicationRecord 579 * objects. 580 */ 581 final MyProcessMap mProcessNames = new MyProcessMap(); 582 583 final class MyProcessMap extends ProcessMap<ProcessRecord> { 584 @Override put(String name, int uid, ProcessRecord value)585 public ProcessRecord put(String name, int uid, ProcessRecord value) { 586 final ProcessRecord r = super.put(name, uid, value); 587 mService.mAtmInternal.onProcessAdded(r.getWindowProcessController()); 588 return r; 589 } 590 591 @Override remove(String name, int uid)592 public ProcessRecord remove(String name, int uid) { 593 final ProcessRecord r = super.remove(name, uid); 594 mService.mAtmInternal.onProcessRemoved(name, uid); 595 return r; 596 } 597 } 598 599 final class KillHandler extends Handler { 600 static final int KILL_PROCESS_GROUP_MSG = 4000; 601 static final int LMKD_RECONNECT_MSG = 4001; 602 static final int LMKD_PROC_KILLED_MSG = 4002; 603 KillHandler(Looper looper)604 public KillHandler(Looper looper) { 605 super(looper, null, true); 606 } 607 608 @Override handleMessage(Message msg)609 public void handleMessage(Message msg) { 610 switch (msg.what) { 611 case KILL_PROCESS_GROUP_MSG: 612 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup"); 613 Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */); 614 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 615 break; 616 case LMKD_RECONNECT_MSG: 617 if (!sLmkdConnection.connect()) { 618 Slog.i(TAG, "Failed to connect to lmkd, retry after " 619 + LMKD_RECONNECT_DELAY_MS + " ms"); 620 // retry after LMKD_RECONNECT_DELAY_MS 621 sKillHandler.sendMessageDelayed(sKillHandler.obtainMessage( 622 KillHandler.LMKD_RECONNECT_MSG), LMKD_RECONNECT_DELAY_MS); 623 } 624 break; 625 case LMKD_PROC_KILLED_MSG: 626 handleLmkdProcKilled(msg.arg1 /* pid */, msg.arg2 /* uid */); 627 break; 628 629 default: 630 super.handleMessage(msg); 631 } 632 } 633 } 634 635 //////////////////// END FIELDS //////////////////// 636 ProcessList()637 ProcessList() { 638 MemInfoReader minfo = new MemInfoReader(); 639 minfo.readMemInfo(); 640 mTotalMemMb = minfo.getTotalSize()/(1024*1024); 641 updateOomLevels(0, 0, false); 642 } 643 init(ActivityManagerService service, ActiveUids activeUids, PlatformCompat platformCompat)644 void init(ActivityManagerService service, ActiveUids activeUids, 645 PlatformCompat platformCompat) { 646 mService = service; 647 mActiveUids = activeUids; 648 mPlatformCompat = platformCompat; 649 650 if (sKillHandler == null) { 651 sKillThread = new ServiceThread(TAG + ":kill", 652 THREAD_PRIORITY_BACKGROUND, true /* allowIo */); 653 sKillThread.start(); 654 sKillHandler = new KillHandler(sKillThread.getLooper()); 655 sLmkdConnection = new LmkdConnection(sKillThread.getLooper().getQueue(), 656 new LmkdConnection.LmkdConnectionListener() { 657 @Override 658 public boolean onConnect(OutputStream ostream) { 659 Slog.i(TAG, "Connection with lmkd established"); 660 return onLmkdConnect(ostream); 661 } 662 @Override 663 public void onDisconnect() { 664 Slog.w(TAG, "Lost connection to lmkd"); 665 // start reconnection after delay to let lmkd restart 666 sKillHandler.sendMessageDelayed(sKillHandler.obtainMessage( 667 KillHandler.LMKD_RECONNECT_MSG), LMKD_RECONNECT_DELAY_MS); 668 } 669 @Override 670 public boolean isReplyExpected(ByteBuffer replyBuf, 671 ByteBuffer dataReceived, int receivedLen) { 672 // compare the preambule (currently one integer) to check if 673 // this is the reply packet we are waiting for 674 return (receivedLen == replyBuf.array().length 675 && dataReceived.getInt(0) == replyBuf.getInt(0)); 676 } 677 678 @Override 679 public boolean handleUnsolicitedMessage(ByteBuffer dataReceived, 680 int receivedLen) { 681 if (receivedLen < 4) { 682 return false; 683 } 684 switch (dataReceived.getInt(0)) { 685 case LMK_PROCKILL: 686 if (receivedLen != 12) { 687 return false; 688 } 689 sKillHandler.obtainMessage(KillHandler.LMKD_PROC_KILLED_MSG, 690 dataReceived.getInt(4), dataReceived.getInt(8)) 691 .sendToTarget(); 692 return true; 693 default: 694 return false; 695 } 696 } 697 } 698 ); 699 // Start listening on incoming connections from zygotes. 700 mSystemServerSocketForZygote = createSystemServerSocketForZygote(); 701 if (mSystemServerSocketForZygote != null) { 702 sKillHandler.getLooper().getQueue().addOnFileDescriptorEventListener( 703 mSystemServerSocketForZygote.getFileDescriptor(), 704 EVENT_INPUT, this::handleZygoteMessages); 705 } 706 } 707 } 708 applyDisplaySize(WindowManagerService wm)709 void applyDisplaySize(WindowManagerService wm) { 710 if (!mHaveDisplaySize) { 711 Point p = new Point(); 712 // TODO(multi-display): Compute based on sum of all connected displays' resolutions. 713 wm.getBaseDisplaySize(Display.DEFAULT_DISPLAY, p); 714 if (p.x != 0 && p.y != 0) { 715 updateOomLevels(p.x, p.y, true); 716 mHaveDisplaySize = true; 717 } 718 } 719 } 720 updateOomLevels(int displayWidth, int displayHeight, boolean write)721 private void updateOomLevels(int displayWidth, int displayHeight, boolean write) { 722 // Scale buckets from avail memory: at 300MB we use the lowest values to 723 // 700MB or more for the top values. 724 float scaleMem = ((float) (mTotalMemMb - 350)) / (700 - 350); 725 726 // Scale buckets from screen size. 727 int minSize = 480 * 800; // 384000 728 int maxSize = 1280 * 800; // 1024000 230400 870400 .264 729 float scaleDisp = ((float)(displayWidth * displayHeight) - minSize) / (maxSize - minSize); 730 if (false) { 731 Slog.i("XXXXXX", "scaleMem=" + scaleMem); 732 Slog.i("XXXXXX", "scaleDisp=" + scaleDisp + " dw=" + displayWidth 733 + " dh=" + displayHeight); 734 } 735 736 float scale = scaleMem > scaleDisp ? scaleMem : scaleDisp; 737 if (scale < 0) scale = 0; 738 else if (scale > 1) scale = 1; 739 int minfree_adj = Resources.getSystem().getInteger( 740 com.android.internal.R.integer.config_lowMemoryKillerMinFreeKbytesAdjust); 741 int minfree_abs = Resources.getSystem().getInteger( 742 com.android.internal.R.integer.config_lowMemoryKillerMinFreeKbytesAbsolute); 743 if (false) { 744 Slog.i("XXXXXX", "minfree_adj=" + minfree_adj + " minfree_abs=" + minfree_abs); 745 } 746 747 final boolean is64bit = Build.SUPPORTED_64_BIT_ABIS.length > 0; 748 749 for (int i = 0; i < mOomAdj.length; i++) { 750 int low = mOomMinFreeLow[i]; 751 int high = mOomMinFreeHigh[i]; 752 if (is64bit) { 753 // Increase the high min-free levels for cached processes for 64-bit 754 if (i == 4) high = (high * 3) / 2; 755 else if (i == 5) high = (high * 7) / 4; 756 } 757 mOomMinFree[i] = (int)(low + ((high - low) * scale)); 758 } 759 760 if (minfree_abs >= 0) { 761 for (int i = 0; i < mOomAdj.length; i++) { 762 mOomMinFree[i] = (int)((float)minfree_abs * mOomMinFree[i] 763 / mOomMinFree[mOomAdj.length - 1]); 764 } 765 } 766 767 if (minfree_adj != 0) { 768 for (int i = 0; i < mOomAdj.length; i++) { 769 mOomMinFree[i] += (int)((float) minfree_adj * mOomMinFree[i] 770 / mOomMinFree[mOomAdj.length - 1]); 771 if (mOomMinFree[i] < 0) { 772 mOomMinFree[i] = 0; 773 } 774 } 775 } 776 777 // The maximum size we will restore a process from cached to background, when under 778 // memory duress, is 1/3 the size we have reserved for kernel caches and other overhead 779 // before killing background processes. 780 mCachedRestoreLevel = (getMemLevel(ProcessList.CACHED_APP_MAX_ADJ) / 1024) / 3; 781 782 // Ask the kernel to try to keep enough memory free to allocate 3 full 783 // screen 32bpp buffers without entering direct reclaim. 784 int reserve = displayWidth * displayHeight * 4 * 3 / 1024; 785 int reserve_adj = Resources.getSystem().getInteger( 786 com.android.internal.R.integer.config_extraFreeKbytesAdjust); 787 int reserve_abs = Resources.getSystem().getInteger( 788 com.android.internal.R.integer.config_extraFreeKbytesAbsolute); 789 790 if (reserve_abs >= 0) { 791 reserve = reserve_abs; 792 } 793 794 if (reserve_adj != 0) { 795 reserve += reserve_adj; 796 if (reserve < 0) { 797 reserve = 0; 798 } 799 } 800 801 if (write) { 802 ByteBuffer buf = ByteBuffer.allocate(4 * (2 * mOomAdj.length + 1)); 803 buf.putInt(LMK_TARGET); 804 for (int i = 0; i < mOomAdj.length; i++) { 805 buf.putInt((mOomMinFree[i] * 1024)/PAGE_SIZE); 806 buf.putInt(mOomAdj[i]); 807 } 808 809 writeLmkd(buf, null); 810 SystemProperties.set("sys.sysctl.extra_free_kbytes", Integer.toString(reserve)); 811 mOomLevelsSet = true; 812 } 813 // GB: 2048,3072,4096,6144,7168,8192 814 // HC: 8192,10240,12288,14336,16384,20480 815 } 816 computeEmptyProcessLimit(int totalProcessLimit)817 public static int computeEmptyProcessLimit(int totalProcessLimit) { 818 return totalProcessLimit/2; 819 } 820 buildOomTag(String prefix, String compactPrefix, String space, int val, int base, boolean compact)821 private static String buildOomTag(String prefix, String compactPrefix, String space, int val, 822 int base, boolean compact) { 823 final int diff = val - base; 824 if (diff == 0) { 825 if (compact) { 826 return compactPrefix; 827 } 828 if (space == null) return prefix; 829 return prefix + space; 830 } 831 if (diff < 10) { 832 return prefix + (compact ? "+" : "+ ") + Integer.toString(diff); 833 } 834 return prefix + "+" + Integer.toString(diff); 835 } 836 makeOomAdjString(int setAdj, boolean compact)837 public static String makeOomAdjString(int setAdj, boolean compact) { 838 if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 839 return buildOomTag("cch", "cch", " ", setAdj, 840 ProcessList.CACHED_APP_MIN_ADJ, compact); 841 } else if (setAdj >= ProcessList.SERVICE_B_ADJ) { 842 return buildOomTag("svcb ", "svcb", null, setAdj, 843 ProcessList.SERVICE_B_ADJ, compact); 844 } else if (setAdj >= ProcessList.PREVIOUS_APP_ADJ) { 845 return buildOomTag("prev ", "prev", null, setAdj, 846 ProcessList.PREVIOUS_APP_ADJ, compact); 847 } else if (setAdj >= ProcessList.HOME_APP_ADJ) { 848 return buildOomTag("home ", "home", null, setAdj, 849 ProcessList.HOME_APP_ADJ, compact); 850 } else if (setAdj >= ProcessList.SERVICE_ADJ) { 851 return buildOomTag("svc ", "svc", null, setAdj, 852 ProcessList.SERVICE_ADJ, compact); 853 } else if (setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 854 return buildOomTag("hvy ", "hvy", null, setAdj, 855 ProcessList.HEAVY_WEIGHT_APP_ADJ, compact); 856 } else if (setAdj >= ProcessList.BACKUP_APP_ADJ) { 857 return buildOomTag("bkup ", "bkup", null, setAdj, 858 ProcessList.BACKUP_APP_ADJ, compact); 859 } else if (setAdj >= ProcessList.PERCEPTIBLE_LOW_APP_ADJ) { 860 return buildOomTag("prcl ", "prcl", null, setAdj, 861 ProcessList.PERCEPTIBLE_LOW_APP_ADJ, compact); 862 } else if (setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) { 863 return buildOomTag("prcp ", "prcp", null, setAdj, 864 ProcessList.PERCEPTIBLE_APP_ADJ, compact); 865 } else if (setAdj >= ProcessList.VISIBLE_APP_ADJ) { 866 return buildOomTag("vis", "vis", " ", setAdj, 867 ProcessList.VISIBLE_APP_ADJ, compact); 868 } else if (setAdj >= ProcessList.FOREGROUND_APP_ADJ) { 869 return buildOomTag("fore ", "fore", null, setAdj, 870 ProcessList.FOREGROUND_APP_ADJ, compact); 871 } else if (setAdj >= ProcessList.PERSISTENT_SERVICE_ADJ) { 872 return buildOomTag("psvc ", "psvc", null, setAdj, 873 ProcessList.PERSISTENT_SERVICE_ADJ, compact); 874 } else if (setAdj >= ProcessList.PERSISTENT_PROC_ADJ) { 875 return buildOomTag("pers ", "pers", null, setAdj, 876 ProcessList.PERSISTENT_PROC_ADJ, compact); 877 } else if (setAdj >= ProcessList.SYSTEM_ADJ) { 878 return buildOomTag("sys ", "sys", null, setAdj, 879 ProcessList.SYSTEM_ADJ, compact); 880 } else if (setAdj >= ProcessList.NATIVE_ADJ) { 881 return buildOomTag("ntv ", "ntv", null, setAdj, 882 ProcessList.NATIVE_ADJ, compact); 883 } else { 884 return Integer.toString(setAdj); 885 } 886 } 887 makeProcStateString(int curProcState)888 public static String makeProcStateString(int curProcState) { 889 String procState; 890 switch (curProcState) { 891 case ActivityManager.PROCESS_STATE_PERSISTENT: 892 procState = "PER "; 893 break; 894 case ActivityManager.PROCESS_STATE_PERSISTENT_UI: 895 procState = "PERU"; 896 break; 897 case ActivityManager.PROCESS_STATE_TOP: 898 procState = "TOP "; 899 break; 900 case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION: 901 procState = "FGSL"; 902 break; 903 case ActivityManager.PROCESS_STATE_BOUND_TOP: 904 procState = "BTOP"; 905 break; 906 case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE: 907 procState = "FGS "; 908 break; 909 case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE: 910 procState = "BFGS"; 911 break; 912 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND: 913 procState = "IMPF"; 914 break; 915 case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND: 916 procState = "IMPB"; 917 break; 918 case ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND: 919 procState = "TRNB"; 920 break; 921 case ActivityManager.PROCESS_STATE_BACKUP: 922 procState = "BKUP"; 923 break; 924 case ActivityManager.PROCESS_STATE_SERVICE: 925 procState = "SVC "; 926 break; 927 case ActivityManager.PROCESS_STATE_RECEIVER: 928 procState = "RCVR"; 929 break; 930 case ActivityManager.PROCESS_STATE_TOP_SLEEPING: 931 procState = "TPSL"; 932 break; 933 case ActivityManager.PROCESS_STATE_HEAVY_WEIGHT: 934 procState = "HVY "; 935 break; 936 case ActivityManager.PROCESS_STATE_HOME: 937 procState = "HOME"; 938 break; 939 case ActivityManager.PROCESS_STATE_LAST_ACTIVITY: 940 procState = "LAST"; 941 break; 942 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 943 procState = "CAC "; 944 break; 945 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 946 procState = "CACC"; 947 break; 948 case ActivityManager.PROCESS_STATE_CACHED_RECENT: 949 procState = "CRE "; 950 break; 951 case ActivityManager.PROCESS_STATE_CACHED_EMPTY: 952 procState = "CEM "; 953 break; 954 case ActivityManager.PROCESS_STATE_NONEXISTENT: 955 procState = "NONE"; 956 break; 957 default: 958 procState = "??"; 959 break; 960 } 961 return procState; 962 } 963 makeProcStateProtoEnum(int curProcState)964 public static int makeProcStateProtoEnum(int curProcState) { 965 switch (curProcState) { 966 case ActivityManager.PROCESS_STATE_PERSISTENT: 967 return AppProtoEnums.PROCESS_STATE_PERSISTENT; 968 case ActivityManager.PROCESS_STATE_PERSISTENT_UI: 969 return AppProtoEnums.PROCESS_STATE_PERSISTENT_UI; 970 case ActivityManager.PROCESS_STATE_TOP: 971 return AppProtoEnums.PROCESS_STATE_TOP; 972 case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION: 973 return AppProtoEnums.PROCESS_STATE_FOREGROUND_SERVICE; 974 case ActivityManager.PROCESS_STATE_BOUND_TOP: 975 return AppProtoEnums.PROCESS_STATE_BOUND_TOP; 976 case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE: 977 return AppProtoEnums.PROCESS_STATE_FOREGROUND_SERVICE; 978 case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE: 979 return AppProtoEnums.PROCESS_STATE_BOUND_FOREGROUND_SERVICE; 980 case ActivityManager.PROCESS_STATE_TOP_SLEEPING: 981 return AppProtoEnums.PROCESS_STATE_TOP_SLEEPING; 982 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND: 983 return AppProtoEnums.PROCESS_STATE_IMPORTANT_FOREGROUND; 984 case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND: 985 return AppProtoEnums.PROCESS_STATE_IMPORTANT_BACKGROUND; 986 case ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND: 987 return AppProtoEnums.PROCESS_STATE_TRANSIENT_BACKGROUND; 988 case ActivityManager.PROCESS_STATE_BACKUP: 989 return AppProtoEnums.PROCESS_STATE_BACKUP; 990 case ActivityManager.PROCESS_STATE_HEAVY_WEIGHT: 991 return AppProtoEnums.PROCESS_STATE_HEAVY_WEIGHT; 992 case ActivityManager.PROCESS_STATE_SERVICE: 993 return AppProtoEnums.PROCESS_STATE_SERVICE; 994 case ActivityManager.PROCESS_STATE_RECEIVER: 995 return AppProtoEnums.PROCESS_STATE_RECEIVER; 996 case ActivityManager.PROCESS_STATE_HOME: 997 return AppProtoEnums.PROCESS_STATE_HOME; 998 case ActivityManager.PROCESS_STATE_LAST_ACTIVITY: 999 return AppProtoEnums.PROCESS_STATE_LAST_ACTIVITY; 1000 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 1001 return AppProtoEnums.PROCESS_STATE_CACHED_ACTIVITY; 1002 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 1003 return AppProtoEnums.PROCESS_STATE_CACHED_ACTIVITY_CLIENT; 1004 case ActivityManager.PROCESS_STATE_CACHED_RECENT: 1005 return AppProtoEnums.PROCESS_STATE_CACHED_RECENT; 1006 case ActivityManager.PROCESS_STATE_CACHED_EMPTY: 1007 return AppProtoEnums.PROCESS_STATE_CACHED_EMPTY; 1008 case ActivityManager.PROCESS_STATE_NONEXISTENT: 1009 return AppProtoEnums.PROCESS_STATE_NONEXISTENT; 1010 case ActivityManager.PROCESS_STATE_UNKNOWN: 1011 return AppProtoEnums.PROCESS_STATE_UNKNOWN; 1012 default: 1013 return AppProtoEnums.PROCESS_STATE_UNKNOWN_TO_PROTO; 1014 } 1015 } 1016 appendRamKb(StringBuilder sb, long ramKb)1017 public static void appendRamKb(StringBuilder sb, long ramKb) { 1018 for (int j = 0, fact = 10; j < 6; j++, fact *= 10) { 1019 if (ramKb < fact) { 1020 sb.append(' '); 1021 } 1022 } 1023 sb.append(ramKb); 1024 } 1025 1026 // How long after a state change that it is safe to collect PSS without it being dirty. 1027 public static final int PSS_SAFE_TIME_FROM_STATE_CHANGE = 1000; 1028 1029 // The minimum time interval after a state change it is safe to collect PSS. 1030 public static final int PSS_MIN_TIME_FROM_STATE_CHANGE = 15*1000; 1031 1032 // The maximum amount of time we want to go between PSS collections. 1033 public static final int PSS_MAX_INTERVAL = 60*60*1000; 1034 1035 // The minimum amount of time between successive PSS requests for *all* processes. 1036 public static final int PSS_ALL_INTERVAL = 20*60*1000; 1037 1038 // The amount of time until PSS when a persistent process first appears. 1039 private static final int PSS_FIRST_PERSISTENT_INTERVAL = 30*1000; 1040 1041 // The amount of time until PSS when a process first becomes top. 1042 private static final int PSS_FIRST_TOP_INTERVAL = 10*1000; 1043 1044 // The amount of time until PSS when a process first goes into the background. 1045 private static final int PSS_FIRST_BACKGROUND_INTERVAL = 20*1000; 1046 1047 // The amount of time until PSS when a process first becomes cached. 1048 private static final int PSS_FIRST_CACHED_INTERVAL = 20*1000; 1049 1050 // The amount of time until PSS when an important process stays in the same state. 1051 private static final int PSS_SAME_PERSISTENT_INTERVAL = 10*60*1000; 1052 1053 // The amount of time until PSS when the top process stays in the same state. 1054 private static final int PSS_SAME_TOP_INTERVAL = 1*60*1000; 1055 1056 // The amount of time until PSS when an important process stays in the same state. 1057 private static final int PSS_SAME_IMPORTANT_INTERVAL = 10*60*1000; 1058 1059 // The amount of time until PSS when a service process stays in the same state. 1060 private static final int PSS_SAME_SERVICE_INTERVAL = 5*60*1000; 1061 1062 // The amount of time until PSS when a cached process stays in the same state. 1063 private static final int PSS_SAME_CACHED_INTERVAL = 10*60*1000; 1064 1065 // The amount of time until PSS when a persistent process first appears. 1066 private static final int PSS_FIRST_ASLEEP_PERSISTENT_INTERVAL = 1*60*1000; 1067 1068 // The amount of time until PSS when a process first becomes top. 1069 private static final int PSS_FIRST_ASLEEP_TOP_INTERVAL = 20*1000; 1070 1071 // The amount of time until PSS when a process first goes into the background. 1072 private static final int PSS_FIRST_ASLEEP_BACKGROUND_INTERVAL = 30*1000; 1073 1074 // The amount of time until PSS when a process first becomes cached. 1075 private static final int PSS_FIRST_ASLEEP_CACHED_INTERVAL = 1*60*1000; 1076 1077 // The minimum time interval after a state change it is safe to collect PSS. 1078 public static final int PSS_TEST_MIN_TIME_FROM_STATE_CHANGE = 10*1000; 1079 1080 // The amount of time during testing until PSS when a process first becomes top. 1081 private static final int PSS_TEST_FIRST_TOP_INTERVAL = 3*1000; 1082 1083 // The amount of time during testing until PSS when a process first goes into the background. 1084 private static final int PSS_TEST_FIRST_BACKGROUND_INTERVAL = 5*1000; 1085 1086 // The amount of time during testing until PSS when an important process stays in same state. 1087 private static final int PSS_TEST_SAME_IMPORTANT_INTERVAL = 10*1000; 1088 1089 // The amount of time during testing until PSS when a background process stays in same state. 1090 private static final int PSS_TEST_SAME_BACKGROUND_INTERVAL = 15*1000; 1091 1092 public static final int PROC_MEM_PERSISTENT = 0; 1093 public static final int PROC_MEM_TOP = 1; 1094 public static final int PROC_MEM_IMPORTANT = 2; 1095 public static final int PROC_MEM_SERVICE = 3; 1096 public static final int PROC_MEM_CACHED = 4; 1097 public static final int PROC_MEM_NUM = 5; 1098 1099 // Map large set of system process states to 1100 private static final int[] sProcStateToProcMem = new int[] { 1101 PROC_MEM_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT 1102 PROC_MEM_PERSISTENT, // ActivityManager.PROCESS_STATE_PERSISTENT_UI 1103 PROC_MEM_TOP, // ActivityManager.PROCESS_STATE_TOP 1104 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE_LOCATION 1105 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE 1106 PROC_MEM_TOP, // ActivityManager.PROCESS_STATE_BOUND_TOP 1107 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE 1108 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND 1109 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 1110 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_TRANSIENT_BACKGROUND 1111 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_BACKUP 1112 PROC_MEM_SERVICE, // ActivityManager.PROCESS_STATE_SERVICE 1113 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_RECEIVER 1114 PROC_MEM_TOP, // ActivityManager.PROCESS_STATE_TOP_SLEEPING 1115 PROC_MEM_IMPORTANT, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT 1116 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_HOME 1117 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY 1118 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY 1119 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT 1120 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_CACHED_RECENT 1121 PROC_MEM_CACHED, // ActivityManager.PROCESS_STATE_CACHED_EMPTY 1122 }; 1123 1124 private static final long[] sFirstAwakePssTimes = new long[] { 1125 PSS_FIRST_PERSISTENT_INTERVAL, // PROC_MEM_PERSISTENT 1126 PSS_FIRST_TOP_INTERVAL, // PROC_MEM_TOP 1127 PSS_FIRST_BACKGROUND_INTERVAL, // PROC_MEM_IMPORTANT 1128 PSS_FIRST_BACKGROUND_INTERVAL, // PROC_MEM_SERVICE 1129 PSS_FIRST_CACHED_INTERVAL, // PROC_MEM_CACHED 1130 }; 1131 1132 private static final long[] sSameAwakePssTimes = new long[] { 1133 PSS_SAME_PERSISTENT_INTERVAL, // PROC_MEM_PERSISTENT 1134 PSS_SAME_TOP_INTERVAL, // PROC_MEM_TOP 1135 PSS_SAME_IMPORTANT_INTERVAL, // PROC_MEM_IMPORTANT 1136 PSS_SAME_SERVICE_INTERVAL, // PROC_MEM_SERVICE 1137 PSS_SAME_CACHED_INTERVAL, // PROC_MEM_CACHED 1138 }; 1139 1140 private static final long[] sFirstAsleepPssTimes = new long[] { 1141 PSS_FIRST_ASLEEP_PERSISTENT_INTERVAL, // PROC_MEM_PERSISTENT 1142 PSS_FIRST_ASLEEP_TOP_INTERVAL, // PROC_MEM_TOP 1143 PSS_FIRST_ASLEEP_BACKGROUND_INTERVAL, // PROC_MEM_IMPORTANT 1144 PSS_FIRST_ASLEEP_BACKGROUND_INTERVAL, // PROC_MEM_SERVICE 1145 PSS_FIRST_ASLEEP_CACHED_INTERVAL, // PROC_MEM_CACHED 1146 }; 1147 1148 private static final long[] sSameAsleepPssTimes = new long[] { 1149 PSS_SAME_PERSISTENT_INTERVAL, // PROC_MEM_PERSISTENT 1150 PSS_SAME_TOP_INTERVAL, // PROC_MEM_TOP 1151 PSS_SAME_IMPORTANT_INTERVAL, // PROC_MEM_IMPORTANT 1152 PSS_SAME_SERVICE_INTERVAL, // PROC_MEM_SERVICE 1153 PSS_SAME_CACHED_INTERVAL, // PROC_MEM_CACHED 1154 }; 1155 1156 private static final long[] sTestFirstPssTimes = new long[] { 1157 PSS_TEST_FIRST_TOP_INTERVAL, // PROC_MEM_PERSISTENT 1158 PSS_TEST_FIRST_TOP_INTERVAL, // PROC_MEM_TOP 1159 PSS_TEST_FIRST_BACKGROUND_INTERVAL, // PROC_MEM_IMPORTANT 1160 PSS_TEST_FIRST_BACKGROUND_INTERVAL, // PROC_MEM_SERVICE 1161 PSS_TEST_FIRST_BACKGROUND_INTERVAL, // PROC_MEM_CACHED 1162 }; 1163 1164 private static final long[] sTestSamePssTimes = new long[] { 1165 PSS_TEST_SAME_BACKGROUND_INTERVAL, // PROC_MEM_PERSISTENT 1166 PSS_TEST_SAME_IMPORTANT_INTERVAL, // PROC_MEM_TOP 1167 PSS_TEST_SAME_IMPORTANT_INTERVAL, // PROC_MEM_IMPORTANT 1168 PSS_TEST_SAME_BACKGROUND_INTERVAL, // PROC_MEM_SERVICE 1169 PSS_TEST_SAME_BACKGROUND_INTERVAL, // PROC_MEM_CACHED 1170 }; 1171 1172 public static final class ProcStateMemTracker { 1173 final int[] mHighestMem = new int[PROC_MEM_NUM]; 1174 final float[] mScalingFactor = new float[PROC_MEM_NUM]; 1175 int mTotalHighestMem = PROC_MEM_CACHED; 1176 1177 int mPendingMemState; 1178 int mPendingHighestMemState; 1179 float mPendingScalingFactor; 1180 ProcStateMemTracker()1181 public ProcStateMemTracker() { 1182 for (int i = PROC_MEM_PERSISTENT; i < PROC_MEM_NUM; i++) { 1183 mHighestMem[i] = PROC_MEM_NUM; 1184 mScalingFactor[i] = 1.0f; 1185 } 1186 mPendingMemState = -1; 1187 } 1188 dumpLine(PrintWriter pw)1189 public void dumpLine(PrintWriter pw) { 1190 pw.print("best="); 1191 pw.print(mTotalHighestMem); 1192 pw.print(" ("); 1193 boolean needSep = false; 1194 for (int i = 0; i < PROC_MEM_NUM; i++) { 1195 if (mHighestMem[i] < PROC_MEM_NUM) { 1196 if (needSep) { 1197 pw.print(", "); 1198 needSep = false; 1199 } 1200 pw.print(i); 1201 pw.print("="); 1202 pw.print(mHighestMem[i]); 1203 pw.print(" "); 1204 pw.print(mScalingFactor[i]); 1205 pw.print("x"); 1206 needSep = true; 1207 } 1208 } 1209 pw.print(")"); 1210 if (mPendingMemState >= 0) { 1211 pw.print(" / pending state="); 1212 pw.print(mPendingMemState); 1213 pw.print(" highest="); 1214 pw.print(mPendingHighestMemState); 1215 pw.print(" "); 1216 pw.print(mPendingScalingFactor); 1217 pw.print("x"); 1218 } 1219 pw.println(); 1220 } 1221 } 1222 procStatesDifferForMem(int procState1, int procState2)1223 public static boolean procStatesDifferForMem(int procState1, int procState2) { 1224 return sProcStateToProcMem[procState1] != sProcStateToProcMem[procState2]; 1225 } 1226 minTimeFromStateChange(boolean test)1227 public static long minTimeFromStateChange(boolean test) { 1228 return test ? PSS_TEST_MIN_TIME_FROM_STATE_CHANGE : PSS_MIN_TIME_FROM_STATE_CHANGE; 1229 } 1230 commitNextPssTime(ProcStateMemTracker tracker)1231 public static void commitNextPssTime(ProcStateMemTracker tracker) { 1232 if (tracker.mPendingMemState >= 0) { 1233 tracker.mHighestMem[tracker.mPendingMemState] = tracker.mPendingHighestMemState; 1234 tracker.mScalingFactor[tracker.mPendingMemState] = tracker.mPendingScalingFactor; 1235 tracker.mTotalHighestMem = tracker.mPendingHighestMemState; 1236 tracker.mPendingMemState = -1; 1237 } 1238 } 1239 abortNextPssTime(ProcStateMemTracker tracker)1240 public static void abortNextPssTime(ProcStateMemTracker tracker) { 1241 tracker.mPendingMemState = -1; 1242 } 1243 computeNextPssTime(int procState, ProcStateMemTracker tracker, boolean test, boolean sleeping, long now)1244 public static long computeNextPssTime(int procState, ProcStateMemTracker tracker, boolean test, 1245 boolean sleeping, long now) { 1246 boolean first; 1247 float scalingFactor; 1248 final int memState = sProcStateToProcMem[procState]; 1249 if (tracker != null) { 1250 final int highestMemState = memState < tracker.mTotalHighestMem 1251 ? memState : tracker.mTotalHighestMem; 1252 first = highestMemState < tracker.mHighestMem[memState]; 1253 tracker.mPendingMemState = memState; 1254 tracker.mPendingHighestMemState = highestMemState; 1255 if (first) { 1256 tracker.mPendingScalingFactor = scalingFactor = 1.0f; 1257 } else { 1258 scalingFactor = tracker.mScalingFactor[memState]; 1259 tracker.mPendingScalingFactor = scalingFactor * 1.5f; 1260 } 1261 } else { 1262 first = true; 1263 scalingFactor = 1.0f; 1264 } 1265 final long[] table = test 1266 ? (first 1267 ? sTestFirstPssTimes 1268 : sTestSamePssTimes) 1269 : (first 1270 ? (sleeping ? sFirstAsleepPssTimes : sFirstAwakePssTimes) 1271 : (sleeping ? sSameAsleepPssTimes : sSameAwakePssTimes)); 1272 long delay = (long)(table[memState] * scalingFactor); 1273 if (delay > PSS_MAX_INTERVAL) { 1274 delay = PSS_MAX_INTERVAL; 1275 } 1276 return now + delay; 1277 } 1278 1279 long getMemLevel(int adjustment) { 1280 for (int i = 0; i < mOomAdj.length; i++) { 1281 if (adjustment <= mOomAdj[i]) { 1282 return mOomMinFree[i] * 1024; 1283 } 1284 } 1285 return mOomMinFree[mOomAdj.length - 1] * 1024; 1286 } 1287 1288 /** 1289 * Return the maximum pss size in kb that we consider a process acceptable to 1290 * restore from its cached state for running in the background when RAM is low. 1291 */ 1292 long getCachedRestoreThresholdKb() { 1293 return mCachedRestoreLevel; 1294 } 1295 1296 /** 1297 * Set the out-of-memory badness adjustment for a process. 1298 * If {@code pid <= 0}, this method will be a no-op. 1299 * 1300 * @param pid The process identifier to set. 1301 * @param uid The uid of the app 1302 * @param amt Adjustment value -- lmkd allows -1000 to +1000 1303 * 1304 * {@hide} 1305 */ 1306 public static void setOomAdj(int pid, int uid, int amt) { 1307 // This indicates that the process is not started yet and so no need to proceed further. 1308 if (pid <= 0) { 1309 return; 1310 } 1311 if (amt == UNKNOWN_ADJ) 1312 return; 1313 1314 long start = SystemClock.elapsedRealtime(); 1315 ByteBuffer buf = ByteBuffer.allocate(4 * 4); 1316 buf.putInt(LMK_PROCPRIO); 1317 buf.putInt(pid); 1318 buf.putInt(uid); 1319 buf.putInt(amt); 1320 writeLmkd(buf, null); 1321 long now = SystemClock.elapsedRealtime(); 1322 if ((now-start) > 250) { 1323 Slog.w("ActivityManager", "SLOW OOM ADJ: " + (now-start) + "ms for pid " + pid 1324 + " = " + amt); 1325 } 1326 } 1327 1328 /* 1329 * {@hide} 1330 */ 1331 public static final void remove(int pid) { 1332 // This indicates that the process is not started yet and so no need to proceed further. 1333 if (pid <= 0) { 1334 return; 1335 } 1336 ByteBuffer buf = ByteBuffer.allocate(4 * 2); 1337 buf.putInt(LMK_PROCREMOVE); 1338 buf.putInt(pid); 1339 writeLmkd(buf, null); 1340 } 1341 1342 /* 1343 * {@hide} 1344 */ 1345 public static final Integer getLmkdKillCount(int min_oom_adj, int max_oom_adj) { 1346 ByteBuffer buf = ByteBuffer.allocate(4 * 3); 1347 ByteBuffer repl = ByteBuffer.allocate(4 * 2); 1348 buf.putInt(LMK_GETKILLCNT); 1349 buf.putInt(min_oom_adj); 1350 buf.putInt(max_oom_adj); 1351 // indicate what we are waiting for 1352 repl.putInt(LMK_GETKILLCNT); 1353 repl.rewind(); 1354 if (writeLmkd(buf, repl) && repl.getInt() == LMK_GETKILLCNT) { 1355 return new Integer(repl.getInt()); 1356 } 1357 return null; 1358 } 1359 1360 boolean onLmkdConnect(OutputStream ostream) { 1361 try { 1362 // Purge any previously registered pids 1363 ByteBuffer buf = ByteBuffer.allocate(4); 1364 buf.putInt(LMK_PROCPURGE); 1365 ostream.write(buf.array(), 0, buf.position()); 1366 if (mOomLevelsSet) { 1367 // Reset oom_adj levels 1368 buf = ByteBuffer.allocate(4 * (2 * mOomAdj.length + 1)); 1369 buf.putInt(LMK_TARGET); 1370 for (int i = 0; i < mOomAdj.length; i++) { 1371 buf.putInt((mOomMinFree[i] * 1024) / PAGE_SIZE); 1372 buf.putInt(mOomAdj[i]); 1373 } 1374 ostream.write(buf.array(), 0, buf.position()); 1375 } 1376 // Subscribe for kill event notifications 1377 buf = ByteBuffer.allocate(4 * 2); 1378 buf.putInt(LMK_SUBSCRIBE); 1379 buf.putInt(LMK_ASYNC_EVENT_KILL); 1380 ostream.write(buf.array(), 0, buf.position()); 1381 } catch (IOException ex) { 1382 return false; 1383 } 1384 return true; 1385 } 1386 1387 private static boolean writeLmkd(ByteBuffer buf, ByteBuffer repl) { 1388 if (!sLmkdConnection.isConnected()) { 1389 // try to connect immediately and then keep retrying 1390 sKillHandler.sendMessage( 1391 sKillHandler.obtainMessage(KillHandler.LMKD_RECONNECT_MSG)); 1392 1393 // wait for connection retrying 3 times (up to 3 seconds) 1394 if (!sLmkdConnection.waitForConnection(3 * LMKD_RECONNECT_DELAY_MS)) { 1395 return false; 1396 } 1397 } 1398 1399 return sLmkdConnection.exchange(buf, repl); 1400 } 1401 1402 static void killProcessGroup(int uid, int pid) { 1403 /* static; one-time init here */ 1404 if (sKillHandler != null) { 1405 sKillHandler.sendMessage( 1406 sKillHandler.obtainMessage(KillHandler.KILL_PROCESS_GROUP_MSG, uid, pid)); 1407 } else { 1408 Slog.w(TAG, "Asked to kill process group before system bringup!"); 1409 Process.killProcessGroup(uid, pid); 1410 } 1411 } 1412 1413 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean 1414 keepIfLarge) { 1415 if (uid == SYSTEM_UID) { 1416 // The system gets to run in any process. If there are multiple 1417 // processes with the same uid, just pick the first (this 1418 // should never happen). 1419 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName); 1420 if (procs == null) return null; 1421 final int procCount = procs.size(); 1422 for (int i = 0; i < procCount; i++) { 1423 final int procUid = procs.keyAt(i); 1424 if (!UserHandle.isCore(procUid) || !UserHandle.isSameUser(procUid, uid)) { 1425 // Don't use an app process or different user process for system component. 1426 continue; 1427 } 1428 return procs.valueAt(i); 1429 } 1430 } 1431 ProcessRecord proc = mProcessNames.get(processName, uid); 1432 if (false && proc != null && !keepIfLarge 1433 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY 1434 && proc.lastCachedPss >= 4000) { 1435 // Turn this condition on to cause killing to happen regularly, for testing. 1436 if (proc.baseProcessTracker != null) { 1437 proc.baseProcessTracker.reportCachedKill(proc.pkgList.mPkgList, proc.lastCachedPss); 1438 for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) { 1439 ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg); 1440 StatsLog.write(StatsLog.CACHED_KILL_REPORTED, 1441 proc.info.uid, 1442 holder.state.getName(), 1443 holder.state.getPackage(), 1444 proc.lastCachedPss, holder.appVersion); 1445 } 1446 } 1447 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 1448 } else if (proc != null && !keepIfLarge 1449 && mService.mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 1450 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 1451 if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc 1452 .lastCachedPss); 1453 if (proc.lastCachedPss >= getCachedRestoreThresholdKb()) { 1454 if (proc.baseProcessTracker != null) { 1455 proc.baseProcessTracker.reportCachedKill(proc.pkgList.mPkgList, 1456 proc.lastCachedPss); 1457 for (int ipkg = proc.pkgList.size() - 1; ipkg >= 0; ipkg--) { 1458 ProcessStats.ProcessStateHolder holder = proc.pkgList.valueAt(ipkg); 1459 StatsLog.write(StatsLog.CACHED_KILL_REPORTED, 1460 proc.info.uid, 1461 holder.state.getName(), 1462 holder.state.getPackage(), 1463 proc.lastCachedPss, holder.appVersion); 1464 } 1465 } 1466 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 1467 } 1468 } 1469 return proc; 1470 } 1471 getMemoryInfo(ActivityManager.MemoryInfo outInfo)1472 void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 1473 final long homeAppMem = getMemLevel(HOME_APP_ADJ); 1474 final long cachedAppMem = getMemLevel(CACHED_APP_MIN_ADJ); 1475 outInfo.availMem = getFreeMemory(); 1476 outInfo.totalMem = getTotalMemory(); 1477 outInfo.threshold = homeAppMem; 1478 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2)); 1479 outInfo.hiddenAppThreshold = cachedAppMem; 1480 outInfo.secondaryServerThreshold = getMemLevel(SERVICE_ADJ); 1481 outInfo.visibleAppThreshold = getMemLevel(VISIBLE_APP_ADJ); 1482 outInfo.foregroundAppThreshold = getMemLevel(FOREGROUND_APP_ADJ); 1483 } 1484 1485 ProcessRecord findAppProcessLocked(IBinder app, String reason) { 1486 final int NP = mProcessNames.getMap().size(); 1487 for (int ip = 0; ip < NP; ip++) { 1488 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 1489 final int NA = apps.size(); 1490 for (int ia = 0; ia < NA; ia++) { 1491 ProcessRecord p = apps.valueAt(ia); 1492 if (p.thread != null && p.thread.asBinder() == app) { 1493 return p; 1494 } 1495 } 1496 } 1497 1498 Slog.w(TAG, "Can't find mystery application for " + reason 1499 + " from pid=" + Binder.getCallingPid() 1500 + " uid=" + Binder.getCallingUid() + ": " + app); 1501 return null; 1502 } 1503 1504 private void checkSlow(long startTime, String where) { 1505 long now = SystemClock.uptimeMillis(); 1506 if ((now - startTime) > 50) { 1507 // If we are taking more than 50ms, log about it. 1508 Slog.w(TAG, "Slow operation: " + (now - startTime) + "ms so far, now at " + where); 1509 } 1510 } 1511 1512 /** 1513 * @return {@code true} if process start is successful, false otherwise. 1514 */ 1515 @GuardedBy("mService") 1516 boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, 1517 int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks, 1518 boolean mountExtStorageFull, String abiOverride) { 1519 if (app.pendingStart) { 1520 return true; 1521 } 1522 long startTime = SystemClock.elapsedRealtime(); 1523 if (app.pid > 0 && app.pid != ActivityManagerService.MY_PID) { 1524 checkSlow(startTime, "startProcess: removing from pids map"); 1525 mService.mPidsSelfLocked.remove(app); 1526 mService.mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 1527 checkSlow(startTime, "startProcess: done removing from pids map"); 1528 app.setPid(0); 1529 app.startSeq = 0; 1530 } 1531 1532 if (DEBUG_PROCESSES && mService.mProcessesOnHold.contains(app)) Slog.v( 1533 TAG_PROCESSES, 1534 "startProcessLocked removing on hold: " + app); 1535 mService.mProcessesOnHold.remove(app); 1536 1537 checkSlow(startTime, "startProcess: starting to update cpu stats"); 1538 mService.updateCpuStats(); 1539 checkSlow(startTime, "startProcess: done updating cpu stats"); 1540 1541 try { 1542 try { 1543 final int userId = UserHandle.getUserId(app.uid); 1544 AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId); 1545 } catch (RemoteException e) { 1546 throw e.rethrowAsRuntimeException(); 1547 } 1548 1549 int uid = app.uid; 1550 int[] gids = null; 1551 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 1552 if (!app.isolated) { 1553 int[] permGids = null; 1554 try { 1555 checkSlow(startTime, "startProcess: getting gids from package manager"); 1556 final IPackageManager pm = AppGlobals.getPackageManager(); 1557 permGids = pm.getPackageGids(app.info.packageName, 1558 MATCH_DIRECT_BOOT_AUTO, app.userId); 1559 if (StorageManager.hasIsolatedStorage() && mountExtStorageFull) { 1560 mountExternal = Zygote.MOUNT_EXTERNAL_FULL; 1561 } else { 1562 StorageManagerInternal storageManagerInternal = LocalServices.getService( 1563 StorageManagerInternal.class); 1564 mountExternal = storageManagerInternal.getExternalStorageMountMode(uid, 1565 app.info.packageName); 1566 } 1567 } catch (RemoteException e) { 1568 throw e.rethrowAsRuntimeException(); 1569 } 1570 1571 /* 1572 * Add shared application and profile GIDs so applications can share some 1573 * resources like shared libraries and access user-wide resources 1574 */ 1575 if (ArrayUtils.isEmpty(permGids)) { 1576 gids = new int[3]; 1577 } else { 1578 gids = new int[permGids.length + 3]; 1579 System.arraycopy(permGids, 0, gids, 3, permGids.length); 1580 } 1581 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 1582 gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid)); 1583 gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid)); 1584 1585 // Replace any invalid GIDs 1586 if (gids[0] == UserHandle.ERR_GID) gids[0] = gids[2]; 1587 if (gids[1] == UserHandle.ERR_GID) gids[1] = gids[2]; 1588 } 1589 app.mountMode = mountExternal; 1590 checkSlow(startTime, "startProcess: building args"); 1591 if (mService.mAtmInternal.isFactoryTestProcess(app.getWindowProcessController())) { 1592 uid = 0; 1593 } 1594 int runtimeFlags = 0; 1595 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 1596 runtimeFlags |= Zygote.DEBUG_ENABLE_JDWP; 1597 runtimeFlags |= Zygote.DEBUG_JAVA_DEBUGGABLE; 1598 // Also turn on CheckJNI for debuggable apps. It's quite 1599 // awkward to turn on otherwise. 1600 runtimeFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 1601 1602 // Check if the developer does not want ART verification 1603 if (android.provider.Settings.Global.getInt(mService.mContext.getContentResolver(), 1604 android.provider.Settings.Global.ART_VERIFIER_VERIFY_DEBUGGABLE, 1) == 0) { 1605 runtimeFlags |= Zygote.DISABLE_VERIFIER; 1606 Slog.w(TAG_PROCESSES, app + ": ART verification disabled"); 1607 } 1608 } 1609 // Run the app in safe mode if its manifest requests so or the 1610 // system is booted in safe mode. 1611 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || mService.mSafeMode) { 1612 runtimeFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 1613 } 1614 if ((app.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_PROFILEABLE_BY_SHELL) != 0) { 1615 runtimeFlags |= Zygote.PROFILE_FROM_SHELL; 1616 } 1617 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 1618 runtimeFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 1619 } 1620 String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info"); 1621 if ("1".equals(genDebugInfoProperty) || "true".equals(genDebugInfoProperty)) { 1622 runtimeFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; 1623 } 1624 String genMiniDebugInfoProperty = SystemProperties.get("dalvik.vm.minidebuginfo"); 1625 if ("1".equals(genMiniDebugInfoProperty) || "true".equals(genMiniDebugInfoProperty)) { 1626 runtimeFlags |= Zygote.DEBUG_GENERATE_MINI_DEBUG_INFO; 1627 } 1628 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 1629 runtimeFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 1630 } 1631 if ("1".equals(SystemProperties.get("debug.assert"))) { 1632 runtimeFlags |= Zygote.DEBUG_ENABLE_ASSERT; 1633 } 1634 if ("1".equals(SystemProperties.get("debug.ignoreappsignalhandler"))) { 1635 runtimeFlags |= Zygote.DEBUG_IGNORE_APP_SIGNAL_HANDLER; 1636 } 1637 if (mService.mNativeDebuggingApp != null 1638 && mService.mNativeDebuggingApp.equals(app.processName)) { 1639 // Enable all debug flags required by the native debugger. 1640 runtimeFlags |= Zygote.DEBUG_ALWAYS_JIT; // Don't interpret anything 1641 runtimeFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; // Generate debug info 1642 runtimeFlags |= Zygote.DEBUG_NATIVE_DEBUGGABLE; // Disbale optimizations 1643 mService.mNativeDebuggingApp = null; 1644 } 1645 1646 if (app.info.isEmbeddedDexUsed() 1647 || (app.info.isPrivilegedApp() 1648 && DexManager.isPackageSelectedToRunOob(app.pkgList.mPkgList.keySet()))) { 1649 runtimeFlags |= Zygote.ONLY_USE_SYSTEM_OAT_FILES; 1650 } 1651 1652 if (!disableHiddenApiChecks && !mService.mHiddenApiBlacklist.isDisabled()) { 1653 app.info.maybeUpdateHiddenApiEnforcementPolicy( 1654 mService.mHiddenApiBlacklist.getPolicy()); 1655 @ApplicationInfo.HiddenApiEnforcementPolicy int policy = 1656 app.info.getHiddenApiEnforcementPolicy(); 1657 int policyBits = (policy << Zygote.API_ENFORCEMENT_POLICY_SHIFT); 1658 if ((policyBits & Zygote.API_ENFORCEMENT_POLICY_MASK) != policyBits) { 1659 throw new IllegalStateException("Invalid API policy: " + policy); 1660 } 1661 runtimeFlags |= policyBits; 1662 1663 if (disableTestApiChecks) { 1664 runtimeFlags |= Zygote.DISABLE_TEST_API_ENFORCEMENT_POLICY; 1665 } 1666 } 1667 1668 String useAppImageCache = SystemProperties.get( 1669 PROPERTY_USE_APP_IMAGE_STARTUP_CACHE, ""); 1670 // Property defaults to true currently. 1671 if (!TextUtils.isEmpty(useAppImageCache) && !useAppImageCache.equals("false")) { 1672 runtimeFlags |= Zygote.USE_APP_IMAGE_STARTUP_CACHE; 1673 } 1674 1675 if (Zygote.nativeSupportsMemoryTagging()) { 1676 // System apps are generally more privileged than regular apps, and don't have the 1677 // same app compat concerns as regular apps, so we enable async tag checks for all 1678 // of their processes. 1679 if ((app.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 1680 || mPlatformCompat.isChangeEnabled(NATIVE_MEMORY_TAGGING, app.info)) { 1681 runtimeFlags |= Zygote.MEMORY_TAG_LEVEL_ASYNC; 1682 } 1683 } else if (Zygote.nativeSupportsTaggedPointers()) { 1684 // Enable heap pointer tagging if supported by the kernel, unless disabled by the 1685 // target sdk level or compat feature. 1686 if (mPlatformCompat.isChangeEnabled(NATIVE_HEAP_POINTER_TAGGING, app.info)) { 1687 runtimeFlags |= Zygote.MEMORY_TAG_LEVEL_TBI; 1688 } 1689 } 1690 1691 String invokeWith = null; 1692 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 1693 // Debuggable apps may include a wrapper script with their library directory. 1694 String wrapperFileName = app.info.nativeLibraryDir + "/wrap.sh"; 1695 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 1696 try { 1697 if (new File(wrapperFileName).exists()) { 1698 invokeWith = "/system/bin/logwrapper " + wrapperFileName; 1699 } 1700 } finally { 1701 StrictMode.setThreadPolicy(oldPolicy); 1702 } 1703 } 1704 1705 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi; 1706 if (requiredAbi == null) { 1707 requiredAbi = Build.SUPPORTED_ABIS[0]; 1708 } 1709 1710 String instructionSet = null; 1711 if (app.info.primaryCpuAbi != null) { 1712 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi); 1713 } 1714 1715 app.gids = gids; 1716 app.setRequiredAbi(requiredAbi); 1717 app.instructionSet = instructionSet; 1718 1719 // the per-user SELinux context must be set 1720 if (TextUtils.isEmpty(app.info.seInfoUser)) { 1721 Slog.wtf(ActivityManagerService.TAG, "SELinux tag not defined", 1722 new IllegalStateException("SELinux tag not defined for " 1723 + app.info.packageName + " (uid " + app.uid + ")")); 1724 } 1725 final String seInfo = app.info.seInfo 1726 + (TextUtils.isEmpty(app.info.seInfoUser) ? "" : app.info.seInfoUser); 1727 // Start the process. It will either succeed and return a result containing 1728 // the PID of the new process, or else throw a RuntimeException. 1729 final String entryPoint = "android.app.ActivityThread"; 1730 1731 return startProcessLocked(hostingRecord, entryPoint, app, uid, gids, 1732 runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi, 1733 instructionSet, invokeWith, startTime); 1734 } catch (RuntimeException e) { 1735 Slog.e(ActivityManagerService.TAG, "Failure starting process " + app.processName, e); 1736 1737 // Something went very wrong while trying to start this process; one 1738 // common case is when the package is frozen due to an active 1739 // upgrade. To recover, clean up any active bookkeeping related to 1740 // starting this process. (We already invoked this method once when 1741 // the package was initially frozen through KILL_APPLICATION_MSG, so 1742 // it doesn't hurt to use it again.) 1743 mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), 1744 false, false, true, false, false, app.userId, "start failure"); 1745 return false; 1746 } 1747 } 1748 1749 @GuardedBy("mService") 1750 boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app, 1751 int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal, 1752 String seInfo, String requiredAbi, String instructionSet, String invokeWith, 1753 long startTime) { 1754 app.pendingStart = true; 1755 app.killedByAm = false; 1756 app.removed = false; 1757 app.killed = false; 1758 if (app.startSeq != 0) { 1759 Slog.wtf(TAG, "startProcessLocked processName:" + app.processName 1760 + " with non-zero startSeq:" + app.startSeq); 1761 } 1762 if (app.pid != 0) { 1763 Slog.wtf(TAG, "startProcessLocked processName:" + app.processName 1764 + " with non-zero pid:" + app.pid); 1765 } 1766 app.mDisabledCompatChanges = null; 1767 if (mPlatformCompat != null) { 1768 app.mDisabledCompatChanges = mPlatformCompat.getDisabledChanges(app.info); 1769 } 1770 final long startSeq = app.startSeq = ++mProcStartSeqCounter; 1771 app.setStartParams(uid, hostingRecord, seInfo, startTime); 1772 app.setUsingWrapper(invokeWith != null 1773 || SystemProperties.get("wrap." + app.processName) != null); 1774 mPendingStarts.put(startSeq, app); 1775 1776 if (mService.mConstants.FLAG_PROCESS_START_ASYNC) { 1777 if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES, 1778 "Posting procStart msg for " + app.toShortString()); 1779 mService.mProcStartHandler.post(() -> { 1780 try { 1781 final Process.ProcessStartResult startResult = startProcess(app.hostingRecord, 1782 entryPoint, app, app.startUid, gids, runtimeFlags, zygotePolicyFlags, 1783 mountExternal, app.seInfo, requiredAbi, instructionSet, invokeWith, 1784 app.startTime); 1785 synchronized (mService) { 1786 handleProcessStartedLocked(app, startResult, startSeq); 1787 } 1788 } catch (RuntimeException e) { 1789 synchronized (mService) { 1790 Slog.e(ActivityManagerService.TAG, "Failure starting process " 1791 + app.processName, e); 1792 mPendingStarts.remove(startSeq); 1793 app.pendingStart = false; 1794 mService.forceStopPackageLocked(app.info.packageName, 1795 UserHandle.getAppId(app.uid), 1796 false, false, true, false, false, app.userId, "start failure"); 1797 } 1798 } 1799 }); 1800 return true; 1801 } else { 1802 try { 1803 final Process.ProcessStartResult startResult = startProcess(hostingRecord, 1804 entryPoint, app, 1805 uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, 1806 requiredAbi, instructionSet, invokeWith, startTime); 1807 handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper, 1808 startSeq, false); 1809 } catch (RuntimeException e) { 1810 Slog.e(ActivityManagerService.TAG, "Failure starting process " 1811 + app.processName, e); 1812 app.pendingStart = false; 1813 mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), 1814 false, false, true, false, false, app.userId, "start failure"); 1815 } 1816 return app.pid > 0; 1817 } 1818 } 1819 1820 @GuardedBy("mService") 1821 public void killAppZygoteIfNeededLocked(AppZygote appZygote) { 1822 final ApplicationInfo appInfo = appZygote.getAppInfo(); 1823 ArrayList<ProcessRecord> zygoteProcesses = mAppZygoteProcesses.get(appZygote); 1824 if (zygoteProcesses != null && zygoteProcesses.size() == 0) { 1825 // Only remove if no longer in use now 1826 mAppZygotes.remove(appInfo.processName, appInfo.uid); 1827 mAppZygoteProcesses.remove(appZygote); 1828 mAppIsolatedUidRangeAllocator.freeUidRangeLocked(appInfo); 1829 appZygote.stopZygote(); 1830 } 1831 } 1832 1833 @GuardedBy("mService") 1834 private void removeProcessFromAppZygoteLocked(final ProcessRecord app) { 1835 // Free the isolated uid for this process 1836 final IsolatedUidRange appUidRange = 1837 mAppIsolatedUidRangeAllocator.getIsolatedUidRangeLocked(app.info.processName, 1838 app.hostingRecord.getDefiningUid()); 1839 if (appUidRange != null) { 1840 appUidRange.freeIsolatedUidLocked(app.uid); 1841 } 1842 1843 final AppZygote appZygote = mAppZygotes.get(app.info.processName, 1844 app.hostingRecord.getDefiningUid()); 1845 if (appZygote != null) { 1846 ArrayList<ProcessRecord> zygoteProcesses = mAppZygoteProcesses.get(appZygote); 1847 zygoteProcesses.remove(app); 1848 if (zygoteProcesses.size() == 0) { 1849 mService.mHandler.removeMessages(KILL_APP_ZYGOTE_MSG); 1850 if (app.removed) { 1851 // If we stopped this process because the package hosting it was removed, 1852 // there's no point in delaying the app zygote kill. 1853 killAppZygoteIfNeededLocked(appZygote); 1854 } else { 1855 Message msg = mService.mHandler.obtainMessage(KILL_APP_ZYGOTE_MSG); 1856 msg.obj = appZygote; 1857 mService.mHandler.sendMessageDelayed(msg, KILL_APP_ZYGOTE_DELAY_MS); 1858 } 1859 } 1860 } 1861 } 1862 1863 private AppZygote createAppZygoteForProcessIfNeeded(final ProcessRecord app) { 1864 synchronized (mService) { 1865 // The UID for the app zygote should be the UID of the application hosting 1866 // the service. 1867 final int uid = app.hostingRecord.getDefiningUid(); 1868 AppZygote appZygote = mAppZygotes.get(app.info.processName, uid); 1869 final ArrayList<ProcessRecord> zygoteProcessList; 1870 if (appZygote == null) { 1871 if (DEBUG_PROCESSES) { 1872 Slog.d(TAG_PROCESSES, "Creating new app zygote."); 1873 } 1874 final IsolatedUidRange uidRange = 1875 mAppIsolatedUidRangeAllocator.getIsolatedUidRangeLocked( 1876 app.info.processName, app.hostingRecord.getDefiningUid()); 1877 final int userId = UserHandle.getUserId(uid); 1878 // Create the app-zygote and provide it with the UID-range it's allowed 1879 // to setresuid/setresgid to. 1880 final int firstUid = UserHandle.getUid(userId, uidRange.mFirstUid); 1881 final int lastUid = UserHandle.getUid(userId, uidRange.mLastUid); 1882 ApplicationInfo appInfo = new ApplicationInfo(app.info); 1883 // If this was an external service, the package name and uid in the passed in 1884 // ApplicationInfo have been changed to match those of the calling package; 1885 // that is not what we want for the AppZygote though, which needs to have the 1886 // packageName and uid of the defining application. This is because the 1887 // preloading only makes sense in the context of the defining application, 1888 // not the calling one. 1889 appInfo.packageName = app.hostingRecord.getDefiningPackageName(); 1890 appInfo.uid = uid; 1891 appZygote = new AppZygote(appInfo, uid, firstUid, lastUid); 1892 mAppZygotes.put(app.info.processName, uid, appZygote); 1893 zygoteProcessList = new ArrayList<ProcessRecord>(); 1894 mAppZygoteProcesses.put(appZygote, zygoteProcessList); 1895 } else { 1896 if (DEBUG_PROCESSES) { 1897 Slog.d(TAG_PROCESSES, "Reusing existing app zygote."); 1898 } 1899 mService.mHandler.removeMessages(KILL_APP_ZYGOTE_MSG, appZygote); 1900 zygoteProcessList = mAppZygoteProcesses.get(appZygote); 1901 } 1902 // Note that we already add the app to mAppZygoteProcesses here; 1903 // this is so that another thread can't come in and kill the zygote 1904 // before we've even tried to start the process. If the process launch 1905 // goes wrong, we'll clean this up in removeProcessNameLocked() 1906 zygoteProcessList.add(app); 1907 1908 return appZygote; 1909 } 1910 } 1911 1912 private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint, 1913 ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, 1914 int mountExternal, String seInfo, String requiredAbi, String instructionSet, 1915 String invokeWith, long startTime) { 1916 try { 1917 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + 1918 app.processName); 1919 checkSlow(startTime, "startProcess: asking zygote to start proc"); 1920 final boolean isTopApp = hostingRecord.isTopApp(); 1921 if (isTopApp) { 1922 // Use has-foreground-activities as a temporary hint so the current scheduling 1923 // group won't be lost when the process is attaching. The actual state will be 1924 // refreshed when computing oom-adj. 1925 app.setHasForegroundActivities(true); 1926 } 1927 1928 final Process.ProcessStartResult startResult; 1929 if (hostingRecord.usesWebviewZygote()) { 1930 startResult = startWebView(entryPoint, 1931 app.processName, uid, uid, gids, runtimeFlags, mountExternal, 1932 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 1933 app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges, 1934 new String[]{PROC_START_SEQ_IDENT + app.startSeq}); 1935 } else if (hostingRecord.usesAppZygote()) { 1936 final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app); 1937 1938 startResult = appZygote.getProcess().start(entryPoint, 1939 app.processName, uid, uid, gids, runtimeFlags, mountExternal, 1940 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 1941 app.info.dataDir, null, app.info.packageName, 1942 /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp, 1943 app.mDisabledCompatChanges, 1944 new String[]{PROC_START_SEQ_IDENT + app.startSeq}); 1945 } else { 1946 startResult = Process.start(entryPoint, 1947 app.processName, uid, uid, gids, runtimeFlags, mountExternal, 1948 app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, 1949 app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags, 1950 isTopApp, app.mDisabledCompatChanges, 1951 new String[]{PROC_START_SEQ_IDENT + app.startSeq}); 1952 } 1953 checkSlow(startTime, "startProcess: returned from zygote!"); 1954 return startResult; 1955 } finally { 1956 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 1957 } 1958 } 1959 1960 @GuardedBy("mService") 1961 void startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, int zygotePolicyFlags) { 1962 startProcessLocked(app, hostingRecord, zygotePolicyFlags, null /* abiOverride */); 1963 } 1964 1965 @GuardedBy("mService") 1966 final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, 1967 int zygotePolicyFlags, String abiOverride) { 1968 return startProcessLocked(app, hostingRecord, zygotePolicyFlags, 1969 false /* disableHiddenApiChecks */, false /* disableTestApiChecks */, 1970 false /* mountExtStorageFull */, abiOverride); 1971 } 1972 1973 @GuardedBy("mService") 1974 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, 1975 boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, 1976 int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid, 1977 boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs, 1978 Runnable crashHandler) { 1979 long startTime = SystemClock.elapsedRealtime(); 1980 ProcessRecord app; 1981 if (!isolated) { 1982 app = getProcessRecordLocked(processName, info.uid, keepIfLarge); 1983 checkSlow(startTime, "startProcess: after getProcessRecord"); 1984 1985 if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) { 1986 // If we are in the background, then check to see if this process 1987 // is bad. If so, we will just silently fail. 1988 if (mService.mAppErrors.isBadProcessLocked(info)) { 1989 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 1990 + "/" + info.processName); 1991 return null; 1992 } 1993 } else { 1994 // When the user is explicitly starting a process, then clear its 1995 // crash count so that we won't make it bad until they see at 1996 // least one crash dialog again, and make the process good again 1997 // if it had been bad. 1998 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 1999 + "/" + info.processName); 2000 mService.mAppErrors.resetProcessCrashTimeLocked(info); 2001 if (mService.mAppErrors.isBadProcessLocked(info)) { 2002 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 2003 UserHandle.getUserId(info.uid), info.uid, 2004 info.processName); 2005 mService.mAppErrors.clearBadProcessLocked(info); 2006 if (app != null) { 2007 app.bad = false; 2008 } 2009 } 2010 } 2011 } else { 2012 // If this is an isolated process, it can't re-use an existing process. 2013 app = null; 2014 } 2015 2016 // We don't have to do anything more if: 2017 // (1) There is an existing application record; and 2018 // (2) The caller doesn't think it is dead, OR there is no thread 2019 // object attached to it so we know it couldn't have crashed; and 2020 // (3) There is a pid assigned to it, so it is either starting or 2021 // already running. 2022 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName 2023 + " app=" + app + " knownToBeDead=" + knownToBeDead 2024 + " thread=" + (app != null ? app.thread : null) 2025 + " pid=" + (app != null ? app.pid : -1)); 2026 if (app != null && app.pid > 0) { 2027 if ((!knownToBeDead && !app.killed) || app.thread == null) { 2028 // We already have the app running, or are waiting for it to 2029 // come up (we have a pid but not yet its thread), so keep it. 2030 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app); 2031 // If this is a new package in the process, add the package to the list 2032 app.addPackage(info.packageName, info.longVersionCode, mService.mProcessStats); 2033 checkSlow(startTime, "startProcess: done, added package to proc"); 2034 return app; 2035 } 2036 2037 // An application record is attached to a previous process, 2038 // clean it up now. 2039 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App died: " + app); 2040 checkSlow(startTime, "startProcess: bad proc running, killing"); 2041 ProcessList.killProcessGroup(app.uid, app.pid); 2042 mService.handleAppDiedLocked(app, true, true); 2043 checkSlow(startTime, "startProcess: done killing old proc"); 2044 } 2045 2046 if (app == null) { 2047 checkSlow(startTime, "startProcess: creating new process record"); 2048 app = newProcessRecordLocked(info, processName, isolated, isolatedUid, hostingRecord); 2049 if (app == null) { 2050 Slog.w(TAG, "Failed making new process record for " 2051 + processName + "/" + info.uid + " isolated=" + isolated); 2052 return null; 2053 } 2054 app.crashHandler = crashHandler; 2055 app.isolatedEntryPoint = entryPoint; 2056 app.isolatedEntryPointArgs = entryPointArgs; 2057 checkSlow(startTime, "startProcess: done creating new process record"); 2058 } else { 2059 // If this is a new package in the process, add the package to the list 2060 app.addPackage(info.packageName, info.longVersionCode, mService.mProcessStats); 2061 checkSlow(startTime, "startProcess: added package to existing proc"); 2062 } 2063 2064 // If the system is not ready yet, then hold off on starting this 2065 // process until it is. 2066 if (!mService.mProcessesReady 2067 && !mService.isAllowedWhileBooting(info) 2068 && !allowWhileBooting) { 2069 if (!mService.mProcessesOnHold.contains(app)) { 2070 mService.mProcessesOnHold.add(app); 2071 } 2072 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, 2073 "System not ready, putting on hold: " + app); 2074 checkSlow(startTime, "startProcess: returning with proc on hold"); 2075 return app; 2076 } 2077 2078 checkSlow(startTime, "startProcess: stepping in to startProcess"); 2079 final boolean success = 2080 startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride); 2081 checkSlow(startTime, "startProcess: done starting proc!"); 2082 return success ? app : null; 2083 } 2084 2085 @GuardedBy("mService") isProcStartValidLocked(ProcessRecord app, long expectedStartSeq)2086 private String isProcStartValidLocked(ProcessRecord app, long expectedStartSeq) { 2087 StringBuilder sb = null; 2088 if (app.killedByAm) { 2089 if (sb == null) sb = new StringBuilder(); 2090 sb.append("killedByAm=true;"); 2091 } 2092 if (mProcessNames.get(app.processName, app.uid) != app) { 2093 if (sb == null) sb = new StringBuilder(); 2094 sb.append("No entry in mProcessNames;"); 2095 } 2096 if (!app.pendingStart) { 2097 if (sb == null) sb = new StringBuilder(); 2098 sb.append("pendingStart=false;"); 2099 } 2100 if (app.startSeq > expectedStartSeq) { 2101 if (sb == null) sb = new StringBuilder(); 2102 sb.append("seq=" + app.startSeq + ",expected=" + expectedStartSeq + ";"); 2103 } 2104 return sb == null ? null : sb.toString(); 2105 } 2106 2107 @GuardedBy("mService") handleProcessStartedLocked(ProcessRecord pending, Process.ProcessStartResult startResult, long expectedStartSeq)2108 private boolean handleProcessStartedLocked(ProcessRecord pending, 2109 Process.ProcessStartResult startResult, long expectedStartSeq) { 2110 // Indicates that this process start has been taken care of. 2111 if (mPendingStarts.get(expectedStartSeq) == null) { 2112 if (pending.pid == startResult.pid) { 2113 pending.setUsingWrapper(startResult.usingWrapper); 2114 // TODO: Update already existing clients of usingWrapper 2115 } 2116 return false; 2117 } 2118 return handleProcessStartedLocked(pending, startResult.pid, startResult.usingWrapper, 2119 expectedStartSeq, false); 2120 } 2121 2122 @GuardedBy("mService") handleProcessStartedLocked(ProcessRecord app, int pid, boolean usingWrapper, long expectedStartSeq, boolean procAttached)2123 boolean handleProcessStartedLocked(ProcessRecord app, int pid, boolean usingWrapper, 2124 long expectedStartSeq, boolean procAttached) { 2125 mPendingStarts.remove(expectedStartSeq); 2126 final String reason = isProcStartValidLocked(app, expectedStartSeq); 2127 if (reason != null) { 2128 Slog.w(TAG_PROCESSES, app + " start not valid, killing pid=" + 2129 pid 2130 + ", " + reason); 2131 app.pendingStart = false; 2132 killProcessQuiet(pid); 2133 Process.killProcessGroup(app.uid, app.pid); 2134 return false; 2135 } 2136 mService.mBatteryStatsService.noteProcessStart(app.processName, app.info.uid); 2137 checkSlow(app.startTime, "startProcess: done updating battery stats"); 2138 2139 EventLog.writeEvent(EventLogTags.AM_PROC_START, 2140 UserHandle.getUserId(app.startUid), pid, app.startUid, 2141 app.processName, app.hostingRecord.getType(), 2142 app.hostingRecord.getName() != null ? app.hostingRecord.getName() : ""); 2143 2144 try { 2145 AppGlobals.getPackageManager().logAppProcessStartIfNeeded(app.processName, app.uid, 2146 app.seInfo, app.info.sourceDir, pid); 2147 } catch (RemoteException ex) { 2148 // Ignore 2149 } 2150 2151 if (app.isPersistent()) { 2152 Watchdog.getInstance().processStarted(app.processName, pid); 2153 } 2154 2155 checkSlow(app.startTime, "startProcess: building log message"); 2156 StringBuilder buf = mStringBuilder; 2157 buf.setLength(0); 2158 buf.append("Start proc "); 2159 buf.append(pid); 2160 buf.append(':'); 2161 buf.append(app.processName); 2162 buf.append('/'); 2163 UserHandle.formatUid(buf, app.startUid); 2164 if (app.isolatedEntryPoint != null) { 2165 buf.append(" ["); 2166 buf.append(app.isolatedEntryPoint); 2167 buf.append("]"); 2168 } 2169 buf.append(" for "); 2170 buf.append(app.hostingRecord.getType()); 2171 if (app.hostingRecord.getName() != null) { 2172 buf.append(" "); 2173 buf.append(app.hostingRecord.getName()); 2174 } 2175 mService.reportUidInfoMessageLocked(TAG, buf.toString(), app.startUid); 2176 app.setPid(pid); 2177 app.setUsingWrapper(usingWrapper); 2178 app.pendingStart = false; 2179 checkSlow(app.startTime, "startProcess: starting to update pids map"); 2180 ProcessRecord oldApp; 2181 synchronized (mService.mPidsSelfLocked) { 2182 oldApp = mService.mPidsSelfLocked.get(pid); 2183 } 2184 // If there is already an app occupying that pid that hasn't been cleaned up 2185 if (oldApp != null && !app.isolated) { 2186 // Clean up anything relating to this pid first 2187 Slog.wtf(TAG, "handleProcessStartedLocked process:" + app.processName 2188 + " startSeq:" + app.startSeq 2189 + " pid:" + pid 2190 + " belongs to another existing app:" + oldApp.processName 2191 + " startSeq:" + oldApp.startSeq); 2192 mService.cleanUpApplicationRecordLocked(oldApp, false, false, -1, 2193 true /*replacingPid*/); 2194 } 2195 mService.mPidsSelfLocked.put(app); 2196 synchronized (mService.mPidsSelfLocked) { 2197 if (!procAttached) { 2198 Message msg = mService.mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 2199 msg.obj = app; 2200 mService.mHandler.sendMessageDelayed(msg, usingWrapper 2201 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 2202 } 2203 } 2204 checkSlow(app.startTime, "startProcess: done updating pids map"); 2205 return true; 2206 } 2207 removeLruProcessLocked(ProcessRecord app)2208 final void removeLruProcessLocked(ProcessRecord app) { 2209 int lrui = mLruProcesses.lastIndexOf(app); 2210 if (lrui >= 0) { 2211 if (!app.killed) { 2212 if (app.isPersistent()) { 2213 Slog.w(TAG, "Removing persistent process that hasn't been killed: " + app); 2214 } else { 2215 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app); 2216 if (app.pid > 0) { 2217 killProcessQuiet(app.pid); 2218 ProcessList.killProcessGroup(app.uid, app.pid); 2219 } else { 2220 app.pendingStart = false; 2221 } 2222 } 2223 } 2224 if (lrui < mLruProcessActivityStart) { 2225 mLruProcessActivityStart--; 2226 } 2227 if (lrui < mLruProcessServiceStart) { 2228 mLruProcessServiceStart--; 2229 } 2230 mLruProcesses.remove(lrui); 2231 } 2232 } 2233 2234 @GuardedBy("mService") killPackageProcessesLocked(String packageName, int appId, int userId, int minOomAdj, String reason)2235 boolean killPackageProcessesLocked(String packageName, int appId, int userId, int minOomAdj, 2236 String reason) { 2237 return killPackageProcessesLocked(packageName, appId, userId, minOomAdj, 2238 false /* callerWillRestart */, true /* allowRestart */, true /* doit */, 2239 false /* evenPersistent */, false /* setRemoved */, reason); 2240 } 2241 2242 @GuardedBy("mService") killPackageProcessesLocked(String packageName, int appId, int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit, boolean evenPersistent, boolean setRemoved, String reason)2243 final boolean killPackageProcessesLocked(String packageName, int appId, 2244 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 2245 boolean doit, boolean evenPersistent, boolean setRemoved, String reason) { 2246 ArrayList<ProcessRecord> procs = new ArrayList<>(); 2247 2248 // Remove all processes this package may have touched: all with the 2249 // same UID (except for the system or root user), and all whose name 2250 // matches the package name. 2251 final int NP = mProcessNames.getMap().size(); 2252 for (int ip = 0; ip < NP; ip++) { 2253 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 2254 final int NA = apps.size(); 2255 for (int ia = 0; ia < NA; ia++) { 2256 ProcessRecord app = apps.valueAt(ia); 2257 if (app.isPersistent() && !evenPersistent) { 2258 // we don't kill persistent processes 2259 continue; 2260 } 2261 if (app.removed) { 2262 if (doit) { 2263 procs.add(app); 2264 } 2265 continue; 2266 } 2267 2268 // Skip process if it doesn't meet our oom adj requirement. 2269 if (app.setAdj < minOomAdj) { 2270 // Note it is still possible to have a process with oom adj 0 in the killed 2271 // processes, but it does not mean misjudgment. E.g. a bound service process 2272 // and its client activity process are both in the background, so they are 2273 // collected to be killed. If the client activity is killed first, the service 2274 // may be scheduled to unbind and become an executing service (oom adj 0). 2275 continue; 2276 } 2277 2278 // If no package is specified, we call all processes under the 2279 // give user id. 2280 if (packageName == null) { 2281 if (userId != UserHandle.USER_ALL && app.userId != userId) { 2282 continue; 2283 } 2284 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 2285 continue; 2286 } 2287 // Package has been specified, we want to hit all processes 2288 // that match it. We need to qualify this by the processes 2289 // that are running under the specified app and user ID. 2290 } else { 2291 final boolean isDep = app.pkgDeps != null 2292 && app.pkgDeps.contains(packageName); 2293 if (!isDep && UserHandle.getAppId(app.uid) != appId) { 2294 continue; 2295 } 2296 if (userId != UserHandle.USER_ALL && app.userId != userId) { 2297 continue; 2298 } 2299 if (!app.pkgList.containsKey(packageName) && !isDep) { 2300 continue; 2301 } 2302 } 2303 2304 // Process has passed all conditions, kill it! 2305 if (!doit) { 2306 return true; 2307 } 2308 if (setRemoved) { 2309 app.removed = true; 2310 } 2311 procs.add(app); 2312 } 2313 } 2314 2315 int N = procs.size(); 2316 for (int i=0; i<N; i++) { 2317 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 2318 } 2319 // See if there are any app zygotes running for this packageName / UID combination, 2320 // and kill it if so. 2321 final ArrayList<AppZygote> zygotesToKill = new ArrayList<>(); 2322 for (SparseArray<AppZygote> appZygotes : mAppZygotes.getMap().values()) { 2323 for (int i = 0; i < appZygotes.size(); ++i) { 2324 final int appZygoteUid = appZygotes.keyAt(i); 2325 if (userId != UserHandle.USER_ALL && UserHandle.getUserId(appZygoteUid) != userId) { 2326 continue; 2327 } 2328 if (appId >= 0 && UserHandle.getAppId(appZygoteUid) != appId) { 2329 continue; 2330 } 2331 final AppZygote appZygote = appZygotes.valueAt(i); 2332 if (packageName != null 2333 && !packageName.equals(appZygote.getAppInfo().packageName)) { 2334 continue; 2335 } 2336 zygotesToKill.add(appZygote); 2337 } 2338 } 2339 for (AppZygote appZygote : zygotesToKill) { 2340 killAppZygoteIfNeededLocked(appZygote); 2341 } 2342 mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_PROCESS_END); 2343 return N > 0; 2344 } 2345 2346 @GuardedBy("mService") removeProcessLocked(ProcessRecord app, boolean callerWillRestart, boolean allowRestart, String reason)2347 boolean removeProcessLocked(ProcessRecord app, 2348 boolean callerWillRestart, boolean allowRestart, String reason) { 2349 final String name = app.processName; 2350 final int uid = app.uid; 2351 if (DEBUG_PROCESSES) Slog.d(TAG_PROCESSES, 2352 "Force removing proc " + app.toShortString() + " (" + name + "/" + uid + ")"); 2353 2354 ProcessRecord old = mProcessNames.get(name, uid); 2355 if (old != app) { 2356 // This process is no longer active, so nothing to do. 2357 Slog.w(TAG, "Ignoring remove of inactive process: " + app); 2358 return false; 2359 } 2360 removeProcessNameLocked(name, uid); 2361 mService.mAtmInternal.clearHeavyWeightProcessIfEquals(app.getWindowProcessController()); 2362 2363 boolean needRestart = false; 2364 if ((app.pid > 0 && app.pid != ActivityManagerService.MY_PID) || (app.pid == 0 && app 2365 .pendingStart)) { 2366 int pid = app.pid; 2367 if (pid > 0) { 2368 mService.mPidsSelfLocked.remove(app); 2369 mService.mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 2370 mService.mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 2371 if (app.isolated) { 2372 mService.mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 2373 mService.getPackageManagerInternalLocked().removeIsolatedUid(app.uid); 2374 } 2375 } 2376 boolean willRestart = false; 2377 if (app.isPersistent() && !app.isolated) { 2378 if (!callerWillRestart) { 2379 willRestart = true; 2380 } else { 2381 needRestart = true; 2382 } 2383 } 2384 app.kill(reason, true); 2385 mService.handleAppDiedLocked(app, willRestart, allowRestart); 2386 if (willRestart) { 2387 removeLruProcessLocked(app); 2388 mService.addAppLocked(app.info, null, false, null /* ABI override */, 2389 ZYGOTE_POLICY_FLAG_EMPTY); 2390 } 2391 } else { 2392 mRemovedProcesses.add(app); 2393 } 2394 2395 return needRestart; 2396 } 2397 2398 @GuardedBy("mService") addProcessNameLocked(ProcessRecord proc)2399 final void addProcessNameLocked(ProcessRecord proc) { 2400 // We shouldn't already have a process under this name, but just in case we 2401 // need to clean up whatever may be there now. 2402 ProcessRecord old = removeProcessNameLocked(proc.processName, proc.uid); 2403 if (old == proc && proc.isPersistent()) { 2404 // We are re-adding a persistent process. Whatevs! Just leave it there. 2405 Slog.w(TAG, "Re-adding persistent process " + proc); 2406 } else if (old != null) { 2407 Slog.wtf(TAG, "Already have existing proc " + old + " when adding " + proc); 2408 } 2409 UidRecord uidRec = mActiveUids.get(proc.uid); 2410 if (uidRec == null) { 2411 uidRec = new UidRecord(proc.uid); 2412 // This is the first appearance of the uid, report it now! 2413 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 2414 "Creating new process uid: " + uidRec); 2415 if (Arrays.binarySearch(mService.mDeviceIdleTempWhitelist, 2416 UserHandle.getAppId(proc.uid)) >= 0 2417 || mService.mPendingTempWhitelist.indexOfKey(proc.uid) >= 0) { 2418 uidRec.setWhitelist = uidRec.curWhitelist = true; 2419 } 2420 uidRec.updateHasInternetPermission(); 2421 mActiveUids.put(proc.uid, uidRec); 2422 EventLogTags.writeAmUidRunning(uidRec.uid); 2423 mService.noteUidProcessState(uidRec.uid, uidRec.getCurProcState()); 2424 } 2425 proc.uidRecord = uidRec; 2426 2427 // Reset render thread tid if it was already set, so new process can set it again. 2428 proc.renderThreadTid = 0; 2429 uidRec.numProcs++; 2430 mProcessNames.put(proc.processName, proc.uid, proc); 2431 if (proc.isolated) { 2432 mIsolatedProcesses.put(proc.uid, proc); 2433 } 2434 } 2435 2436 @GuardedBy("mService") getOrCreateIsolatedUidRangeLocked(ApplicationInfo info, HostingRecord hostingRecord)2437 private IsolatedUidRange getOrCreateIsolatedUidRangeLocked(ApplicationInfo info, 2438 HostingRecord hostingRecord) { 2439 if (hostingRecord == null || !hostingRecord.usesAppZygote()) { 2440 // Allocate an isolated UID from the global range 2441 return mGlobalIsolatedUids; 2442 } else { 2443 return mAppIsolatedUidRangeAllocator.getOrCreateIsolatedUidRangeLocked( 2444 info.processName, hostingRecord.getDefiningUid()); 2445 } 2446 } 2447 2448 @GuardedBy("mService") newProcessRecordLocked(ApplicationInfo info, String customProcess, boolean isolated, int isolatedUid, HostingRecord hostingRecord)2449 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess, 2450 boolean isolated, int isolatedUid, HostingRecord hostingRecord) { 2451 String proc = customProcess != null ? customProcess : info.processName; 2452 final int userId = UserHandle.getUserId(info.uid); 2453 int uid = info.uid; 2454 if (isolated) { 2455 if (isolatedUid == 0) { 2456 IsolatedUidRange uidRange = getOrCreateIsolatedUidRangeLocked(info, hostingRecord); 2457 if (uidRange == null) { 2458 return null; 2459 } 2460 uid = uidRange.allocateIsolatedUidLocked(userId); 2461 if (uid == -1) { 2462 return null; 2463 } 2464 } else { 2465 // Special case for startIsolatedProcess (internal only), where 2466 // the uid of the isolated process is specified by the caller. 2467 uid = isolatedUid; 2468 } 2469 mService.getPackageManagerInternalLocked().addIsolatedUid(uid, info.uid); 2470 2471 // Register the isolated UID with this application so BatteryStats knows to 2472 // attribute resource usage to the application. 2473 // 2474 // NOTE: This is done here before addProcessNameLocked, which will tell BatteryStats 2475 // about the process state of the isolated UID *before* it is registered with the 2476 // owning application. 2477 mService.mBatteryStatsService.addIsolatedUid(uid, info.uid); 2478 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, info.uid, uid, 2479 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED); 2480 } 2481 final ProcessRecord r = new ProcessRecord(mService, info, proc, uid); 2482 2483 if (!mService.mBooted && !mService.mBooting 2484 && userId == UserHandle.USER_SYSTEM 2485 && (info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 2486 // The system process is initialized to SCHED_GROUP_DEFAULT in init.rc. 2487 r.setCurrentSchedulingGroup(ProcessList.SCHED_GROUP_DEFAULT); 2488 r.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT; 2489 r.setPersistent(true); 2490 r.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 2491 } 2492 if (isolated && isolatedUid != 0) { 2493 // Special case for startIsolatedProcess (internal only) - assume the process 2494 // is required by the system server to prevent it being killed. 2495 r.maxAdj = ProcessList.PERSISTENT_SERVICE_ADJ; 2496 } 2497 addProcessNameLocked(r); 2498 return r; 2499 } 2500 2501 @GuardedBy("mService") removeProcessNameLocked(final String name, final int uid)2502 final ProcessRecord removeProcessNameLocked(final String name, final int uid) { 2503 return removeProcessNameLocked(name, uid, null); 2504 } 2505 2506 @GuardedBy("mService") removeProcessNameLocked(final String name, final int uid, final ProcessRecord expecting)2507 final ProcessRecord removeProcessNameLocked(final String name, final int uid, 2508 final ProcessRecord expecting) { 2509 ProcessRecord old = mProcessNames.get(name, uid); 2510 // Only actually remove when the currently recorded value matches the 2511 // record that we expected; if it doesn't match then we raced with a 2512 // newly created process and we don't want to destroy the new one. 2513 if ((expecting == null) || (old == expecting)) { 2514 mProcessNames.remove(name, uid); 2515 } 2516 if (old != null && old.uidRecord != null) { 2517 old.uidRecord.numProcs--; 2518 if (old.uidRecord.numProcs == 0) { 2519 // No more processes using this uid, tell clients it is gone. 2520 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 2521 "No more processes in " + old.uidRecord); 2522 mService.enqueueUidChangeLocked(old.uidRecord, -1, UidRecord.CHANGE_GONE); 2523 EventLogTags.writeAmUidStopped(uid); 2524 mActiveUids.remove(uid); 2525 mService.noteUidProcessState(uid, ActivityManager.PROCESS_STATE_NONEXISTENT); 2526 } 2527 old.uidRecord = null; 2528 } 2529 mIsolatedProcesses.remove(uid); 2530 mGlobalIsolatedUids.freeIsolatedUidLocked(uid); 2531 // Remove the (expected) ProcessRecord from the app zygote 2532 final ProcessRecord record = expecting != null ? expecting : old; 2533 if (record != null && record.appZygote) { 2534 removeProcessFromAppZygoteLocked(record); 2535 } 2536 2537 return old; 2538 } 2539 2540 /** Call setCoreSettings on all LRU processes, with the new settings. */ 2541 @GuardedBy("mService") updateCoreSettingsLocked(Bundle settings)2542 void updateCoreSettingsLocked(Bundle settings) { 2543 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 2544 ProcessRecord processRecord = mLruProcesses.get(i); 2545 try { 2546 if (processRecord.thread != null) { 2547 processRecord.thread.setCoreSettings(settings); 2548 } 2549 } catch (RemoteException re) { 2550 /* ignore */ 2551 } 2552 } 2553 } 2554 2555 /** 2556 * Kill all background processes except for ones with targetSdk lower than minTargetSdk and 2557 * procstate lower than maxProcState. 2558 * @param minTargetSdk 2559 * @param maxProcState 2560 */ 2561 @GuardedBy("mService") killAllBackgroundProcessesExceptLocked(int minTargetSdk, int maxProcState)2562 void killAllBackgroundProcessesExceptLocked(int minTargetSdk, int maxProcState) { 2563 final ArrayList<ProcessRecord> procs = new ArrayList<>(); 2564 final int NP = mProcessNames.getMap().size(); 2565 for (int ip = 0; ip < NP; ip++) { 2566 final SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 2567 final int NA = apps.size(); 2568 for (int ia = 0; ia < NA; ia++) { 2569 final ProcessRecord app = apps.valueAt(ia); 2570 if (app.removed || ((minTargetSdk < 0 || app.info.targetSdkVersion < minTargetSdk) 2571 && (maxProcState < 0 || app.setProcState > maxProcState))) { 2572 procs.add(app); 2573 } 2574 } 2575 } 2576 2577 final int N = procs.size(); 2578 for (int i = 0; i < N; i++) { 2579 removeProcessLocked(procs.get(i), false, true, "kill all background except"); 2580 } 2581 } 2582 2583 /** 2584 * Call updateTimePrefs on all LRU processes 2585 * @param timePref The time pref to pass to each process 2586 */ 2587 @GuardedBy("mService") updateAllTimePrefsLocked(int timePref)2588 void updateAllTimePrefsLocked(int timePref) { 2589 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 2590 ProcessRecord r = mLruProcesses.get(i); 2591 if (r.thread != null) { 2592 try { 2593 r.thread.updateTimePrefs(timePref); 2594 } catch (RemoteException ex) { 2595 Slog.w(TAG, "Failed to update preferences for: " 2596 + r.info.processName); 2597 } 2598 } 2599 } 2600 } 2601 setAllHttpProxy()2602 void setAllHttpProxy() { 2603 // Update the HTTP proxy for each application thread. 2604 synchronized (mService) { 2605 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 2606 ProcessRecord r = mLruProcesses.get(i); 2607 // Don't dispatch to isolated processes as they can't access ConnectivityManager and 2608 // don't have network privileges anyway. Exclude system server and update it 2609 // separately outside the AMS lock, to avoid deadlock with Connectivity Service. 2610 if (r.pid != ActivityManagerService.MY_PID && r.thread != null && !r.isolated) { 2611 try { 2612 r.thread.updateHttpProxy(); 2613 } catch (RemoteException ex) { 2614 Slog.w(TAG, "Failed to update http proxy for: " 2615 + r.info.processName); 2616 } 2617 } 2618 } 2619 } 2620 ActivityThread.updateHttpProxy(mService.mContext); 2621 } 2622 2623 @GuardedBy("mService") clearAllDnsCacheLocked()2624 void clearAllDnsCacheLocked() { 2625 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 2626 ProcessRecord r = mLruProcesses.get(i); 2627 if (r.thread != null) { 2628 try { 2629 r.thread.clearDnsCache(); 2630 } catch (RemoteException ex) { 2631 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 2632 } 2633 } 2634 } 2635 } 2636 2637 @GuardedBy("mService") handleAllTrustStorageUpdateLocked()2638 void handleAllTrustStorageUpdateLocked() { 2639 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 2640 ProcessRecord r = mLruProcesses.get(i); 2641 if (r.thread != null) { 2642 try { 2643 r.thread.handleTrustStorageUpdate(); 2644 } catch (RemoteException ex) { 2645 Slog.w(TAG, "Failed to handle trust storage update for: " + 2646 r.info.processName); 2647 } 2648 } 2649 } 2650 } 2651 2652 @GuardedBy("mService") updateLruProcessInternalLocked(ProcessRecord app, long now, int index, int lruSeq, String what, Object obj, ProcessRecord srcApp)2653 int updateLruProcessInternalLocked(ProcessRecord app, long now, int index, 2654 int lruSeq, String what, Object obj, ProcessRecord srcApp) { 2655 app.lastActivityTime = now; 2656 2657 if (app.hasActivitiesOrRecentTasks()) { 2658 // Don't want to touch dependent processes that are hosting activities. 2659 return index; 2660 } 2661 2662 int lrui = mLruProcesses.lastIndexOf(app); 2663 if (lrui < 0) { 2664 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: " 2665 + what + " " + obj + " from " + srcApp); 2666 return index; 2667 } 2668 2669 if (lrui >= index) { 2670 // Don't want to cause this to move dependent processes *back* in the 2671 // list as if they were less frequently used. 2672 return index; 2673 } 2674 2675 if (lrui >= mLruProcessActivityStart && index < mLruProcessActivityStart) { 2676 // Don't want to touch dependent processes that are hosting activities. 2677 return index; 2678 } 2679 2680 mLruProcesses.remove(lrui); 2681 if (index > 0) { 2682 index--; 2683 } 2684 if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index 2685 + " in LRU list: " + app); 2686 mLruProcesses.add(index, app); 2687 app.lruSeq = lruSeq; 2688 return index; 2689 } 2690 2691 /** 2692 * Handle the case where we are inserting a process hosting client activities: 2693 * Make sure any groups have their order match their importance, and take care of 2694 * distributing old clients across other activity processes so they can't spam 2695 * the LRU list. Processing of the list will be restricted by the indices provided, 2696 * and not extend out of them. 2697 * 2698 * @param topApp The app at the top that has just been inserted in to the list. 2699 * @param topI The position in the list where topApp was inserted; this is the start (at the 2700 * top) where we are going to do our processing. 2701 * @param bottomI The last position at which we will be processing; this is the end position 2702 * of whichever section of the LRU list we are in. Nothing past it will be 2703 * touched. 2704 * @param endIndex The current end of the top being processed. Typically topI - 1. That is, 2705 * where we are going to start potentially adjusting other entries in the list. 2706 */ updateClientActivitiesOrdering(final ProcessRecord topApp, final int topI, final int bottomI, int endIndex)2707 private void updateClientActivitiesOrdering(final ProcessRecord topApp, final int topI, 2708 final int bottomI, int endIndex) { 2709 if (topApp.hasActivitiesOrRecentTasks() || topApp.treatLikeActivity 2710 || !topApp.hasClientActivities()) { 2711 // If this is not a special process that has client activities, then there is 2712 // nothing to do. 2713 return; 2714 } 2715 2716 final int uid = topApp.info.uid; 2717 if (topApp.connectionGroup > 0) { 2718 int endImportance = topApp.connectionImportance; 2719 for (int i = endIndex; i >= bottomI; i--) { 2720 final ProcessRecord subProc = mLruProcesses.get(i); 2721 if (subProc.info.uid == uid 2722 && subProc.connectionGroup == topApp.connectionGroup) { 2723 if (i == endIndex && subProc.connectionImportance >= endImportance) { 2724 // This process is already in the group, and its importance 2725 // is not as strong as the process before it, so keep it 2726 // correctly positioned in the group. 2727 if (DEBUG_LRU) Slog.d(TAG_LRU, 2728 "Keeping in-place above " + subProc 2729 + " endImportance=" + endImportance 2730 + " group=" + subProc.connectionGroup 2731 + " importance=" + subProc.connectionImportance); 2732 endIndex--; 2733 endImportance = subProc.connectionImportance; 2734 } else { 2735 // We want to pull this up to be with the rest of the group, 2736 // and order within the group by importance. 2737 if (DEBUG_LRU) Slog.d(TAG_LRU, 2738 "Pulling up " + subProc 2739 + " to position in group with importance=" 2740 + subProc.connectionImportance); 2741 boolean moved = false; 2742 for (int pos = topI; pos > endIndex; pos--) { 2743 final ProcessRecord posProc = mLruProcesses.get(pos); 2744 if (subProc.connectionImportance 2745 <= posProc.connectionImportance) { 2746 mLruProcesses.remove(i); 2747 mLruProcesses.add(pos, subProc); 2748 if (DEBUG_LRU) Slog.d(TAG_LRU, 2749 "Moving " + subProc 2750 + " from position " + i + " to above " + posProc 2751 + " @ " + pos); 2752 moved = true; 2753 endIndex--; 2754 break; 2755 } 2756 } 2757 if (!moved) { 2758 // Goes to the end of the group. 2759 mLruProcesses.remove(i); 2760 mLruProcesses.add(endIndex, subProc); 2761 if (DEBUG_LRU) Slog.d(TAG_LRU, 2762 "Moving " + subProc 2763 + " from position " + i + " to end of group @ " 2764 + endIndex); 2765 endIndex--; 2766 endImportance = subProc.connectionImportance; 2767 } 2768 } 2769 } 2770 } 2771 2772 } 2773 // To keep it from spamming the LRU list (by making a bunch of clients), 2774 // we will distribute other entries owned by it to be in-between other apps. 2775 int i = endIndex; 2776 while (i >= bottomI) { 2777 ProcessRecord subProc = mLruProcesses.get(i); 2778 if (DEBUG_LRU) Slog.d(TAG_LRU, 2779 "Looking to spread old procs, at " + subProc + " @ " + i); 2780 if (subProc.info.uid != uid) { 2781 // This is a different app... if we have gone through some of the 2782 // target app, pull this up to be before them. We want to pull up 2783 // one activity process, but any number of non-activity processes. 2784 if (i < endIndex) { 2785 boolean hasActivity = false; 2786 int connUid = 0; 2787 int connGroup = 0; 2788 while (i >= bottomI) { 2789 mLruProcesses.remove(i); 2790 mLruProcesses.add(endIndex, subProc); 2791 if (DEBUG_LRU) Slog.d(TAG_LRU, 2792 "Different app, moving to " + endIndex); 2793 i--; 2794 if (i < bottomI) { 2795 break; 2796 } 2797 subProc = mLruProcesses.get(i); 2798 if (DEBUG_LRU) Slog.d(TAG_LRU, 2799 "Looking at next app at " + i + ": " + subProc); 2800 if (subProc.hasActivitiesOrRecentTasks() || subProc.treatLikeActivity) { 2801 if (DEBUG_LRU) Slog.d(TAG_LRU, 2802 "This is hosting an activity!"); 2803 if (hasActivity) { 2804 // Already found an activity, done. 2805 if (DEBUG_LRU) Slog.d(TAG_LRU, 2806 "Already found an activity, done"); 2807 break; 2808 } 2809 hasActivity = true; 2810 } else if (subProc.hasClientActivities()) { 2811 if (DEBUG_LRU) Slog.d(TAG_LRU, 2812 "This is a client of an activity"); 2813 if (hasActivity) { 2814 if (connUid == 0 || connUid != subProc.info.uid) { 2815 // Already have an activity that is not from from a client 2816 // connection or is a different client connection, done. 2817 if (DEBUG_LRU) Slog.d(TAG_LRU, 2818 "Already found a different activity: connUid=" 2819 + connUid + " uid=" + subProc.info.uid); 2820 break; 2821 } else if (connGroup == 0 || connGroup != subProc.connectionGroup) { 2822 // Previously saw a different group or not from a group, 2823 // want to treat these as different things. 2824 if (DEBUG_LRU) Slog.d(TAG_LRU, 2825 "Already found a different group: connGroup=" 2826 + connGroup + " group=" + subProc.connectionGroup); 2827 break; 2828 } 2829 } else { 2830 if (DEBUG_LRU) Slog.d(TAG_LRU, 2831 "This is an activity client! uid=" 2832 + subProc.info.uid + " group=" + subProc.connectionGroup); 2833 hasActivity = true; 2834 connUid = subProc.info.uid; 2835 connGroup = subProc.connectionGroup; 2836 } 2837 } 2838 endIndex--; 2839 } 2840 } 2841 // Find the end of the next group of processes for target app. This 2842 // is after any entries of different apps (so we don't change the existing 2843 // relative order of apps) and then after the next last group of processes 2844 // of the target app. 2845 for (endIndex--; endIndex >= bottomI; endIndex--) { 2846 final ProcessRecord endProc = mLruProcesses.get(endIndex); 2847 if (endProc.info.uid == uid) { 2848 if (DEBUG_LRU) Slog.d(TAG_LRU, 2849 "Found next group of app: " + endProc + " @ " 2850 + endIndex); 2851 break; 2852 } 2853 } 2854 if (endIndex >= bottomI) { 2855 final ProcessRecord endProc = mLruProcesses.get(endIndex); 2856 for (endIndex--; endIndex >= bottomI; endIndex--) { 2857 final ProcessRecord nextEndProc = mLruProcesses.get(endIndex); 2858 if (nextEndProc.info.uid != uid 2859 || nextEndProc.connectionGroup != endProc.connectionGroup) { 2860 if (DEBUG_LRU) Slog.d(TAG_LRU, 2861 "Found next group or app: " + nextEndProc + " @ " 2862 + endIndex + " group=" + nextEndProc.connectionGroup); 2863 break; 2864 } 2865 } 2866 } 2867 if (DEBUG_LRU) Slog.d(TAG_LRU, 2868 "Bumping scan position to " + endIndex); 2869 i = endIndex; 2870 } else { 2871 i--; 2872 } 2873 } 2874 } 2875 updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2876 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2877 ProcessRecord client) { 2878 final boolean hasActivity = app.hasActivitiesOrRecentTasks() || app.hasClientActivities() 2879 || app.treatLikeActivity; 2880 final boolean hasService = false; // not impl yet. app.services.size() > 0; 2881 if (!activityChange && hasActivity) { 2882 // The process has activities, so we are only allowing activity-based adjustments 2883 // to move it. It should be kept in the front of the list with other 2884 // processes that have activities, and we don't want those to change their 2885 // order except due to activity operations. 2886 return; 2887 } 2888 2889 mLruSeq++; 2890 final long now = SystemClock.uptimeMillis(); 2891 app.lastActivityTime = now; 2892 2893 // First a quick reject: if the app is already at the position we will 2894 // put it, then there is nothing to do. 2895 if (hasActivity) { 2896 final int N = mLruProcesses.size(); 2897 if (N > 0 && mLruProcesses.get(N - 1) == app) { 2898 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app); 2899 return; 2900 } 2901 } else { 2902 if (mLruProcessServiceStart > 0 2903 && mLruProcesses.get(mLruProcessServiceStart-1) == app) { 2904 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app); 2905 return; 2906 } 2907 } 2908 2909 int lrui = mLruProcesses.lastIndexOf(app); 2910 2911 if (app.isPersistent() && lrui >= 0) { 2912 // We don't care about the position of persistent processes, as long as 2913 // they are in the list. 2914 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app); 2915 return; 2916 } 2917 2918 /* In progress: compute new position first, so we can avoid doing work 2919 if the process is not actually going to move. Not yet working. 2920 int addIndex; 2921 int nextIndex; 2922 boolean inActivity = false, inService = false; 2923 if (hasActivity) { 2924 // Process has activities, put it at the very tipsy-top. 2925 addIndex = mLruProcesses.size(); 2926 nextIndex = mLruProcessServiceStart; 2927 inActivity = true; 2928 } else if (hasService) { 2929 // Process has services, put it at the top of the service list. 2930 addIndex = mLruProcessActivityStart; 2931 nextIndex = mLruProcessServiceStart; 2932 inActivity = true; 2933 inService = true; 2934 } else { 2935 // Process not otherwise of interest, it goes to the top of the non-service area. 2936 addIndex = mLruProcessServiceStart; 2937 if (client != null) { 2938 int clientIndex = mLruProcesses.lastIndexOf(client); 2939 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating " 2940 + app); 2941 if (clientIndex >= 0 && addIndex > clientIndex) { 2942 addIndex = clientIndex; 2943 } 2944 } 2945 nextIndex = addIndex > 0 ? addIndex-1 : addIndex; 2946 } 2947 2948 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act=" 2949 + mLruProcessActivityStart + "): " + app); 2950 */ 2951 2952 if (lrui >= 0) { 2953 if (lrui < mLruProcessActivityStart) { 2954 mLruProcessActivityStart--; 2955 } 2956 if (lrui < mLruProcessServiceStart) { 2957 mLruProcessServiceStart--; 2958 } 2959 /* 2960 if (addIndex > lrui) { 2961 addIndex--; 2962 } 2963 if (nextIndex > lrui) { 2964 nextIndex--; 2965 } 2966 */ 2967 mLruProcesses.remove(lrui); 2968 } 2969 2970 /* 2971 mLruProcesses.add(addIndex, app); 2972 if (inActivity) { 2973 mLruProcessActivityStart++; 2974 } 2975 if (inService) { 2976 mLruProcessActivityStart++; 2977 } 2978 */ 2979 2980 int nextIndex; 2981 int nextActivityIndex = -1; 2982 if (hasActivity) { 2983 final int N = mLruProcesses.size(); 2984 nextIndex = mLruProcessServiceStart; 2985 if (!app.hasActivitiesOrRecentTasks() && !app.treatLikeActivity 2986 && mLruProcessActivityStart < (N - 1)) { 2987 // Process doesn't have activities, but has clients with 2988 // activities... move it up, but below the app that is binding to it. 2989 if (DEBUG_LRU) Slog.d(TAG_LRU, 2990 "Adding to second-top of LRU activity list: " + app 2991 + " group=" + app.connectionGroup 2992 + " importance=" + app.connectionImportance); 2993 int pos = N - 1; 2994 while (pos > mLruProcessActivityStart) { 2995 final ProcessRecord posproc = mLruProcesses.get(pos); 2996 if (posproc.info.uid == app.info.uid) { 2997 // Technically this app could have multiple processes with different 2998 // activities and so we should be looking for the actual process that 2999 // is bound to the target proc... but I don't really care, do you? 3000 break; 3001 } 3002 pos--; 3003 } 3004 mLruProcesses.add(pos, app); 3005 // If this process is part of a group, need to pull up any other processes 3006 // in that group to be with it. 3007 int endIndex = pos - 1; 3008 if (endIndex < mLruProcessActivityStart) { 3009 endIndex = mLruProcessActivityStart; 3010 } 3011 nextActivityIndex = endIndex; 3012 updateClientActivitiesOrdering(app, pos, mLruProcessActivityStart, endIndex); 3013 } else { 3014 // Process has activities, put it at the very tipsy-top. 3015 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app); 3016 mLruProcesses.add(app); 3017 nextActivityIndex = mLruProcesses.size() - 1; 3018 } 3019 } else if (hasService) { 3020 // Process has services, put it at the top of the service list. 3021 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app); 3022 mLruProcesses.add(mLruProcessActivityStart, app); 3023 nextIndex = mLruProcessServiceStart; 3024 mLruProcessActivityStart++; 3025 } else { 3026 // Process not otherwise of interest, it goes to the top of the non-service area. 3027 int index = mLruProcessServiceStart; 3028 if (client != null) { 3029 // If there is a client, don't allow the process to be moved up higher 3030 // in the list than that client. 3031 int clientIndex = mLruProcesses.lastIndexOf(client); 3032 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client 3033 + " when updating " + app); 3034 if (clientIndex <= lrui) { 3035 // Don't allow the client index restriction to push it down farther in the 3036 // list than it already is. 3037 clientIndex = lrui; 3038 } 3039 if (clientIndex >= 0 && index > clientIndex) { 3040 index = clientIndex; 3041 } 3042 } 3043 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app); 3044 mLruProcesses.add(index, app); 3045 nextIndex = index - 1; 3046 mLruProcessActivityStart++; 3047 mLruProcessServiceStart++; 3048 if (index > 1) { 3049 updateClientActivitiesOrdering(app, mLruProcessServiceStart - 1, 0, index - 1); 3050 } 3051 } 3052 3053 app.lruSeq = mLruSeq; 3054 3055 // If the app is currently using a content provider or service, 3056 // bump those processes as well. 3057 for (int j = app.connections.size() - 1; j >= 0; j--) { 3058 ConnectionRecord cr = app.connections.valueAt(j); 3059 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null 3060 && cr.binding.service.app != null 3061 && cr.binding.service.app.lruSeq != mLruSeq 3062 && (cr.flags & Context.BIND_REDUCTION_FLAGS) == 0 3063 && !cr.binding.service.app.isPersistent()) { 3064 if (cr.binding.service.app.hasClientActivities()) { 3065 if (nextActivityIndex >= 0) { 3066 nextActivityIndex = updateLruProcessInternalLocked(cr.binding.service.app, 3067 now, 3068 nextActivityIndex, mLruSeq, 3069 "service connection", cr, app); 3070 } 3071 } else { 3072 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, 3073 now, 3074 nextIndex, mLruSeq, 3075 "service connection", cr, app); 3076 } 3077 } 3078 } 3079 for (int j = app.conProviders.size() - 1; j >= 0; j--) { 3080 ContentProviderRecord cpr = app.conProviders.get(j).provider; 3081 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.isPersistent()) { 3082 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex, mLruSeq, 3083 "provider reference", cpr, app); 3084 } 3085 } 3086 } 3087 getLRURecordForAppLocked(IApplicationThread thread)3088 final ProcessRecord getLRURecordForAppLocked(IApplicationThread thread) { 3089 final IBinder threadBinder = thread.asBinder(); 3090 // Find the application record. 3091 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3092 final ProcessRecord rec = mLruProcesses.get(i); 3093 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 3094 return rec; 3095 } 3096 } 3097 return null; 3098 } 3099 haveBackgroundProcessLocked()3100 boolean haveBackgroundProcessLocked() { 3101 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3102 final ProcessRecord rec = mLruProcesses.get(i); 3103 if (rec.thread != null 3104 && rec.setProcState >= PROCESS_STATE_CACHED_ACTIVITY) { 3105 return true; 3106 } 3107 } 3108 return false; 3109 } 3110 procStateToImportance(int procState, int memAdj, ActivityManager.RunningAppProcessInfo currApp, int clientTargetSdk)3111 private static int procStateToImportance(int procState, int memAdj, 3112 ActivityManager.RunningAppProcessInfo currApp, 3113 int clientTargetSdk) { 3114 int imp = ActivityManager.RunningAppProcessInfo.procStateToImportanceForTargetSdk( 3115 procState, clientTargetSdk); 3116 if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { 3117 currApp.lru = memAdj; 3118 } else { 3119 currApp.lru = 0; 3120 } 3121 return imp; 3122 } 3123 3124 @GuardedBy("mService") fillInProcMemInfoLocked(ProcessRecord app, ActivityManager.RunningAppProcessInfo outInfo, int clientTargetSdk)3125 void fillInProcMemInfoLocked(ProcessRecord app, 3126 ActivityManager.RunningAppProcessInfo outInfo, 3127 int clientTargetSdk) { 3128 outInfo.pid = app.pid; 3129 outInfo.uid = app.info.uid; 3130 if (mService.mAtmInternal.isHeavyWeightProcess(app.getWindowProcessController())) { 3131 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE; 3132 } 3133 if (app.isPersistent()) { 3134 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT; 3135 } 3136 if (app.hasActivities()) { 3137 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES; 3138 } 3139 outInfo.lastTrimLevel = app.trimMemoryLevel; 3140 int adj = app.curAdj; 3141 int procState = app.getCurProcState(); 3142 outInfo.importance = procStateToImportance(procState, adj, outInfo, 3143 clientTargetSdk); 3144 outInfo.importanceReasonCode = app.adjTypeCode; 3145 outInfo.processState = app.getCurProcState(); 3146 outInfo.isFocused = (app == mService.getTopAppLocked()); 3147 outInfo.lastActivityTime = app.lastActivityTime; 3148 } 3149 3150 @GuardedBy("mService") getRunningAppProcessesLocked(boolean allUsers, int userId, boolean allUids, int callingUid, int clientTargetSdk)3151 List<ActivityManager.RunningAppProcessInfo> getRunningAppProcessesLocked(boolean allUsers, 3152 int userId, boolean allUids, int callingUid, int clientTargetSdk) { 3153 // Lazy instantiation of list 3154 List<ActivityManager.RunningAppProcessInfo> runList = null; 3155 3156 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3157 ProcessRecord app = mLruProcesses.get(i); 3158 if ((!allUsers && app.userId != userId) 3159 || (!allUids && app.uid != callingUid)) { 3160 continue; 3161 } 3162 if ((app.thread != null) && (!app.isCrashing() && !app.isNotResponding())) { 3163 // Generate process state info for running application 3164 ActivityManager.RunningAppProcessInfo currApp = 3165 new ActivityManager.RunningAppProcessInfo(app.processName, 3166 app.pid, app.getPackageList()); 3167 fillInProcMemInfoLocked(app, currApp, clientTargetSdk); 3168 if (app.adjSource instanceof ProcessRecord) { 3169 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid; 3170 currApp.importanceReasonImportance = 3171 ActivityManager.RunningAppProcessInfo.procStateToImportance( 3172 app.adjSourceProcState); 3173 } else if (app.adjSource instanceof ActivityServiceConnectionsHolder) { 3174 final ActivityServiceConnectionsHolder r = 3175 (ActivityServiceConnectionsHolder) app.adjSource; 3176 final int pid = r.getActivityPid(); 3177 if (pid != -1) { 3178 currApp.importanceReasonPid = pid; 3179 } 3180 } 3181 if (app.adjTarget instanceof ComponentName) { 3182 currApp.importanceReasonComponent = (ComponentName)app.adjTarget; 3183 } 3184 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance 3185 // + " lru=" + currApp.lru); 3186 if (runList == null) { 3187 runList = new ArrayList<>(); 3188 } 3189 runList.add(currApp); 3190 } 3191 } 3192 return runList; 3193 } 3194 3195 @GuardedBy("mService") getLruSizeLocked()3196 int getLruSizeLocked() { 3197 return mLruProcesses.size(); 3198 } 3199 3200 @GuardedBy("mService") dumpLruListHeaderLocked(PrintWriter pw)3201 void dumpLruListHeaderLocked(PrintWriter pw) { 3202 pw.print(" Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size()); 3203 pw.print(" total, non-act at "); 3204 pw.print(mLruProcesses.size() - mLruProcessActivityStart); 3205 pw.print(", non-svc at "); 3206 pw.print(mLruProcesses.size() - mLruProcessServiceStart); 3207 pw.println("):"); 3208 } 3209 3210 @GuardedBy("mService") collectProcessesLocked(int start, boolean allPkgs, String[] args)3211 ArrayList<ProcessRecord> collectProcessesLocked(int start, boolean allPkgs, String[] args) { 3212 ArrayList<ProcessRecord> procs; 3213 if (args != null && args.length > start 3214 && args[start].charAt(0) != '-') { 3215 procs = new ArrayList<ProcessRecord>(); 3216 int pid = -1; 3217 try { 3218 pid = Integer.parseInt(args[start]); 3219 } catch (NumberFormatException e) { 3220 } 3221 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3222 ProcessRecord proc = mLruProcesses.get(i); 3223 if (proc.pid > 0 && proc.pid == pid) { 3224 procs.add(proc); 3225 } else if (allPkgs && proc.pkgList != null 3226 && proc.pkgList.containsKey(args[start])) { 3227 procs.add(proc); 3228 } else if (proc.processName.equals(args[start])) { 3229 procs.add(proc); 3230 } 3231 } 3232 if (procs.size() <= 0) { 3233 return null; 3234 } 3235 } else { 3236 procs = new ArrayList<ProcessRecord>(mLruProcesses); 3237 } 3238 return procs; 3239 } 3240 3241 @GuardedBy("mService") updateApplicationInfoLocked(List<String> packagesToUpdate, int userId, boolean updateFrameworkRes)3242 void updateApplicationInfoLocked(List<String> packagesToUpdate, int userId, 3243 boolean updateFrameworkRes) { 3244 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3245 final ProcessRecord app = mLruProcesses.get(i); 3246 if (app.thread == null) { 3247 continue; 3248 } 3249 3250 if (userId != UserHandle.USER_ALL && app.userId != userId) { 3251 continue; 3252 } 3253 3254 final int packageCount = app.pkgList.size(); 3255 for (int j = 0; j < packageCount; j++) { 3256 final String packageName = app.pkgList.keyAt(j); 3257 if (updateFrameworkRes || packagesToUpdate.contains(packageName)) { 3258 try { 3259 final ApplicationInfo ai = AppGlobals.getPackageManager() 3260 .getApplicationInfo(packageName, STOCK_PM_FLAGS, app.userId); 3261 if (ai != null) { 3262 app.thread.scheduleApplicationInfoChanged(ai); 3263 } 3264 } catch (RemoteException e) { 3265 Slog.w(TAG, String.format("Failed to update %s ApplicationInfo for %s", 3266 packageName, app)); 3267 } 3268 } 3269 } 3270 } 3271 } 3272 3273 @GuardedBy("mService") sendPackageBroadcastLocked(int cmd, String[] packages, int userId)3274 void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 3275 boolean foundProcess = false; 3276 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3277 ProcessRecord r = mLruProcesses.get(i); 3278 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) { 3279 try { 3280 for (int index = packages.length - 1; index >= 0 && !foundProcess; index--) { 3281 if (packages[index].equals(r.info.packageName)) { 3282 foundProcess = true; 3283 } 3284 } 3285 r.thread.dispatchPackageBroadcast(cmd, packages); 3286 } catch (RemoteException ex) { 3287 } 3288 } 3289 } 3290 3291 if (!foundProcess) { 3292 try { 3293 AppGlobals.getPackageManager().notifyPackagesReplacedReceived(packages); 3294 } catch (RemoteException ignored) { 3295 } 3296 } 3297 } 3298 3299 /** Returns the uid's process state or PROCESS_STATE_NONEXISTENT if not running */ 3300 @GuardedBy("mService") getUidProcStateLocked(int uid)3301 int getUidProcStateLocked(int uid) { 3302 UidRecord uidRec = mActiveUids.get(uid); 3303 return uidRec == null ? PROCESS_STATE_NONEXISTENT : uidRec.getCurProcState(); 3304 } 3305 3306 /** Returns the UidRecord for the given uid, if it exists. */ 3307 @GuardedBy("mService") getUidRecordLocked(int uid)3308 UidRecord getUidRecordLocked(int uid) { 3309 return mActiveUids.get(uid); 3310 } 3311 3312 /** 3313 * Call {@link ActivityManagerService#doStopUidLocked} 3314 * (which will also stop background services) for all idle UIDs. 3315 */ 3316 @GuardedBy("mService") doStopUidForIdleUidsLocked()3317 void doStopUidForIdleUidsLocked() { 3318 final int size = mActiveUids.size(); 3319 for (int i = 0; i < size; i++) { 3320 final int uid = mActiveUids.keyAt(i); 3321 if (UserHandle.isCore(uid)) { 3322 continue; 3323 } 3324 final UidRecord uidRec = mActiveUids.valueAt(i); 3325 if (!uidRec.idle) { 3326 continue; 3327 } 3328 mService.doStopUidLocked(uidRec.uid, uidRec); 3329 } 3330 } 3331 setLmkdKillListener(final LmkdKillListener listener)3332 void setLmkdKillListener(final LmkdKillListener listener) { 3333 synchronized (mService) { 3334 mLmkdKillListener = listener; 3335 } 3336 } 3337 handleLmkdProcKilled(final int pid, final int uid)3338 private void handleLmkdProcKilled(final int pid, final int uid) { 3339 // Log only now 3340 if (DEBUG_PROCESSES) { 3341 Slog.i(TAG, "lmkd kill: pid=" + pid + " uid=" + uid); 3342 } 3343 3344 if (mService == null) { 3345 return; 3346 } 3347 // Notify any interesed party regarding the lmkd kills 3348 synchronized (mService) { 3349 final LmkdKillListener listener = mLmkdKillListener; 3350 if (listener != null) { 3351 mService.mHandler.post(()-> listener.onLmkdKillOccurred(pid, uid)); 3352 } 3353 } 3354 } 3355 handleZygoteSigChld(int pid, int uid, int status)3356 private void handleZygoteSigChld(int pid, int uid, int status) { 3357 // Just log it now. 3358 if (DEBUG_PROCESSES) { 3359 Slog.i(TAG, "Got SIGCHLD from zygote: pid=" + pid + ", uid=" + uid 3360 + ", status=" + Integer.toHexString(status)); 3361 } 3362 } 3363 3364 /** 3365 * Create a server socket in system_server, zygote will connect to it 3366 * in order to send unsolicited messages to system_server. 3367 */ createSystemServerSocketForZygote()3368 private LocalSocket createSystemServerSocketForZygote() { 3369 // The file system entity for this socket is created with 0666 perms, owned 3370 // by system:system. selinux restricts things so that only zygotes can 3371 // access it. 3372 final File socketFile = new File(UNSOL_ZYGOTE_MSG_SOCKET_PATH); 3373 if (socketFile.exists()) { 3374 socketFile.delete(); 3375 } 3376 3377 LocalSocket serverSocket = null; 3378 try { 3379 serverSocket = new LocalSocket(LocalSocket.SOCKET_DGRAM); 3380 serverSocket.bind(new LocalSocketAddress( 3381 UNSOL_ZYGOTE_MSG_SOCKET_PATH, LocalSocketAddress.Namespace.FILESYSTEM)); 3382 Os.chmod(UNSOL_ZYGOTE_MSG_SOCKET_PATH, 0666); 3383 } catch (Exception e) { 3384 if (serverSocket != null) { 3385 try { 3386 serverSocket.close(); 3387 } catch (IOException ex) { 3388 } 3389 serverSocket = null; 3390 } 3391 } 3392 return serverSocket; 3393 } 3394 3395 /** 3396 * Handle the unsolicited message from zygote. 3397 */ handleZygoteMessages(FileDescriptor fd, int events)3398 private int handleZygoteMessages(FileDescriptor fd, int events) { 3399 final int eventFd = fd.getInt$(); 3400 if ((events & EVENT_INPUT) != 0) { 3401 // An incoming message from zygote 3402 try { 3403 final int len = Os.read(fd, mZygoteUnsolicitedMessage, 0, 3404 mZygoteUnsolicitedMessage.length); 3405 if (len > 0 && mZygoteSigChldMessage.length == Zygote.nativeParseSigChld( 3406 mZygoteUnsolicitedMessage, len, mZygoteSigChldMessage)) { 3407 handleZygoteSigChld(mZygoteSigChldMessage[0] /* pid */, 3408 mZygoteSigChldMessage[1] /* uid */, 3409 mZygoteSigChldMessage[2] /* status */); 3410 } 3411 } catch (Exception e) { 3412 Slog.w(TAG, "Exception in reading unsolicited zygote message: " + e); 3413 } 3414 } 3415 return EVENT_INPUT; 3416 } 3417 } 3418