1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.am; 18 19 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT; 20 21 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST; 22 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR; 23 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 24 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 25 import static com.android.server.am.ActivityManagerService.MY_PID; 26 27 import android.app.ActivityManager; 28 import android.app.ApplicationErrorReport; 29 import android.app.Dialog; 30 import android.app.IApplicationThread; 31 import android.content.ComponentName; 32 import android.content.Context; 33 import android.content.pm.ApplicationInfo; 34 import android.content.pm.ServiceInfo; 35 import android.content.pm.VersionedPackage; 36 import android.content.res.CompatibilityInfo; 37 import android.os.Binder; 38 import android.os.Debug; 39 import android.os.IBinder; 40 import android.os.Message; 41 import android.os.Process; 42 import android.os.RemoteException; 43 import android.os.SystemClock; 44 import android.os.Trace; 45 import android.os.UserHandle; 46 import android.provider.Settings; 47 import android.server.ServerProtoEnums; 48 import android.util.ArrayMap; 49 import android.util.ArraySet; 50 import android.util.DebugUtils; 51 import android.util.EventLog; 52 import android.util.Slog; 53 import android.util.SparseArray; 54 import android.util.StatsLog; 55 import android.util.TimeUtils; 56 import android.util.proto.ProtoOutputStream; 57 58 import com.android.internal.annotations.VisibleForTesting; 59 import com.android.internal.app.procstats.ProcessState; 60 import com.android.internal.app.procstats.ProcessStats; 61 import com.android.internal.os.BatteryStatsImpl; 62 import com.android.internal.os.ProcessCpuTracker; 63 import com.android.internal.os.Zygote; 64 import com.android.server.wm.WindowProcessController; 65 import com.android.server.wm.WindowProcessListener; 66 67 import java.io.File; 68 import java.io.PrintWriter; 69 import java.util.ArrayList; 70 import java.util.Arrays; 71 import java.util.List; 72 73 /** 74 * Full information about a particular process that 75 * is currently running. 76 */ 77 class ProcessRecord implements WindowProcessListener { 78 private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM; 79 80 private final ActivityManagerService mService; // where we came from 81 final ApplicationInfo info; // all about the first app in the process 82 final boolean isolated; // true if this is a special isolated process 83 final boolean appZygote; // true if this is forked from the app zygote 84 final int uid; // uid of process; may be different from 'info' if isolated 85 final int userId; // user of process. 86 final String processName; // name of the process 87 // List of packages running in the process 88 final PackageList pkgList = new PackageList(); 89 final class PackageList { 90 final ArrayMap<String, ProcessStats.ProcessStateHolder> mPkgList = new ArrayMap<>(); 91 put(String key, ProcessStats.ProcessStateHolder value)92 ProcessStats.ProcessStateHolder put(String key, ProcessStats.ProcessStateHolder value) { 93 mWindowProcessController.addPackage(key); 94 return mPkgList.put(key, value); 95 } 96 clear()97 void clear() { 98 mPkgList.clear(); 99 mWindowProcessController.clearPackageList(); 100 } 101 size()102 int size() { 103 return mPkgList.size(); 104 } 105 keyAt(int index)106 String keyAt(int index) { 107 return mPkgList.keyAt(index); 108 } 109 valueAt(int index)110 public ProcessStats.ProcessStateHolder valueAt(int index) { 111 return mPkgList.valueAt(index); 112 } 113 get(String pkgName)114 ProcessStats.ProcessStateHolder get(String pkgName) { 115 return mPkgList.get(pkgName); 116 } 117 containsKey(Object key)118 boolean containsKey(Object key) { 119 return mPkgList.containsKey(key); 120 } 121 } 122 123 final ProcessList.ProcStateMemTracker procStateMemTracker 124 = new ProcessList.ProcStateMemTracker(); 125 UidRecord uidRecord; // overall state of process's uid. 126 ArraySet<String> pkgDeps; // additional packages we have a dependency on 127 IApplicationThread thread; // the actual proc... may be null only if 128 // 'persistent' is true (in which case we 129 // are in the process of launching the app) 130 ProcessState baseProcessTracker; 131 BatteryStatsImpl.Uid.Proc curProcBatteryStats; 132 int pid; // The process of this application; 0 if none 133 String procStatFile; // path to /proc/<pid>/stat 134 int[] gids; // The gids this process was launched with 135 private String mRequiredAbi;// The ABI this process was launched with 136 String instructionSet; // The instruction set this process was launched with 137 boolean starting; // True if the process is being started 138 long lastActivityTime; // For managing the LRU list 139 long lastPssTime; // Last time we retrieved PSS data 140 long nextPssTime; // Next time we want to request PSS data 141 long lastStateTime; // Last time setProcState changed 142 long initialIdlePss; // Initial memory pss of process for idle maintenance. 143 long lastPss; // Last computed memory pss. 144 long lastSwapPss; // Last computed SwapPss. 145 long lastCachedPss; // Last computed pss when in cached state. 146 long lastCachedSwapPss; // Last computed SwapPss when in cached state. 147 int maxAdj; // Maximum OOM adjustment for this process 148 private int mCurRawAdj; // Current OOM unlimited adjustment for this process 149 int setRawAdj; // Last set OOM unlimited adjustment for this process 150 int curAdj; // Current OOM adjustment for this process 151 int setAdj; // Last set OOM adjustment for this process 152 int verifiedAdj; // The last adjustment that was verified as actually being set 153 long lastCompactTime; // The last time that this process was compacted 154 int reqCompactAction; // The most recent compaction action requested for this app. 155 int lastCompactAction; // The most recent compaction action performed for this app. 156 private int mCurSchedGroup; // Currently desired scheduling class 157 int setSchedGroup; // Last set to background scheduling class 158 int trimMemoryLevel; // Last selected memory trimming level 159 private int mCurProcState = PROCESS_STATE_NONEXISTENT; // Currently computed process state 160 private int mRepProcState = PROCESS_STATE_NONEXISTENT; // Last reported process state 161 private int mCurRawProcState = PROCESS_STATE_NONEXISTENT; // Temp state during computation 162 int setProcState = PROCESS_STATE_NONEXISTENT; // Last set process state in process tracker 163 int pssProcState = PROCESS_STATE_NONEXISTENT; // Currently requesting pss for 164 int pssStatType; // The type of stat collection that we are currently requesting 165 int savedPriority; // Previous priority value if we're switching to non-SCHED_OTHER 166 int renderThreadTid; // TID for RenderThread 167 ServiceRecord connectionService; // Service that applied current connectionGroup/Importance 168 int connectionGroup; // Last group set by a connection 169 int connectionImportance; // Last importance set by a connection 170 boolean serviceb; // Process currently is on the service B list 171 boolean serviceHighRam; // We are forcing to service B list due to its RAM use 172 boolean notCachedSinceIdle; // Has this process not been in a cached state since last idle? 173 private boolean mHasClientActivities; // Are there any client services with activities? 174 boolean hasStartedServices; // Are there any started services running in this process? 175 private boolean mHasForegroundServices; // Running any services that are foreground? 176 private int mFgServiceTypes; // Type of foreground service, if there is a foreground service. 177 private int mRepFgServiceTypes; // Last reported foreground service types. 178 private boolean mHasForegroundActivities; // Running any activities that are foreground? 179 boolean repForegroundActivities; // Last reported foreground activities. 180 boolean systemNoUi; // This is a system process, but not currently showing UI. 181 boolean hasShownUi; // Has UI been shown in this process since it was started? 182 private boolean mHasTopUi; // Is this process currently showing a non-activity UI that the user 183 // is interacting with? E.g. The status bar when it is expanded, but 184 // not when it is minimized. When true the 185 // process will be set to use the ProcessList#SCHED_GROUP_TOP_APP 186 // scheduling group to boost performance. 187 private boolean mHasOverlayUi; // Is the process currently showing a non-activity UI that 188 // overlays on-top of activity UIs on screen. E.g. display a window 189 // of type 190 // android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY 191 // When true the process will oom adj score will be set to 192 // ProcessList#PERCEPTIBLE_APP_ADJ at minimum to reduce the chance 193 // of the process getting killed. 194 boolean runningRemoteAnimation; // Is the process currently running a RemoteAnimation? When true 195 // the process will be set to use the 196 // ProcessList#SCHED_GROUP_TOP_APP scheduling group to boost 197 // performance, as well as oom adj score will be set to 198 // ProcessList#VISIBLE_APP_ADJ at minimum to reduce the chance 199 // of the process getting killed. 200 private boolean mPendingUiClean; // Want to clean up resources from showing UI? 201 boolean hasAboveClient; // Bound using BIND_ABOVE_CLIENT, so want to be lower 202 boolean treatLikeActivity; // Bound using BIND_TREAT_LIKE_ACTIVITY 203 boolean bad; // True if disabled in the bad process list 204 boolean killedByAm; // True when proc has been killed by activity manager, not for RAM 205 boolean killed; // True once we know the process has been killed 206 boolean procStateChanged; // Keep track of whether we changed 'setAdj'. 207 boolean reportedInteraction;// Whether we have told usage stats about it being an interaction 208 boolean unlocked; // True when proc was started in user unlocked state 209 private long mInteractionEventTime; // The time we sent the last interaction event 210 private long mFgInteractionTime; // When we became foreground for interaction purposes 211 String waitingToKill; // Process is waiting to be killed when in the bg, and reason 212 Object forcingToImportant; // Token that is forcing this process to be important 213 int adjSeq; // Sequence id for identifying oom_adj assignment cycles 214 int completedAdjSeq; // Sequence id for identifying oom_adj assignment cycles 215 boolean containsCycle; // Whether this app has encountered a cycle in the most recent update 216 int lruSeq; // Sequence id for identifying LRU update cycles 217 CompatibilityInfo compat; // last used compatibility mode 218 IBinder.DeathRecipient deathRecipient; // Who is watching for the death. 219 private ActiveInstrumentation mInstr; // Set to currently active instrumentation running in 220 // process. 221 private boolean mUsingWrapper; // Set to true when process was launched with a wrapper attached 222 final ArraySet<BroadcastRecord> curReceivers = new ArraySet<BroadcastRecord>();// receivers currently running in the app 223 private long mWhenUnimportant; // When (uptime) the process last became unimportant 224 long lastCpuTime; // How long proc has run CPU at last check 225 long curCpuTime; // How long proc has run CPU most recently 226 long lastRequestedGc; // When we last asked the app to do a gc 227 long lastLowMemory; // When we last told the app that memory is low 228 long lastProviderTime; // The last time someone else was using a provider in this process. 229 long lastTopTime; // The last time the process was in the TOP state or greater. 230 boolean reportLowMemory; // Set to true when waiting to report low mem 231 boolean empty; // Is this an empty background process? 232 boolean cached; // Is this a cached process? 233 String adjType; // Debugging: primary thing impacting oom_adj. 234 int adjTypeCode; // Debugging: adj code to report to app. 235 Object adjSource; // Debugging: option dependent object. 236 int adjSourceProcState; // Debugging: proc state of adjSource's process. 237 Object adjTarget; // Debugging: target component impacting oom_adj. 238 Runnable crashHandler; // Optional local handler to be invoked in the process crash. 239 240 // Cache of last retrieve memory info and uptime, to throttle how frequently 241 // apps can requyest it. 242 Debug.MemoryInfo lastMemInfo; 243 long lastMemInfoTime; 244 245 // Controller for driving the process state on the window manager side. 246 final private WindowProcessController mWindowProcessController; 247 // all ServiceRecord running in this process 248 final ArraySet<ServiceRecord> services = new ArraySet<>(); 249 // services that are currently executing code (need to remain foreground). 250 final ArraySet<ServiceRecord> executingServices = new ArraySet<>(); 251 // All ConnectionRecord this process holds 252 final ArraySet<ConnectionRecord> connections = new ArraySet<>(); 253 // all IIntentReceivers that are registered from this process. 254 final ArraySet<ReceiverList> receivers = new ArraySet<>(); 255 // class (String) -> ContentProviderRecord 256 final ArrayMap<String, ContentProviderRecord> pubProviders = new ArrayMap<>(); 257 // All ContentProviderRecord process is using 258 final ArrayList<ContentProviderConnection> conProviders = new ArrayList<>(); 259 // A set of tokens that currently contribute to this process being temporarily whitelisted 260 // to start activities even if it's not in the foreground 261 final ArraySet<Binder> mAllowBackgroundActivityStartsTokens = new ArraySet<>(); 262 // a set of UIDs of all bound clients 263 private ArraySet<Integer> mBoundClientUids = new ArraySet<>(); 264 265 String isolatedEntryPoint; // Class to run on start if this is a special isolated process. 266 String[] isolatedEntryPointArgs; // Arguments to pass to isolatedEntryPoint's main(). 267 268 boolean execServicesFg; // do we need to be executing services in the foreground? 269 private boolean mPersistent;// always keep this application running? 270 private boolean mCrashing; // are we in the process of crashing? 271 Dialog crashDialog; // dialog being displayed due to crash. 272 boolean forceCrashReport; // suppress normal auto-dismiss of crash dialog & report UI? 273 private boolean mNotResponding; // does the app have a not responding dialog? 274 Dialog anrDialog; // dialog being displayed due to app not resp. 275 volatile boolean removed; // Whether this process should be killed and removed from process 276 // list. It is set when the package is force-stopped or the process 277 // has crashed too many times. 278 private boolean mDebugging; // was app launched for debugging? 279 boolean waitedForDebugger; // has process show wait for debugger dialog? 280 Dialog waitDialog; // current wait for debugger dialog 281 282 String shortStringName; // caching of toShortString() result. 283 String stringName; // caching of toString() result. 284 boolean pendingStart; // Process start is pending. 285 long startSeq; // Seq no. indicating the latest process start associated with 286 // this process record. 287 int mountMode; // Indicates how the external storage was mounted for this process. 288 289 // These reports are generated & stored when an app gets into an error condition. 290 // They will be "null" when all is OK. 291 ActivityManager.ProcessErrorStateInfo crashingReport; 292 ActivityManager.ProcessErrorStateInfo notRespondingReport; 293 294 // Who will be notified of the error. This is usually an activity in the 295 // app that installed the package. 296 ComponentName errorReportReceiver; 297 298 // Process is currently hosting a backup agent for backup or restore 299 public boolean inFullBackup; 300 // App is allowed to manage whitelists such as temporary Power Save mode whitelist. 301 boolean whitelistManager; 302 303 // Params used in starting this process. 304 HostingRecord hostingRecord; 305 String seInfo; 306 long startTime; 307 // This will be same as {@link #uid} usually except for some apps used during factory testing. 308 int startUid; 309 setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, long startTime)310 void setStartParams(int startUid, HostingRecord hostingRecord, String seInfo, 311 long startTime) { 312 this.startUid = startUid; 313 this.hostingRecord = hostingRecord; 314 this.seInfo = seInfo; 315 this.startTime = startTime; 316 } 317 dump(PrintWriter pw, String prefix)318 void dump(PrintWriter pw, String prefix) { 319 final long nowUptime = SystemClock.uptimeMillis(); 320 321 pw.print(prefix); pw.print("user #"); pw.print(userId); 322 pw.print(" uid="); pw.print(info.uid); 323 if (uid != info.uid) { 324 pw.print(" ISOLATED uid="); pw.print(uid); 325 } 326 pw.print(" gids={"); 327 if (gids != null) { 328 for (int gi=0; gi<gids.length; gi++) { 329 if (gi != 0) pw.print(", "); 330 pw.print(gids[gi]); 331 332 } 333 } 334 pw.println("}"); 335 pw.print(prefix); pw.print("mRequiredAbi="); pw.print(mRequiredAbi); 336 pw.print(" instructionSet="); pw.println(instructionSet); 337 if (info.className != null) { 338 pw.print(prefix); pw.print("class="); pw.println(info.className); 339 } 340 if (info.manageSpaceActivityName != null) { 341 pw.print(prefix); pw.print("manageSpaceActivityName="); 342 pw.println(info.manageSpaceActivityName); 343 } 344 345 pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir); 346 pw.print(" publicDir="); pw.print(info.publicSourceDir); 347 pw.print(" data="); pw.println(info.dataDir); 348 pw.print(prefix); pw.print("packageList={"); 349 for (int i=0; i<pkgList.size(); i++) { 350 if (i > 0) pw.print(", "); 351 pw.print(pkgList.keyAt(i)); 352 } 353 pw.println("}"); 354 if (pkgDeps != null) { 355 pw.print(prefix); pw.print("packageDependencies={"); 356 for (int i=0; i<pkgDeps.size(); i++) { 357 if (i > 0) pw.print(", "); 358 pw.print(pkgDeps.valueAt(i)); 359 } 360 pw.println("}"); 361 } 362 pw.print(prefix); pw.print("compat="); pw.println(compat); 363 if (mInstr != null) { 364 pw.print(prefix); pw.print("mInstr="); pw.println(mInstr); 365 } 366 pw.print(prefix); pw.print("thread="); pw.println(thread); 367 pw.print(prefix); pw.print("pid="); pw.print(pid); pw.print(" starting="); 368 pw.println(starting); 369 pw.print(prefix); pw.print("lastActivityTime="); 370 TimeUtils.formatDuration(lastActivityTime, nowUptime, pw); 371 pw.print(" lastPssTime="); 372 TimeUtils.formatDuration(lastPssTime, nowUptime, pw); 373 pw.print(" pssStatType="); pw.print(pssStatType); 374 pw.print(" nextPssTime="); 375 TimeUtils.formatDuration(nextPssTime, nowUptime, pw); 376 pw.println(); 377 pw.print(prefix); pw.print("adjSeq="); pw.print(adjSeq); 378 pw.print(" lruSeq="); pw.print(lruSeq); 379 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, lastPss*1024); 380 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, lastSwapPss*1024); 381 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, lastCachedPss*1024); 382 pw.print(" lastCachedSwapPss="); DebugUtils.printSizeValue(pw, lastCachedSwapPss*1024); 383 pw.println(); 384 pw.print(prefix); pw.print("procStateMemTracker: "); 385 procStateMemTracker.dumpLine(pw); 386 pw.print(prefix); pw.print("cached="); pw.print(cached); 387 pw.print(" empty="); pw.println(empty); 388 if (serviceb) { 389 pw.print(prefix); pw.print("serviceb="); pw.print(serviceb); 390 pw.print(" serviceHighRam="); pw.println(serviceHighRam); 391 } 392 if (notCachedSinceIdle) { 393 pw.print(prefix); pw.print("notCachedSinceIdle="); pw.print(notCachedSinceIdle); 394 pw.print(" initialIdlePss="); pw.println(initialIdlePss); 395 } 396 pw.print(prefix); pw.print("oom: max="); pw.print(maxAdj); 397 pw.print(" curRaw="); pw.print(mCurRawAdj); 398 pw.print(" setRaw="); pw.print(setRawAdj); 399 pw.print(" cur="); pw.print(curAdj); 400 pw.print(" set="); pw.println(setAdj); 401 pw.print(prefix); pw.print("lastCompactTime="); pw.print(lastCompactTime); 402 pw.print(" lastCompactAction="); pw.print(lastCompactAction); 403 pw.print(prefix); pw.print("mCurSchedGroup="); pw.print(mCurSchedGroup); 404 pw.print(" setSchedGroup="); pw.print(setSchedGroup); 405 pw.print(" systemNoUi="); pw.print(systemNoUi); 406 pw.print(" trimMemoryLevel="); pw.println(trimMemoryLevel); 407 pw.print(prefix); pw.print("curProcState="); pw.print(getCurProcState()); 408 pw.print(" mRepProcState="); pw.print(mRepProcState); 409 pw.print(" pssProcState="); pw.print(pssProcState); 410 pw.print(" setProcState="); pw.print(setProcState); 411 pw.print(" lastStateTime="); 412 TimeUtils.formatDuration(lastStateTime, nowUptime, pw); 413 pw.println(); 414 if (hasShownUi || mPendingUiClean || hasAboveClient || treatLikeActivity) { 415 pw.print(prefix); pw.print("hasShownUi="); pw.print(hasShownUi); 416 pw.print(" pendingUiClean="); pw.print(mPendingUiClean); 417 pw.print(" hasAboveClient="); pw.print(hasAboveClient); 418 pw.print(" treatLikeActivity="); pw.println(treatLikeActivity); 419 } 420 if (connectionService != null || connectionGroup != 0) { 421 pw.print(prefix); pw.print("connectionGroup="); pw.print(connectionGroup); 422 pw.print(" Importance="); pw.print(connectionImportance); 423 pw.print(" Service="); pw.println(connectionService); 424 } 425 if (hasTopUi() || hasOverlayUi() || runningRemoteAnimation) { 426 pw.print(prefix); pw.print("hasTopUi="); pw.print(hasTopUi()); 427 pw.print(" hasOverlayUi="); pw.print(hasOverlayUi()); 428 pw.print(" runningRemoteAnimation="); pw.println(runningRemoteAnimation); 429 } 430 if (mHasForegroundServices || forcingToImportant != null) { 431 pw.print(prefix); pw.print("mHasForegroundServices="); pw.print(mHasForegroundServices); 432 pw.print(" forcingToImportant="); pw.println(forcingToImportant); 433 } 434 if (reportedInteraction || mFgInteractionTime != 0) { 435 pw.print(prefix); pw.print("reportedInteraction="); 436 pw.print(reportedInteraction); 437 if (mInteractionEventTime != 0) { 438 pw.print(" time="); 439 TimeUtils.formatDuration(mInteractionEventTime, SystemClock.elapsedRealtime(), pw); 440 } 441 if (mFgInteractionTime != 0) { 442 pw.print(" fgInteractionTime="); 443 TimeUtils.formatDuration(mFgInteractionTime, SystemClock.elapsedRealtime(), pw); 444 } 445 pw.println(); 446 } 447 if (mPersistent || removed) { 448 pw.print(prefix); pw.print("persistent="); pw.print(mPersistent); 449 pw.print(" removed="); pw.println(removed); 450 } 451 if (mHasClientActivities || mHasForegroundActivities || repForegroundActivities) { 452 pw.print(prefix); pw.print("hasClientActivities="); pw.print(mHasClientActivities); 453 pw.print(" foregroundActivities="); pw.print(mHasForegroundActivities); 454 pw.print(" (rep="); pw.print(repForegroundActivities); pw.println(")"); 455 } 456 if (lastProviderTime > 0) { 457 pw.print(prefix); pw.print("lastProviderTime="); 458 TimeUtils.formatDuration(lastProviderTime, nowUptime, pw); 459 pw.println(); 460 } 461 if (lastTopTime > 0) { 462 pw.print(prefix); pw.print("lastTopTime="); 463 TimeUtils.formatDuration(lastTopTime, nowUptime, pw); 464 pw.println(); 465 } 466 if (hasStartedServices) { 467 pw.print(prefix); pw.print("hasStartedServices="); pw.println(hasStartedServices); 468 } 469 if (pendingStart) { 470 pw.print(prefix); pw.print("pendingStart="); pw.println(pendingStart); 471 } 472 pw.print(prefix); pw.print("startSeq="); pw.println(startSeq); 473 pw.print(prefix); pw.print("mountMode="); pw.println( 474 DebugUtils.valueToString(Zygote.class, "MOUNT_EXTERNAL_", mountMode)); 475 if (setProcState > ActivityManager.PROCESS_STATE_SERVICE) { 476 pw.print(prefix); pw.print("lastCpuTime="); pw.print(lastCpuTime); 477 if (lastCpuTime > 0) { 478 pw.print(" timeUsed="); 479 TimeUtils.formatDuration(curCpuTime - lastCpuTime, pw); 480 } 481 pw.print(" whenUnimportant="); 482 TimeUtils.formatDuration(mWhenUnimportant - nowUptime, pw); 483 pw.println(); 484 } 485 pw.print(prefix); pw.print("lastRequestedGc="); 486 TimeUtils.formatDuration(lastRequestedGc, nowUptime, pw); 487 pw.print(" lastLowMemory="); 488 TimeUtils.formatDuration(lastLowMemory, nowUptime, pw); 489 pw.print(" reportLowMemory="); pw.println(reportLowMemory); 490 if (killed || killedByAm || waitingToKill != null) { 491 pw.print(prefix); pw.print("killed="); pw.print(killed); 492 pw.print(" killedByAm="); pw.print(killedByAm); 493 pw.print(" waitingToKill="); pw.println(waitingToKill); 494 } 495 if (mDebugging || mCrashing || crashDialog != null || mNotResponding 496 || anrDialog != null || bad) { 497 pw.print(prefix); pw.print("mDebugging="); pw.print(mDebugging); 498 pw.print(" mCrashing="); pw.print(mCrashing); 499 pw.print(" "); pw.print(crashDialog); 500 pw.print(" mNotResponding="); pw.print(mNotResponding); 501 pw.print(" " ); pw.print(anrDialog); 502 pw.print(" bad="); pw.print(bad); 503 504 // mCrashing or mNotResponding is always set before errorReportReceiver 505 if (errorReportReceiver != null) { 506 pw.print(" errorReportReceiver="); 507 pw.print(errorReportReceiver.flattenToShortString()); 508 } 509 pw.println(); 510 } 511 if (whitelistManager) { 512 pw.print(prefix); pw.print("whitelistManager="); pw.println(whitelistManager); 513 } 514 if (isolatedEntryPoint != null || isolatedEntryPointArgs != null) { 515 pw.print(prefix); pw.print("isolatedEntryPoint="); pw.println(isolatedEntryPoint); 516 pw.print(prefix); pw.print("isolatedEntryPointArgs="); 517 pw.println(Arrays.toString(isolatedEntryPointArgs)); 518 } 519 mWindowProcessController.dump(pw, prefix); 520 if (services.size() > 0) { 521 pw.print(prefix); pw.println("Services:"); 522 for (int i=0; i<services.size(); i++) { 523 pw.print(prefix); pw.print(" - "); pw.println(services.valueAt(i)); 524 } 525 } 526 if (executingServices.size() > 0) { 527 pw.print(prefix); pw.print("Executing Services (fg="); 528 pw.print(execServicesFg); pw.println(")"); 529 for (int i=0; i<executingServices.size(); i++) { 530 pw.print(prefix); pw.print(" - "); pw.println(executingServices.valueAt(i)); 531 } 532 } 533 if (connections.size() > 0) { 534 pw.print(prefix); pw.println("Connections:"); 535 for (int i=0; i<connections.size(); i++) { 536 pw.print(prefix); pw.print(" - "); pw.println(connections.valueAt(i)); 537 } 538 } 539 if (pubProviders.size() > 0) { 540 pw.print(prefix); pw.println("Published Providers:"); 541 for (int i=0; i<pubProviders.size(); i++) { 542 pw.print(prefix); pw.print(" - "); pw.println(pubProviders.keyAt(i)); 543 pw.print(prefix); pw.print(" -> "); pw.println(pubProviders.valueAt(i)); 544 } 545 } 546 if (conProviders.size() > 0) { 547 pw.print(prefix); pw.println("Connected Providers:"); 548 for (int i=0; i<conProviders.size(); i++) { 549 pw.print(prefix); pw.print(" - "); pw.println(conProviders.get(i).toShortString()); 550 } 551 } 552 if (!curReceivers.isEmpty()) { 553 pw.print(prefix); pw.println("Current Receivers:"); 554 for (int i=0; i < curReceivers.size(); i++) { 555 pw.print(prefix); pw.print(" - "); pw.println(curReceivers.valueAt(i)); 556 } 557 } 558 if (receivers.size() > 0) { 559 pw.print(prefix); pw.println("Receivers:"); 560 for (int i=0; i<receivers.size(); i++) { 561 pw.print(prefix); pw.print(" - "); pw.println(receivers.valueAt(i)); 562 } 563 } 564 if (mAllowBackgroundActivityStartsTokens.size() > 0) { 565 pw.print(prefix); pw.println("Background activity start whitelist tokens:"); 566 for (int i = 0; i < mAllowBackgroundActivityStartsTokens.size(); i++) { 567 pw.print(prefix); pw.print(" - "); 568 pw.println(mAllowBackgroundActivityStartsTokens.valueAt(i)); 569 } 570 } 571 } 572 ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, int _uid)573 ProcessRecord(ActivityManagerService _service, ApplicationInfo _info, String _processName, 574 int _uid) { 575 mService = _service; 576 info = _info; 577 isolated = _info.uid != _uid; 578 appZygote = (UserHandle.getAppId(_uid) >= Process.FIRST_APP_ZYGOTE_ISOLATED_UID 579 && UserHandle.getAppId(_uid) <= Process.LAST_APP_ZYGOTE_ISOLATED_UID); 580 uid = _uid; 581 userId = UserHandle.getUserId(_uid); 582 processName = _processName; 583 maxAdj = ProcessList.UNKNOWN_ADJ; 584 mCurRawAdj = setRawAdj = ProcessList.INVALID_ADJ; 585 curAdj = setAdj = verifiedAdj = ProcessList.INVALID_ADJ; 586 mPersistent = false; 587 removed = false; 588 lastStateTime = lastPssTime = nextPssTime = SystemClock.uptimeMillis(); 589 mWindowProcessController = new WindowProcessController( 590 mService.mActivityTaskManager, info, processName, uid, userId, this, this); 591 pkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.longVersionCode)); 592 } 593 setPid(int _pid)594 public void setPid(int _pid) { 595 pid = _pid; 596 mWindowProcessController.setPid(pid); 597 procStatFile = null; 598 shortStringName = null; 599 stringName = null; 600 } 601 makeActive(IApplicationThread _thread, ProcessStatsService tracker)602 public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) { 603 if (thread == null) { 604 final ProcessState origBase = baseProcessTracker; 605 if (origBase != null) { 606 origBase.setState(ProcessStats.STATE_NOTHING, 607 tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList.mPkgList); 608 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) { 609 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED, 610 uid, processName, pkgList.keyAt(ipkg), 611 ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING), 612 pkgList.valueAt(ipkg).appVersion); 613 } 614 origBase.makeInactive(); 615 } 616 baseProcessTracker = tracker.getProcessStateLocked(info.packageName, info.uid, 617 info.longVersionCode, processName); 618 baseProcessTracker.makeActive(); 619 for (int i=0; i<pkgList.size(); i++) { 620 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i); 621 if (holder.state != null && holder.state != origBase) { 622 holder.state.makeInactive(); 623 } 624 tracker.updateProcessStateHolderLocked(holder, pkgList.keyAt(i), info.uid, 625 info.longVersionCode, processName); 626 if (holder.state != baseProcessTracker) { 627 holder.state.makeActive(); 628 } 629 } 630 } 631 thread = _thread; 632 mWindowProcessController.setThread(thread); 633 } 634 makeInactive(ProcessStatsService tracker)635 public void makeInactive(ProcessStatsService tracker) { 636 thread = null; 637 mWindowProcessController.setThread(null); 638 final ProcessState origBase = baseProcessTracker; 639 if (origBase != null) { 640 if (origBase != null) { 641 origBase.setState(ProcessStats.STATE_NOTHING, 642 tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList.mPkgList); 643 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) { 644 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED, 645 uid, processName, pkgList.keyAt(ipkg), 646 ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING), 647 pkgList.valueAt(ipkg).appVersion); 648 } 649 origBase.makeInactive(); 650 } 651 baseProcessTracker = null; 652 for (int i=0; i<pkgList.size(); i++) { 653 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i); 654 if (holder.state != null && holder.state != origBase) { 655 holder.state.makeInactive(); 656 } 657 holder.pkg = null; 658 holder.state = null; 659 } 660 } 661 } 662 hasActivities()663 boolean hasActivities() { 664 return mWindowProcessController.hasActivities(); 665 } 666 hasActivitiesOrRecentTasks()667 boolean hasActivitiesOrRecentTasks() { 668 return mWindowProcessController.hasActivitiesOrRecentTasks(); 669 } 670 hasRecentTasks()671 boolean hasRecentTasks() { 672 return mWindowProcessController.hasRecentTasks(); 673 } 674 675 /** 676 * This method returns true if any of the activities within the process record are interesting 677 * to the user. See HistoryRecord.isInterestingToUserLocked() 678 */ isInterestingToUserLocked()679 public boolean isInterestingToUserLocked() { 680 if (mWindowProcessController.isInterestingToUser()) { 681 return true; 682 } 683 684 final int servicesSize = services.size(); 685 for (int i = 0; i < servicesSize; i++) { 686 ServiceRecord r = services.valueAt(i); 687 if (r.isForeground) { 688 return true; 689 } 690 } 691 return false; 692 } 693 unlinkDeathRecipient()694 public void unlinkDeathRecipient() { 695 if (deathRecipient != null && thread != null) { 696 thread.asBinder().unlinkToDeath(deathRecipient, 0); 697 } 698 deathRecipient = null; 699 } 700 updateHasAboveClientLocked()701 void updateHasAboveClientLocked() { 702 hasAboveClient = false; 703 for (int i=connections.size()-1; i>=0; i--) { 704 ConnectionRecord cr = connections.valueAt(i); 705 if ((cr.flags&Context.BIND_ABOVE_CLIENT) != 0) { 706 hasAboveClient = true; 707 break; 708 } 709 } 710 } 711 modifyRawOomAdj(int adj)712 int modifyRawOomAdj(int adj) { 713 if (hasAboveClient) { 714 // If this process has bound to any services with BIND_ABOVE_CLIENT, 715 // then we need to drop its adjustment to be lower than the service's 716 // in order to honor the request. We want to drop it by one adjustment 717 // level... but there is special meaning applied to various levels so 718 // we will skip some of them. 719 if (adj < ProcessList.FOREGROUND_APP_ADJ) { 720 // System process will not get dropped, ever 721 } else if (adj < ProcessList.VISIBLE_APP_ADJ) { 722 adj = ProcessList.VISIBLE_APP_ADJ; 723 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) { 724 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 725 } else if (adj < ProcessList.PERCEPTIBLE_LOW_APP_ADJ) { 726 adj = ProcessList.PERCEPTIBLE_LOW_APP_ADJ; 727 } else if (adj < ProcessList.CACHED_APP_MIN_ADJ) { 728 adj = ProcessList.CACHED_APP_MIN_ADJ; 729 } else if (adj < ProcessList.CACHED_APP_MAX_ADJ) { 730 adj++; 731 } 732 } 733 return adj; 734 } 735 scheduleCrash(String message)736 void scheduleCrash(String message) { 737 // Checking killedbyAm should keep it from showing the crash dialog if the process 738 // was already dead for a good / normal reason. 739 if (!killedByAm) { 740 if (thread != null) { 741 if (pid == Process.myPid()) { 742 Slog.w(TAG, "scheduleCrash: trying to crash system process!"); 743 return; 744 } 745 long ident = Binder.clearCallingIdentity(); 746 try { 747 thread.scheduleCrash(message); 748 } catch (RemoteException e) { 749 // If it's already dead our work is done. If it's wedged just kill it. 750 // We won't get the crash dialog or the error reporting. 751 kill("scheduleCrash for '" + message + "' failed", true); 752 } finally { 753 Binder.restoreCallingIdentity(ident); 754 } 755 } 756 } 757 } 758 kill(String reason, boolean noisy)759 void kill(String reason, boolean noisy) { 760 if (!killedByAm) { 761 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill"); 762 if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) { 763 mService.reportUidInfoMessageLocked(TAG, 764 "Killing " + toShortString() + " (adj " + setAdj + "): " + reason, 765 info.uid); 766 } 767 if (pid > 0) { 768 EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason); 769 Process.killProcessQuiet(pid); 770 ProcessList.killProcessGroup(uid, pid); 771 } else { 772 pendingStart = false; 773 } 774 if (!mPersistent) { 775 killed = true; 776 killedByAm = true; 777 } 778 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 779 } 780 } 781 782 @Override writeToProto(ProtoOutputStream proto, long fieldId)783 public void writeToProto(ProtoOutputStream proto, long fieldId) { 784 writeToProto(proto, fieldId, -1); 785 } 786 writeToProto(ProtoOutputStream proto, long fieldId, int lruIndex)787 public void writeToProto(ProtoOutputStream proto, long fieldId, int lruIndex) { 788 long token = proto.start(fieldId); 789 proto.write(ProcessRecordProto.PID, pid); 790 proto.write(ProcessRecordProto.PROCESS_NAME, processName); 791 proto.write(ProcessRecordProto.UID, info.uid); 792 if (UserHandle.getAppId(info.uid) >= Process.FIRST_APPLICATION_UID) { 793 proto.write(ProcessRecordProto.USER_ID, userId); 794 proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid)); 795 } 796 if (uid != info.uid) { 797 proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid)); 798 } 799 proto.write(ProcessRecordProto.PERSISTENT, mPersistent); 800 if (lruIndex >= 0) { 801 proto.write(ProcessRecordProto.LRU_INDEX, lruIndex); 802 } 803 proto.end(token); 804 } 805 toShortString()806 public String toShortString() { 807 if (shortStringName != null) { 808 return shortStringName; 809 } 810 StringBuilder sb = new StringBuilder(128); 811 toShortString(sb); 812 return shortStringName = sb.toString(); 813 } 814 toShortString(StringBuilder sb)815 void toShortString(StringBuilder sb) { 816 sb.append(pid); 817 sb.append(':'); 818 sb.append(processName); 819 sb.append('/'); 820 if (info.uid < Process.FIRST_APPLICATION_UID) { 821 sb.append(uid); 822 } else { 823 sb.append('u'); 824 sb.append(userId); 825 int appId = UserHandle.getAppId(info.uid); 826 if (appId >= Process.FIRST_APPLICATION_UID) { 827 sb.append('a'); 828 sb.append(appId - Process.FIRST_APPLICATION_UID); 829 } else { 830 sb.append('s'); 831 sb.append(appId); 832 } 833 if (uid != info.uid) { 834 sb.append('i'); 835 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID); 836 } 837 } 838 } 839 toString()840 public String toString() { 841 if (stringName != null) { 842 return stringName; 843 } 844 StringBuilder sb = new StringBuilder(128); 845 sb.append("ProcessRecord{"); 846 sb.append(Integer.toHexString(System.identityHashCode(this))); 847 sb.append(' '); 848 toShortString(sb); 849 sb.append('}'); 850 return stringName = sb.toString(); 851 } 852 makeAdjReason()853 public String makeAdjReason() { 854 if (adjSource != null || adjTarget != null) { 855 StringBuilder sb = new StringBuilder(128); 856 sb.append(' '); 857 if (adjTarget instanceof ComponentName) { 858 sb.append(((ComponentName)adjTarget).flattenToShortString()); 859 } else if (adjTarget != null) { 860 sb.append(adjTarget.toString()); 861 } else { 862 sb.append("{null}"); 863 } 864 sb.append("<="); 865 if (adjSource instanceof ProcessRecord) { 866 sb.append("Proc{"); 867 sb.append(((ProcessRecord)adjSource).toShortString()); 868 sb.append("}"); 869 } else if (adjSource != null) { 870 sb.append(adjSource.toString()); 871 } else { 872 sb.append("{null}"); 873 } 874 return sb.toString(); 875 } 876 return null; 877 } 878 879 /* 880 * Return true if package has been added false if not 881 */ addPackage(String pkg, long versionCode, ProcessStatsService tracker)882 public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) { 883 if (!pkgList.containsKey(pkg)) { 884 ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder( 885 versionCode); 886 if (baseProcessTracker != null) { 887 tracker.updateProcessStateHolderLocked(holder, pkg, info.uid, versionCode, 888 processName); 889 pkgList.put(pkg, holder); 890 if (holder.state != baseProcessTracker) { 891 holder.state.makeActive(); 892 } 893 } else { 894 pkgList.put(pkg, holder); 895 } 896 return true; 897 } 898 return false; 899 } 900 getSetAdjWithServices()901 public int getSetAdjWithServices() { 902 if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 903 if (hasStartedServices) { 904 return ProcessList.SERVICE_B_ADJ; 905 } 906 } 907 return setAdj; 908 } 909 forceProcessStateUpTo(int newState)910 public void forceProcessStateUpTo(int newState) { 911 if (mRepProcState > newState) { 912 mRepProcState = newState; 913 setCurProcState(newState); 914 setCurRawProcState(newState); 915 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) { 916 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED, 917 uid, processName, pkgList.keyAt(ipkg), 918 ActivityManager.processStateAmToProto(mRepProcState), 919 pkgList.valueAt(ipkg).appVersion); 920 } 921 } 922 } 923 924 /* 925 * Delete all packages from list except the package indicated in info 926 */ resetPackageList(ProcessStatsService tracker)927 public void resetPackageList(ProcessStatsService tracker) { 928 final int N = pkgList.size(); 929 if (baseProcessTracker != null) { 930 long now = SystemClock.uptimeMillis(); 931 baseProcessTracker.setState(ProcessStats.STATE_NOTHING, 932 tracker.getMemFactorLocked(), now, pkgList.mPkgList); 933 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) { 934 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED, 935 uid, processName, pkgList.keyAt(ipkg), 936 ActivityManager.processStateAmToProto(ProcessStats.STATE_NOTHING), 937 pkgList.valueAt(ipkg).appVersion); 938 } 939 if (N != 1) { 940 for (int i=0; i<N; i++) { 941 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i); 942 if (holder.state != null && holder.state != baseProcessTracker) { 943 holder.state.makeInactive(); 944 } 945 946 } 947 pkgList.clear(); 948 ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder( 949 info.longVersionCode); 950 tracker.updateProcessStateHolderLocked(holder, info.packageName, info.uid, 951 info.longVersionCode, processName); 952 pkgList.put(info.packageName, holder); 953 if (holder.state != baseProcessTracker) { 954 holder.state.makeActive(); 955 } 956 } 957 } else if (N != 1) { 958 pkgList.clear(); 959 pkgList.put(info.packageName, new ProcessStats.ProcessStateHolder(info.longVersionCode)); 960 } 961 } 962 getPackageList()963 public String[] getPackageList() { 964 int size = pkgList.size(); 965 if (size == 0) { 966 return null; 967 } 968 String list[] = new String[size]; 969 for (int i=0; i<pkgList.size(); i++) { 970 list[i] = pkgList.keyAt(i); 971 } 972 return list; 973 } 974 getPackageListWithVersionCode()975 public List<VersionedPackage> getPackageListWithVersionCode() { 976 int size = pkgList.size(); 977 if (size == 0) { 978 return null; 979 } 980 List<VersionedPackage> list = new ArrayList<>(); 981 for (int i = 0; i < pkgList.size(); i++) { 982 list.add(new VersionedPackage(pkgList.keyAt(i), pkgList.valueAt(i).appVersion)); 983 } 984 return list; 985 } 986 getWindowProcessController()987 WindowProcessController getWindowProcessController() { 988 return mWindowProcessController; 989 } 990 setCurrentSchedulingGroup(int curSchedGroup)991 void setCurrentSchedulingGroup(int curSchedGroup) { 992 mCurSchedGroup = curSchedGroup; 993 mWindowProcessController.setCurrentSchedulingGroup(curSchedGroup); 994 } 995 getCurrentSchedulingGroup()996 int getCurrentSchedulingGroup() { 997 return mCurSchedGroup; 998 } 999 setCurProcState(int curProcState)1000 void setCurProcState(int curProcState) { 1001 mCurProcState = curProcState; 1002 mWindowProcessController.setCurrentProcState(mCurProcState); 1003 } 1004 getCurProcState()1005 int getCurProcState() { 1006 return mCurProcState; 1007 } 1008 setCurRawProcState(int curRawProcState)1009 void setCurRawProcState(int curRawProcState) { 1010 mCurRawProcState = curRawProcState; 1011 } 1012 getCurRawProcState()1013 int getCurRawProcState() { 1014 return mCurRawProcState; 1015 } 1016 setReportedProcState(int repProcState)1017 void setReportedProcState(int repProcState) { 1018 mRepProcState = repProcState; 1019 for (int ipkg = pkgList.size() - 1; ipkg >= 0; ipkg--) { 1020 StatsLog.write(StatsLog.PROCESS_STATE_CHANGED, 1021 uid, processName, pkgList.keyAt(ipkg), 1022 ActivityManager.processStateAmToProto(mRepProcState), 1023 pkgList.valueAt(ipkg).appVersion); 1024 } 1025 mWindowProcessController.setReportedProcState(repProcState); 1026 } 1027 getReportedProcState()1028 int getReportedProcState() { 1029 return mRepProcState; 1030 } 1031 setCrashing(boolean crashing)1032 void setCrashing(boolean crashing) { 1033 mCrashing = crashing; 1034 mWindowProcessController.setCrashing(crashing); 1035 } 1036 isCrashing()1037 boolean isCrashing() { 1038 return mCrashing; 1039 } 1040 setNotResponding(boolean notResponding)1041 void setNotResponding(boolean notResponding) { 1042 mNotResponding = notResponding; 1043 mWindowProcessController.setNotResponding(notResponding); 1044 } 1045 isNotResponding()1046 boolean isNotResponding() { 1047 return mNotResponding; 1048 } 1049 setPersistent(boolean persistent)1050 void setPersistent(boolean persistent) { 1051 mPersistent = persistent; 1052 mWindowProcessController.setPersistent(persistent); 1053 } 1054 isPersistent()1055 boolean isPersistent() { 1056 return mPersistent; 1057 } 1058 setRequiredAbi(String requiredAbi)1059 public void setRequiredAbi(String requiredAbi) { 1060 mRequiredAbi = requiredAbi; 1061 mWindowProcessController.setRequiredAbi(requiredAbi); 1062 } 1063 getRequiredAbi()1064 String getRequiredAbi() { 1065 return mRequiredAbi; 1066 } 1067 setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes)1068 void setHasForegroundServices(boolean hasForegroundServices, int fgServiceTypes) { 1069 mHasForegroundServices = hasForegroundServices; 1070 mFgServiceTypes = fgServiceTypes; 1071 mWindowProcessController.setHasForegroundServices(hasForegroundServices); 1072 } 1073 hasForegroundServices()1074 boolean hasForegroundServices() { 1075 return mHasForegroundServices; 1076 } 1077 hasLocationForegroundServices()1078 boolean hasLocationForegroundServices() { 1079 return mHasForegroundServices 1080 && (mFgServiceTypes & ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION) != 0; 1081 } 1082 getForegroundServiceTypes()1083 int getForegroundServiceTypes() { 1084 return mHasForegroundServices ? mFgServiceTypes : 0; 1085 } 1086 getReportedForegroundServiceTypes()1087 int getReportedForegroundServiceTypes() { 1088 return mRepFgServiceTypes; 1089 } 1090 setReportedForegroundServiceTypes(int foregroundServiceTypes)1091 void setReportedForegroundServiceTypes(int foregroundServiceTypes) { 1092 mRepFgServiceTypes = foregroundServiceTypes; 1093 } 1094 setHasForegroundActivities(boolean hasForegroundActivities)1095 void setHasForegroundActivities(boolean hasForegroundActivities) { 1096 mHasForegroundActivities = hasForegroundActivities; 1097 mWindowProcessController.setHasForegroundActivities(hasForegroundActivities); 1098 } 1099 hasForegroundActivities()1100 boolean hasForegroundActivities() { 1101 return mHasForegroundActivities; 1102 } 1103 setHasClientActivities(boolean hasClientActivities)1104 void setHasClientActivities(boolean hasClientActivities) { 1105 mHasClientActivities = hasClientActivities; 1106 mWindowProcessController.setHasClientActivities(hasClientActivities); 1107 } 1108 hasClientActivities()1109 boolean hasClientActivities() { 1110 return mHasClientActivities; 1111 } 1112 setHasTopUi(boolean hasTopUi)1113 void setHasTopUi(boolean hasTopUi) { 1114 mHasTopUi = hasTopUi; 1115 mWindowProcessController.setHasTopUi(hasTopUi); 1116 } 1117 hasTopUi()1118 boolean hasTopUi() { 1119 return mHasTopUi; 1120 } 1121 setHasOverlayUi(boolean hasOverlayUi)1122 void setHasOverlayUi(boolean hasOverlayUi) { 1123 mHasOverlayUi = hasOverlayUi; 1124 mWindowProcessController.setHasOverlayUi(hasOverlayUi); 1125 } 1126 hasOverlayUi()1127 boolean hasOverlayUi() { 1128 return mHasOverlayUi; 1129 } 1130 setInteractionEventTime(long interactionEventTime)1131 void setInteractionEventTime(long interactionEventTime) { 1132 mInteractionEventTime = interactionEventTime; 1133 mWindowProcessController.setInteractionEventTime(interactionEventTime); 1134 } 1135 getInteractionEventTime()1136 long getInteractionEventTime() { 1137 return mInteractionEventTime; 1138 } 1139 setFgInteractionTime(long fgInteractionTime)1140 void setFgInteractionTime(long fgInteractionTime) { 1141 mFgInteractionTime = fgInteractionTime; 1142 mWindowProcessController.setFgInteractionTime(fgInteractionTime); 1143 } 1144 getFgInteractionTime()1145 long getFgInteractionTime() { 1146 return mFgInteractionTime; 1147 } 1148 setWhenUnimportant(long whenUnimportant)1149 void setWhenUnimportant(long whenUnimportant) { 1150 mWhenUnimportant = whenUnimportant; 1151 mWindowProcessController.setWhenUnimportant(whenUnimportant); 1152 } 1153 getWhenUnimportant()1154 long getWhenUnimportant() { 1155 return mWhenUnimportant; 1156 } 1157 setDebugging(boolean debugging)1158 void setDebugging(boolean debugging) { 1159 mDebugging = debugging; 1160 mWindowProcessController.setDebugging(debugging); 1161 } 1162 isDebugging()1163 boolean isDebugging() { 1164 return mDebugging; 1165 } 1166 setUsingWrapper(boolean usingWrapper)1167 void setUsingWrapper(boolean usingWrapper) { 1168 mUsingWrapper = usingWrapper; 1169 mWindowProcessController.setUsingWrapper(usingWrapper); 1170 } 1171 isUsingWrapper()1172 boolean isUsingWrapper() { 1173 return mUsingWrapper; 1174 } 1175 addAllowBackgroundActivityStartsToken(Binder entity)1176 void addAllowBackgroundActivityStartsToken(Binder entity) { 1177 if (entity == null) return; 1178 mAllowBackgroundActivityStartsTokens.add(entity); 1179 mWindowProcessController.setAllowBackgroundActivityStarts(true); 1180 } 1181 removeAllowBackgroundActivityStartsToken(Binder entity)1182 void removeAllowBackgroundActivityStartsToken(Binder entity) { 1183 if (entity == null) return; 1184 mAllowBackgroundActivityStartsTokens.remove(entity); 1185 mWindowProcessController.setAllowBackgroundActivityStarts( 1186 !mAllowBackgroundActivityStartsTokens.isEmpty()); 1187 } 1188 addBoundClientUid(int clientUid)1189 void addBoundClientUid(int clientUid) { 1190 mBoundClientUids.add(clientUid); 1191 mWindowProcessController.setBoundClientUids(mBoundClientUids); 1192 } 1193 updateBoundClientUids()1194 void updateBoundClientUids() { 1195 if (services.isEmpty()) { 1196 clearBoundClientUids(); 1197 return; 1198 } 1199 // grab a set of clientUids of all connections of all services 1200 ArraySet<Integer> boundClientUids = new ArraySet<>(); 1201 final int K = services.size(); 1202 for (int j = 0; j < K; j++) { 1203 ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns = 1204 services.valueAt(j).getConnections(); 1205 final int N = conns.size(); 1206 for (int conni = 0; conni < N; conni++) { 1207 ArrayList<ConnectionRecord> c = conns.valueAt(conni); 1208 for (int i = 0; i < c.size(); i++) { 1209 boundClientUids.add(c.get(i).clientUid); 1210 } 1211 } 1212 } 1213 mBoundClientUids = boundClientUids; 1214 mWindowProcessController.setBoundClientUids(mBoundClientUids); 1215 } 1216 addBoundClientUidsOfNewService(ServiceRecord sr)1217 void addBoundClientUidsOfNewService(ServiceRecord sr) { 1218 if (sr == null) { 1219 return; 1220 } 1221 ArrayMap<IBinder, ArrayList<ConnectionRecord>> conns = sr.getConnections(); 1222 for (int conni = conns.size() - 1; conni >= 0; conni--) { 1223 ArrayList<ConnectionRecord> c = conns.valueAt(conni); 1224 for (int i = 0; i < c.size(); i++) { 1225 mBoundClientUids.add(c.get(i).clientUid); 1226 } 1227 } 1228 mWindowProcessController.setBoundClientUids(mBoundClientUids); 1229 } 1230 clearBoundClientUids()1231 void clearBoundClientUids() { 1232 mBoundClientUids.clear(); 1233 mWindowProcessController.setBoundClientUids(mBoundClientUids); 1234 } 1235 setActiveInstrumentation(ActiveInstrumentation instr)1236 void setActiveInstrumentation(ActiveInstrumentation instr) { 1237 mInstr = instr; 1238 boolean isInstrumenting = instr != null; 1239 mWindowProcessController.setInstrumenting(isInstrumenting, 1240 isInstrumenting && instr.mHasBackgroundActivityStartsPermission); 1241 } 1242 getActiveInstrumentation()1243 ActiveInstrumentation getActiveInstrumentation() { 1244 return mInstr; 1245 } 1246 setCurRawAdj(int curRawAdj)1247 void setCurRawAdj(int curRawAdj) { 1248 mCurRawAdj = curRawAdj; 1249 mWindowProcessController.setPerceptible(curRawAdj <= ProcessList.PERCEPTIBLE_APP_ADJ); 1250 } 1251 getCurRawAdj()1252 int getCurRawAdj() { 1253 return mCurRawAdj; 1254 } 1255 1256 @Override clearProfilerIfNeeded()1257 public void clearProfilerIfNeeded() { 1258 synchronized (mService) { 1259 if (mService.mProfileData.getProfileProc() == null 1260 || mService.mProfileData.getProfilerInfo() == null 1261 || mService.mProfileData.getProfileProc() != this) { 1262 return; 1263 } 1264 mService.clearProfilerLocked(); 1265 } 1266 } 1267 1268 @Override updateServiceConnectionActivities()1269 public void updateServiceConnectionActivities() { 1270 synchronized (mService) { 1271 mService.mServices.updateServiceConnectionActivitiesLocked(this); 1272 } 1273 } 1274 1275 @Override setPendingUiClean(boolean pendingUiClean)1276 public void setPendingUiClean(boolean pendingUiClean) { 1277 synchronized (mService) { 1278 mPendingUiClean = pendingUiClean; 1279 mWindowProcessController.setPendingUiClean(pendingUiClean); 1280 } 1281 } 1282 hasPendingUiClean()1283 boolean hasPendingUiClean() { 1284 return mPendingUiClean; 1285 } 1286 1287 @Override setPendingUiCleanAndForceProcessStateUpTo(int newState)1288 public void setPendingUiCleanAndForceProcessStateUpTo(int newState) { 1289 synchronized (mService) { 1290 setPendingUiClean(true); 1291 forceProcessStateUpTo(newState); 1292 } 1293 } 1294 1295 @Override updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, boolean updateOomAdj)1296 public void updateProcessInfo(boolean updateServiceConnectionActivities, boolean activityChange, 1297 boolean updateOomAdj) { 1298 synchronized (mService) { 1299 if (updateServiceConnectionActivities) { 1300 mService.mServices.updateServiceConnectionActivitiesLocked(this); 1301 } 1302 mService.mProcessList.updateLruProcessLocked(this, activityChange, null /* client */); 1303 if (updateOomAdj) { 1304 mService.updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_ACTIVITY); 1305 } 1306 } 1307 } 1308 1309 @Override isRemoved()1310 public boolean isRemoved() { 1311 return removed; 1312 } 1313 1314 /** 1315 * Returns the total time (in milliseconds) spent executing in both user and system code. 1316 * Safe to call without lock held. 1317 */ 1318 @Override getCpuTime()1319 public long getCpuTime() { 1320 return mService.mProcessCpuTracker.getCpuTimeForPid(pid); 1321 } 1322 1323 @Override onStartActivity(int topProcessState, boolean setProfileProc, String packageName, long versionCode)1324 public void onStartActivity(int topProcessState, boolean setProfileProc, String packageName, 1325 long versionCode) { 1326 synchronized (mService) { 1327 waitingToKill = null; 1328 if (setProfileProc) { 1329 mService.mProfileData.setProfileProc(this); 1330 } 1331 if (packageName != null) { 1332 addPackage(packageName, versionCode, mService.mProcessStats); 1333 } 1334 1335 // Update oom adj first, we don't want the additional states are involved in this round. 1336 updateProcessInfo(false /* updateServiceConnectionActivities */, 1337 true /* activityChange */, true /* updateOomAdj */); 1338 hasShownUi = true; 1339 setPendingUiClean(true); 1340 forceProcessStateUpTo(topProcessState); 1341 } 1342 } 1343 1344 @Override appDied()1345 public void appDied() { 1346 synchronized (mService) { 1347 mService.appDiedLocked(this); 1348 } 1349 } 1350 getInputDispatchingTimeout()1351 public long getInputDispatchingTimeout() { 1352 return mWindowProcessController.getInputDispatchingTimeout(); 1353 } 1354 getProcessClassEnum()1355 public int getProcessClassEnum() { 1356 if (pid == MY_PID) { 1357 return ServerProtoEnums.SYSTEM_SERVER; 1358 } 1359 if (info == null) { 1360 return ServerProtoEnums.ERROR_SOURCE_UNKNOWN; 1361 } 1362 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? ServerProtoEnums.SYSTEM_APP : 1363 ServerProtoEnums.DATA_APP; 1364 } 1365 1366 /** 1367 * Unless configured otherwise, swallow ANRs in background processes & kill the process. 1368 * Non-private access is for tests only. 1369 */ 1370 @VisibleForTesting isSilentAnr()1371 boolean isSilentAnr() { 1372 return !getShowBackground() && !isInterestingForBackgroundTraces(); 1373 } 1374 1375 /** Non-private access is for tests only. */ 1376 @VisibleForTesting getLruProcessList()1377 List<ProcessRecord> getLruProcessList() { 1378 return mService.mProcessList.mLruProcesses; 1379 } 1380 1381 /** Non-private access is for tests only. */ 1382 @VisibleForTesting isMonitorCpuUsage()1383 boolean isMonitorCpuUsage() { 1384 return mService.MONITOR_CPU_USAGE; 1385 } 1386 appNotResponding(String activityShortComponentName, ApplicationInfo aInfo, String parentShortComponentName, WindowProcessController parentProcess, boolean aboveSystem, String annotation)1387 void appNotResponding(String activityShortComponentName, ApplicationInfo aInfo, 1388 String parentShortComponentName, WindowProcessController parentProcess, 1389 boolean aboveSystem, String annotation) { 1390 ArrayList<Integer> firstPids = new ArrayList<>(5); 1391 SparseArray<Boolean> lastPids = new SparseArray<>(20); 1392 1393 mWindowProcessController.appEarlyNotResponding(annotation, () -> kill("anr", true)); 1394 1395 long anrTime = SystemClock.uptimeMillis(); 1396 if (isMonitorCpuUsage()) { 1397 mService.updateCpuStatsNow(); 1398 } 1399 1400 synchronized (mService) { 1401 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 1402 if (mService.mAtmInternal.isShuttingDown()) { 1403 Slog.i(TAG, "During shutdown skipping ANR: " + this + " " + annotation); 1404 return; 1405 } else if (isNotResponding()) { 1406 Slog.i(TAG, "Skipping duplicate ANR: " + this + " " + annotation); 1407 return; 1408 } else if (isCrashing()) { 1409 Slog.i(TAG, "Crashing app skipping ANR: " + this + " " + annotation); 1410 return; 1411 } else if (killedByAm) { 1412 Slog.i(TAG, "App already killed by AM skipping ANR: " + this + " " + annotation); 1413 return; 1414 } else if (killed) { 1415 Slog.i(TAG, "Skipping died app ANR: " + this + " " + annotation); 1416 return; 1417 } 1418 1419 // In case we come through here for the same app before completing 1420 // this one, mark as anring now so we will bail out. 1421 setNotResponding(true); 1422 1423 // Log the ANR to the event log. 1424 EventLog.writeEvent(EventLogTags.AM_ANR, userId, pid, processName, info.flags, 1425 annotation); 1426 1427 // Dump thread traces as quickly as we can, starting with "interesting" processes. 1428 firstPids.add(pid); 1429 1430 // Don't dump other PIDs if it's a background ANR 1431 if (!isSilentAnr()) { 1432 int parentPid = pid; 1433 if (parentProcess != null && parentProcess.getPid() > 0) { 1434 parentPid = parentProcess.getPid(); 1435 } 1436 if (parentPid != pid) firstPids.add(parentPid); 1437 1438 if (MY_PID != pid && MY_PID != parentPid) firstPids.add(MY_PID); 1439 1440 for (int i = getLruProcessList().size() - 1; i >= 0; i--) { 1441 ProcessRecord r = getLruProcessList().get(i); 1442 if (r != null && r.thread != null) { 1443 int myPid = r.pid; 1444 if (myPid > 0 && myPid != pid && myPid != parentPid && myPid != MY_PID) { 1445 if (r.isPersistent()) { 1446 firstPids.add(myPid); 1447 if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r); 1448 } else if (r.treatLikeActivity) { 1449 firstPids.add(myPid); 1450 if (DEBUG_ANR) Slog.i(TAG, "Adding likely IME: " + r); 1451 } else { 1452 lastPids.put(myPid, Boolean.TRUE); 1453 if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r); 1454 } 1455 } 1456 } 1457 } 1458 } 1459 } 1460 1461 // Log the ANR to the main log. 1462 StringBuilder info = new StringBuilder(); 1463 info.setLength(0); 1464 info.append("ANR in ").append(processName); 1465 if (activityShortComponentName != null) { 1466 info.append(" (").append(activityShortComponentName).append(")"); 1467 } 1468 info.append("\n"); 1469 info.append("PID: ").append(pid).append("\n"); 1470 if (annotation != null) { 1471 info.append("Reason: ").append(annotation).append("\n"); 1472 } 1473 if (parentShortComponentName != null 1474 && parentShortComponentName.equals(activityShortComponentName)) { 1475 info.append("Parent: ").append(parentShortComponentName).append("\n"); 1476 } 1477 1478 ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true); 1479 1480 // don't dump native PIDs for background ANRs unless it is the process of interest 1481 String[] nativeProcs = null; 1482 if (isSilentAnr()) { 1483 for (int i = 0; i < NATIVE_STACKS_OF_INTEREST.length; i++) { 1484 if (NATIVE_STACKS_OF_INTEREST[i].equals(processName)) { 1485 nativeProcs = new String[] { processName }; 1486 break; 1487 } 1488 } 1489 } else { 1490 nativeProcs = NATIVE_STACKS_OF_INTEREST; 1491 } 1492 1493 int[] pids = nativeProcs == null ? null : Process.getPidsForCommands(nativeProcs); 1494 ArrayList<Integer> nativePids = null; 1495 1496 if (pids != null) { 1497 nativePids = new ArrayList<>(pids.length); 1498 for (int i : pids) { 1499 nativePids.add(i); 1500 } 1501 } 1502 1503 // For background ANRs, don't pass the ProcessCpuTracker to 1504 // avoid spending 1/2 second collecting stats to rank lastPids. 1505 File tracesFile = ActivityManagerService.dumpStackTraces(firstPids, 1506 (isSilentAnr()) ? null : processCpuTracker, (isSilentAnr()) ? null : lastPids, 1507 nativePids); 1508 1509 String cpuInfo = null; 1510 if (isMonitorCpuUsage()) { 1511 mService.updateCpuStatsNow(); 1512 synchronized (mService.mProcessCpuTracker) { 1513 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime); 1514 } 1515 info.append(processCpuTracker.printCurrentLoad()); 1516 info.append(cpuInfo); 1517 } 1518 1519 info.append(processCpuTracker.printCurrentState(anrTime)); 1520 1521 Slog.e(TAG, info.toString()); 1522 if (tracesFile == null) { 1523 // There is no trace file, so dump (only) the alleged culprit's threads to the log 1524 Process.sendSignal(pid, Process.SIGNAL_QUIT); 1525 } 1526 1527 StatsLog.write(StatsLog.ANR_OCCURRED, uid, processName, 1528 activityShortComponentName == null ? "unknown": activityShortComponentName, 1529 annotation, 1530 (this.info != null) ? (this.info.isInstantApp() 1531 ? StatsLog.ANROCCURRED__IS_INSTANT_APP__TRUE 1532 : StatsLog.ANROCCURRED__IS_INSTANT_APP__FALSE) 1533 : StatsLog.ANROCCURRED__IS_INSTANT_APP__UNAVAILABLE, 1534 isInterestingToUserLocked() 1535 ? StatsLog.ANROCCURRED__FOREGROUND_STATE__FOREGROUND 1536 : StatsLog.ANROCCURRED__FOREGROUND_STATE__BACKGROUND, 1537 getProcessClassEnum(), 1538 (this.info != null) ? this.info.packageName : ""); 1539 final ProcessRecord parentPr = parentProcess != null 1540 ? (ProcessRecord) parentProcess.mOwner : null; 1541 mService.addErrorToDropBox("anr", this, processName, activityShortComponentName, 1542 parentShortComponentName, parentPr, annotation, cpuInfo, tracesFile, null); 1543 1544 if (mWindowProcessController.appNotResponding(info.toString(), () -> kill("anr", true), 1545 () -> { 1546 synchronized (mService) { 1547 mService.mServices.scheduleServiceTimeoutLocked(this); 1548 } 1549 })) { 1550 return; 1551 } 1552 1553 synchronized (mService) { 1554 // mBatteryStatsService can be null if the AMS is constructed with injector only. This 1555 // will only happen in tests. 1556 if (mService.mBatteryStatsService != null) { 1557 mService.mBatteryStatsService.noteProcessAnr(processName, uid); 1558 } 1559 1560 if (isSilentAnr() && !isDebugging()) { 1561 kill("bg anr", true); 1562 return; 1563 } 1564 1565 // Set the app's notResponding state, and look up the errorReportReceiver 1566 makeAppNotRespondingLocked(activityShortComponentName, 1567 annotation != null ? "ANR " + annotation : "ANR", info.toString()); 1568 1569 // mUiHandler can be null if the AMS is constructed with injector only. This will only 1570 // happen in tests. 1571 if (mService.mUiHandler != null) { 1572 // Bring up the infamous App Not Responding dialog 1573 Message msg = Message.obtain(); 1574 msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG; 1575 msg.obj = new AppNotRespondingDialog.Data(this, aInfo, aboveSystem); 1576 1577 mService.mUiHandler.sendMessage(msg); 1578 } 1579 } 1580 } 1581 makeAppNotRespondingLocked(String activity, String shortMsg, String longMsg)1582 private void makeAppNotRespondingLocked(String activity, String shortMsg, String longMsg) { 1583 setNotResponding(true); 1584 // mAppErrors can be null if the AMS is constructed with injector only. This will only 1585 // happen in tests. 1586 if (mService.mAppErrors != null) { 1587 notRespondingReport = mService.mAppErrors.generateProcessError(this, 1588 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING, 1589 activity, shortMsg, longMsg, null); 1590 } 1591 startAppProblemLocked(); 1592 getWindowProcessController().stopFreezingActivities(); 1593 } 1594 startAppProblemLocked()1595 void startAppProblemLocked() { 1596 // If this app is not running under the current user, then we can't give it a report button 1597 // because that would require launching the report UI under a different user. 1598 errorReportReceiver = null; 1599 1600 for (int userId : mService.mUserController.getCurrentProfileIds()) { 1601 if (this.userId == userId) { 1602 errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver( 1603 mService.mContext, info.packageName, info.flags); 1604 } 1605 } 1606 mService.skipCurrentReceiverLocked(this); 1607 } 1608 isInterestingForBackgroundTraces()1609 private boolean isInterestingForBackgroundTraces() { 1610 // The system_server is always considered interesting. 1611 if (pid == MY_PID) { 1612 return true; 1613 } 1614 1615 // A package is considered interesting if any of the following is true : 1616 // 1617 // - It's displaying an activity. 1618 // - It's the SystemUI. 1619 // - It has an overlay or a top UI visible. 1620 // 1621 // NOTE: The check whether a given ProcessRecord belongs to the systemui 1622 // process is a bit of a kludge, but the same pattern seems repeated at 1623 // several places in the system server. 1624 return isInterestingToUserLocked() || 1625 (info != null && "com.android.systemui".equals(info.packageName)) 1626 || (hasTopUi() || hasOverlayUi()); 1627 } 1628 getShowBackground()1629 private boolean getShowBackground() { 1630 return Settings.Secure.getInt(mService.mContext.getContentResolver(), 1631 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 1632 } 1633 } 1634