Home | History | Annotate | Download | only in am
      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 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
     21 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
     22 
     23 import android.util.ArraySet;
     24 import android.util.DebugUtils;
     25 import android.util.EventLog;
     26 import android.util.Slog;
     27 import com.android.internal.app.procstats.ProcessStats;
     28 import com.android.internal.app.procstats.ProcessState;
     29 import com.android.internal.os.BatteryStatsImpl;
     30 
     31 import android.app.ActivityManager;
     32 import android.app.Dialog;
     33 import android.app.IApplicationThread;
     34 import android.content.ComponentName;
     35 import android.content.Context;
     36 import android.content.pm.ApplicationInfo;
     37 import android.content.res.CompatibilityInfo;
     38 import android.os.Binder;
     39 import android.os.IBinder;
     40 import android.os.Process;
     41 import android.os.RemoteException;
     42 import android.os.SystemClock;
     43 import android.os.Trace;
     44 import android.os.UserHandle;
     45 import android.util.ArrayMap;
     46 import android.util.TimeUtils;
     47 import android.util.proto.ProtoOutputStream;
     48 
     49 import java.io.PrintWriter;
     50 import java.util.ArrayList;
     51 import java.util.Arrays;
     52 
     53 /**
     54  * Full information about a particular process that
     55  * is currently running.
     56  */
     57 final class ProcessRecord {
     58     private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessRecord" : TAG_AM;
     59 
     60     private final ActivityManagerService mService; // where we came from
     61     private final BatteryStatsImpl mBatteryStats; // where to collect runtime statistics
     62     final ApplicationInfo info; // all about the first app in the process
     63     final boolean isolated;     // true if this is a special isolated process
     64     final int uid;              // uid of process; may be different from 'info' if isolated
     65     final int userId;           // user of process.
     66     final String processName;   // name of the process
     67     // List of packages running in the process
     68     final ArrayMap<String, ProcessStats.ProcessStateHolder> pkgList = new ArrayMap<>();
     69     final ProcessList.ProcStateMemTracker procStateMemTracker
     70             = new ProcessList.ProcStateMemTracker();
     71     UidRecord uidRecord;        // overall state of process's uid.
     72     ArraySet<String> pkgDeps;   // additional packages we have a dependency on
     73     IApplicationThread thread;  // the actual proc...  may be null only if
     74                                 // 'persistent' is true (in which case we
     75                                 // are in the process of launching the app)
     76     ProcessState baseProcessTracker;
     77     BatteryStatsImpl.Uid.Proc curProcBatteryStats;
     78     int pid;                    // The process of this application; 0 if none
     79     String procStatFile;        // path to /proc/<pid>/stat
     80     int[] gids;                 // The gids this process was launched with
     81     String requiredAbi;         // The ABI this process was launched with
     82     String instructionSet;      // The instruction set this process was launched with
     83     boolean starting;           // True if the process is being started
     84     long lastActivityTime;      // For managing the LRU list
     85     long lastPssTime;           // Last time we retrieved PSS data
     86     long nextPssTime;           // Next time we want to request PSS data
     87     long lastStateTime;         // Last time setProcState changed
     88     long initialIdlePss;        // Initial memory pss of process for idle maintenance.
     89     long lastPss;               // Last computed memory pss.
     90     long lastSwapPss;           // Last computed SwapPss.
     91     long lastCachedPss;         // Last computed pss when in cached state.
     92     long lastCachedSwapPss;     // Last computed SwapPss when in cached state.
     93     int maxAdj;                 // Maximum OOM adjustment for this process
     94     int curRawAdj;              // Current OOM unlimited adjustment for this process
     95     int setRawAdj;              // Last set OOM unlimited adjustment for this process
     96     int curAdj;                 // Current OOM adjustment for this process
     97     int setAdj;                 // Last set OOM adjustment for this process
     98     int verifiedAdj;            // The last adjustment that was verified as actually being set
     99     int curSchedGroup;          // Currently desired scheduling class
    100     int setSchedGroup;          // Last set to background scheduling class
    101     int vrThreadTid;            // Thread currently set for VR scheduling
    102     int trimMemoryLevel;        // Last selected memory trimming level
    103     int curProcState = PROCESS_STATE_NONEXISTENT; // Currently computed process state
    104     int repProcState = PROCESS_STATE_NONEXISTENT; // Last reported process state
    105     int setProcState = PROCESS_STATE_NONEXISTENT; // Last set process state in process tracker
    106     int pssProcState = PROCESS_STATE_NONEXISTENT; // Currently requesting pss for
    107     int pssStatType;            // The type of stat collection that we are currently requesting
    108     int savedPriority;          // Previous priority value if we're switching to non-SCHED_OTHER
    109     int renderThreadTid;        // TID for RenderThread
    110     boolean serviceb;           // Process currently is on the service B list
    111     boolean serviceHighRam;     // We are forcing to service B list due to its RAM use
    112     boolean notCachedSinceIdle; // Has this process not been in a cached state since last idle?
    113     boolean hasClientActivities;  // Are there any client services with activities?
    114     boolean hasStartedServices; // Are there any started services running in this process?
    115     boolean foregroundServices; // Running any services that are foreground?
    116     boolean foregroundActivities; // Running any activities that are foreground?
    117     boolean repForegroundActivities; // Last reported foreground activities.
    118     boolean systemNoUi;         // This is a system process, but not currently showing UI.
    119     boolean hasShownUi;         // Has UI been shown in this process since it was started?
    120     boolean hasTopUi;           // Is this process currently showing a non-activity UI that the user
    121                                 // is interacting with? E.g. The status bar when it is expanded, but
    122                                 // not when it is minimized. When true the
    123                                 // process will be set to use the ProcessList#SCHED_GROUP_TOP_APP
    124                                 // scheduling group to boost performance.
    125     boolean hasOverlayUi;       // Is the process currently showing a non-activity UI that
    126                                 // overlays on-top of activity UIs on screen. E.g. display a window
    127                                 // of type
    128                                 // android.view.WindowManager.LayoutParams#TYPE_APPLICATION_OVERLAY
    129                                 // When true the process will oom adj score will be set to
    130                                 // ProcessList#PERCEPTIBLE_APP_ADJ at minimum to reduce the chance
    131                                 // of the process getting killed.
    132     boolean runningRemoteAnimation; // Is the process currently running a RemoteAnimation? When true
    133                                 // the process will be set to use the
    134                                 // ProcessList#SCHED_GROUP_TOP_APP scheduling group to boost
    135                                 // performance, as well as oom adj score will be set to
    136                                 // ProcessList#VISIBLE_APP_ADJ at minimum to reduce the chance
    137                                 // of the process getting killed.
    138     boolean pendingUiClean;     // Want to clean up resources from showing UI?
    139     boolean hasAboveClient;     // Bound using BIND_ABOVE_CLIENT, so want to be lower
    140     boolean treatLikeActivity;  // Bound using BIND_TREAT_LIKE_ACTIVITY
    141     boolean bad;                // True if disabled in the bad process list
    142     boolean killedByAm;         // True when proc has been killed by activity manager, not for RAM
    143     boolean killed;             // True once we know the process has been killed
    144     boolean procStateChanged;   // Keep track of whether we changed 'setAdj'.
    145     boolean reportedInteraction;// Whether we have told usage stats about it being an interaction
    146     boolean unlocked;           // True when proc was started in user unlocked state
    147     long interactionEventTime;  // The time we sent the last interaction event
    148     long fgInteractionTime;     // When we became foreground for interaction purposes
    149     String waitingToKill;       // Process is waiting to be killed when in the bg, and reason
    150     Object forcingToImportant;  // Token that is forcing this process to be important
    151     int adjSeq;                 // Sequence id for identifying oom_adj assignment cycles
    152     int completedAdjSeq;        // Sequence id for identifying oom_adj assignment cycles
    153     boolean containsCycle;      // Whether this app has encountered a cycle in the most recent update
    154     int lruSeq;                 // Sequence id for identifying LRU update cycles
    155     CompatibilityInfo compat;   // last used compatibility mode
    156     IBinder.DeathRecipient deathRecipient; // Who is watching for the death.
    157     ActiveInstrumentation instr;// Set to currently active instrumentation running in process
    158     boolean usingWrapper;       // Set to true when process was launched with a wrapper attached
    159     final ArraySet<BroadcastRecord> curReceivers = new ArraySet<BroadcastRecord>();// receivers currently running in the app
    160     long whenUnimportant;       // When (uptime) the process last became unimportant
    161     long lastCpuTime;           // How long proc has run CPU at last check
    162     long curCpuTime;            // How long proc has run CPU most recently
    163     long lastRequestedGc;       // When we last asked the app to do a gc
    164     long lastLowMemory;         // When we last told the app that memory is low
    165     long lastProviderTime;      // The last time someone else was using a provider in this process.
    166     boolean reportLowMemory;    // Set to true when waiting to report low mem
    167     boolean empty;              // Is this an empty background process?
    168     boolean cached;             // Is this a cached process?
    169     String adjType;             // Debugging: primary thing impacting oom_adj.
    170     int adjTypeCode;            // Debugging: adj code to report to app.
    171     Object adjSource;           // Debugging: option dependent object.
    172     int adjSourceProcState;     // Debugging: proc state of adjSource's process.
    173     Object adjTarget;           // Debugging: target component impacting oom_adj.
    174     Runnable crashHandler;      // Optional local handler to be invoked in the process crash.
    175 
    176     // all activities running in the process
    177     final ArrayList<ActivityRecord> activities = new ArrayList<>();
    178     // any tasks this process had run root activities in
    179     final ArrayList<TaskRecord> recentTasks = new ArrayList<>();
    180     // all ServiceRecord running in this process
    181     final ArraySet<ServiceRecord> services = new ArraySet<>();
    182     // services that are currently executing code (need to remain foreground).
    183     final ArraySet<ServiceRecord> executingServices = new ArraySet<>();
    184     // All ConnectionRecord this process holds
    185     final ArraySet<ConnectionRecord> connections = new ArraySet<>();
    186     // all IIntentReceivers that are registered from this process.
    187     final ArraySet<ReceiverList> receivers = new ArraySet<>();
    188     // class (String) -> ContentProviderRecord
    189     final ArrayMap<String, ContentProviderRecord> pubProviders = new ArrayMap<>();
    190     // All ContentProviderRecord process is using
    191     final ArrayList<ContentProviderConnection> conProviders = new ArrayList<>();
    192 
    193     String isolatedEntryPoint;  // Class to run on start if this is a special isolated process.
    194     String[] isolatedEntryPointArgs; // Arguments to pass to isolatedEntryPoint's main().
    195 
    196     boolean execServicesFg;     // do we need to be executing services in the foreground?
    197     boolean persistent;         // always keep this application running?
    198     boolean crashing;           // are we in the process of crashing?
    199     Dialog crashDialog;         // dialog being displayed due to crash.
    200     boolean forceCrashReport;   // suppress normal auto-dismiss of crash dialog & report UI?
    201     boolean notResponding;      // does the app have a not responding dialog?
    202     Dialog anrDialog;           // dialog being displayed due to app not resp.
    203     boolean removed;            // has app package been removed from device?
    204     boolean debugging;          // was app launched for debugging?
    205     boolean waitedForDebugger;  // has process show wait for debugger dialog?
    206     Dialog waitDialog;          // current wait for debugger dialog
    207 
    208     String shortStringName;     // caching of toShortString() result.
    209     String stringName;          // caching of toString() result.
    210     boolean pendingStart;       // Process start is pending.
    211     long startSeq;              // Seq no. indicating the latest process start associated with
    212                                 // this process record.
    213 
    214     // These reports are generated & stored when an app gets into an error condition.
    215     // They will be "null" when all is OK.
    216     ActivityManager.ProcessErrorStateInfo crashingReport;
    217     ActivityManager.ProcessErrorStateInfo notRespondingReport;
    218 
    219     // Who will be notified of the error. This is usually an activity in the
    220     // app that installed the package.
    221     ComponentName errorReportReceiver;
    222 
    223     // Process is currently hosting a backup agent for backup or restore
    224     public boolean inFullBackup;
    225     // App is allowed to manage whitelists such as temporary Power Save mode whitelist.
    226     boolean whitelistManager;
    227 
    228     // Params used in starting this process.
    229     String hostingType;
    230     String hostingNameStr;
    231     String seInfo;
    232     long startTime;
    233     // This will be same as {@link #uid} usually except for some apps used during factory testing.
    234     int startUid;
    235 
    236     void setStartParams(int startUid, String hostingType, String hostingNameStr, String seInfo,
    237             long startTime) {
    238         this.startUid = startUid;
    239         this.hostingType = hostingType;
    240         this.hostingNameStr = hostingNameStr;
    241         this.seInfo = seInfo;
    242         this.startTime = startTime;
    243     }
    244 
    245     void dump(PrintWriter pw, String prefix) {
    246         final long nowUptime = SystemClock.uptimeMillis();
    247 
    248         pw.print(prefix); pw.print("user #"); pw.print(userId);
    249                 pw.print(" uid="); pw.print(info.uid);
    250         if (uid != info.uid) {
    251             pw.print(" ISOLATED uid="); pw.print(uid);
    252         }
    253         pw.print(" gids={");
    254         if (gids != null) {
    255             for (int gi=0; gi<gids.length; gi++) {
    256                 if (gi != 0) pw.print(", ");
    257                 pw.print(gids[gi]);
    258 
    259             }
    260         }
    261         pw.println("}");
    262         pw.print(prefix); pw.print("requiredAbi="); pw.print(requiredAbi);
    263                 pw.print(" instructionSet="); pw.println(instructionSet);
    264         if (info.className != null) {
    265             pw.print(prefix); pw.print("class="); pw.println(info.className);
    266         }
    267         if (info.manageSpaceActivityName != null) {
    268             pw.print(prefix); pw.print("manageSpaceActivityName=");
    269             pw.println(info.manageSpaceActivityName);
    270         }
    271         pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir);
    272                 pw.print(" publicDir="); pw.print(info.publicSourceDir);
    273                 pw.print(" data="); pw.println(info.dataDir);
    274         pw.print(prefix); pw.print("packageList={");
    275         for (int i=0; i<pkgList.size(); i++) {
    276             if (i > 0) pw.print(", ");
    277             pw.print(pkgList.keyAt(i));
    278         }
    279         pw.println("}");
    280         if (pkgDeps != null) {
    281             pw.print(prefix); pw.print("packageDependencies={");
    282             for (int i=0; i<pkgDeps.size(); i++) {
    283                 if (i > 0) pw.print(", ");
    284                 pw.print(pkgDeps.valueAt(i));
    285             }
    286             pw.println("}");
    287         }
    288         pw.print(prefix); pw.print("compat="); pw.println(compat);
    289         if (instr != null) {
    290             pw.print(prefix); pw.print("instr="); pw.println(instr);
    291         }
    292         pw.print(prefix); pw.print("thread="); pw.println(thread);
    293         pw.print(prefix); pw.print("pid="); pw.print(pid); pw.print(" starting=");
    294                 pw.println(starting);
    295         pw.print(prefix); pw.print("lastActivityTime=");
    296                 TimeUtils.formatDuration(lastActivityTime, nowUptime, pw);
    297                 pw.print(" lastPssTime=");
    298                 TimeUtils.formatDuration(lastPssTime, nowUptime, pw);
    299                 pw.print(" pssStatType="); pw.print(pssStatType);
    300                 pw.print(" nextPssTime=");
    301                 TimeUtils.formatDuration(nextPssTime, nowUptime, pw);
    302                 pw.println();
    303         pw.print(prefix); pw.print("adjSeq="); pw.print(adjSeq);
    304                 pw.print(" lruSeq="); pw.print(lruSeq);
    305                 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, lastPss*1024);
    306                 pw.print(" lastSwapPss="); DebugUtils.printSizeValue(pw, lastSwapPss*1024);
    307                 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, lastCachedPss*1024);
    308                 pw.print(" lastCachedSwapPss="); DebugUtils.printSizeValue(pw, lastCachedSwapPss*1024);
    309                 pw.println();
    310         pw.print(prefix); pw.print("procStateMemTracker: ");
    311         procStateMemTracker.dumpLine(pw);
    312         pw.print(prefix); pw.print("cached="); pw.print(cached);
    313                 pw.print(" empty="); pw.println(empty);
    314         if (serviceb) {
    315             pw.print(prefix); pw.print("serviceb="); pw.print(serviceb);
    316                     pw.print(" serviceHighRam="); pw.println(serviceHighRam);
    317         }
    318         if (notCachedSinceIdle) {
    319             pw.print(prefix); pw.print("notCachedSinceIdle="); pw.print(notCachedSinceIdle);
    320                     pw.print(" initialIdlePss="); pw.println(initialIdlePss);
    321         }
    322         pw.print(prefix); pw.print("oom: max="); pw.print(maxAdj);
    323                 pw.print(" curRaw="); pw.print(curRawAdj);
    324                 pw.print(" setRaw="); pw.print(setRawAdj);
    325                 pw.print(" cur="); pw.print(curAdj);
    326                 pw.print(" set="); pw.println(setAdj);
    327         pw.print(prefix); pw.print("curSchedGroup="); pw.print(curSchedGroup);
    328                 pw.print(" setSchedGroup="); pw.print(setSchedGroup);
    329                 pw.print(" systemNoUi="); pw.print(systemNoUi);
    330                 pw.print(" trimMemoryLevel="); pw.println(trimMemoryLevel);
    331         if (vrThreadTid != 0) {
    332             pw.print(prefix); pw.print("vrThreadTid="); pw.println(vrThreadTid);
    333         }
    334         pw.print(prefix); pw.print("curProcState="); pw.print(curProcState);
    335                 pw.print(" repProcState="); pw.print(repProcState);
    336                 pw.print(" pssProcState="); pw.print(pssProcState);
    337                 pw.print(" setProcState="); pw.print(setProcState);
    338                 pw.print(" lastStateTime=");
    339                 TimeUtils.formatDuration(lastStateTime, nowUptime, pw);
    340                 pw.println();
    341         if (hasShownUi || pendingUiClean || hasAboveClient || treatLikeActivity) {
    342             pw.print(prefix); pw.print("hasShownUi="); pw.print(hasShownUi);
    343                     pw.print(" pendingUiClean="); pw.print(pendingUiClean);
    344                     pw.print(" hasAboveClient="); pw.print(hasAboveClient);
    345                     pw.print(" treatLikeActivity="); pw.println(treatLikeActivity);
    346         }
    347         if (hasTopUi || hasOverlayUi || runningRemoteAnimation) {
    348             pw.print(prefix); pw.print("hasTopUi="); pw.print(hasTopUi);
    349                     pw.print(" hasOverlayUi="); pw.print(hasOverlayUi);
    350                     pw.print(" runningRemoteAnimation="); pw.println(runningRemoteAnimation);
    351         }
    352         if (foregroundServices || forcingToImportant != null) {
    353             pw.print(prefix); pw.print("foregroundServices="); pw.print(foregroundServices);
    354                     pw.print(" forcingToImportant="); pw.println(forcingToImportant);
    355         }
    356         if (reportedInteraction || fgInteractionTime != 0) {
    357             pw.print(prefix); pw.print("reportedInteraction=");
    358             pw.print(reportedInteraction);
    359             if (interactionEventTime != 0) {
    360                 pw.print(" time=");
    361                 TimeUtils.formatDuration(interactionEventTime, SystemClock.elapsedRealtime(), pw);
    362             }
    363             if (fgInteractionTime != 0) {
    364                 pw.print(" fgInteractionTime=");
    365                 TimeUtils.formatDuration(fgInteractionTime, SystemClock.elapsedRealtime(), pw);
    366             }
    367             pw.println();
    368         }
    369         if (persistent || removed) {
    370             pw.print(prefix); pw.print("persistent="); pw.print(persistent);
    371                     pw.print(" removed="); pw.println(removed);
    372         }
    373         if (hasClientActivities || foregroundActivities || repForegroundActivities) {
    374             pw.print(prefix); pw.print("hasClientActivities="); pw.print(hasClientActivities);
    375                     pw.print(" foregroundActivities="); pw.print(foregroundActivities);
    376                     pw.print(" (rep="); pw.print(repForegroundActivities); pw.println(")");
    377         }
    378         if (lastProviderTime > 0) {
    379             pw.print(prefix); pw.print("lastProviderTime=");
    380             TimeUtils.formatDuration(lastProviderTime, nowUptime, pw);
    381             pw.println();
    382         }
    383         if (hasStartedServices) {
    384             pw.print(prefix); pw.print("hasStartedServices="); pw.println(hasStartedServices);
    385         }
    386         if (pendingStart) {
    387             pw.print(prefix); pw.print("pendingStart="); pw.println(pendingStart);
    388         }
    389         pw.print(prefix); pw.print("startSeq="); pw.println(startSeq);
    390         if (setProcState > ActivityManager.PROCESS_STATE_SERVICE) {
    391             pw.print(prefix); pw.print("lastCpuTime="); pw.print(lastCpuTime);
    392                     if (lastCpuTime > 0) {
    393                         pw.print(" timeUsed=");
    394                         TimeUtils.formatDuration(curCpuTime - lastCpuTime, pw);
    395                     }
    396                     pw.print(" whenUnimportant=");
    397                     TimeUtils.formatDuration(whenUnimportant - nowUptime, pw);
    398                     pw.println();
    399         }
    400         pw.print(prefix); pw.print("lastRequestedGc=");
    401                 TimeUtils.formatDuration(lastRequestedGc, nowUptime, pw);
    402                 pw.print(" lastLowMemory=");
    403                 TimeUtils.formatDuration(lastLowMemory, nowUptime, pw);
    404                 pw.print(" reportLowMemory="); pw.println(reportLowMemory);
    405         if (killed || killedByAm || waitingToKill != null) {
    406             pw.print(prefix); pw.print("killed="); pw.print(killed);
    407                     pw.print(" killedByAm="); pw.print(killedByAm);
    408                     pw.print(" waitingToKill="); pw.println(waitingToKill);
    409         }
    410         if (debugging || crashing || crashDialog != null || notResponding
    411                 || anrDialog != null || bad) {
    412             pw.print(prefix); pw.print("debugging="); pw.print(debugging);
    413                     pw.print(" crashing="); pw.print(crashing);
    414                     pw.print(" "); pw.print(crashDialog);
    415                     pw.print(" notResponding="); pw.print(notResponding);
    416                     pw.print(" " ); pw.print(anrDialog);
    417                     pw.print(" bad="); pw.print(bad);
    418 
    419                     // crashing or notResponding is always set before errorReportReceiver
    420                     if (errorReportReceiver != null) {
    421                         pw.print(" errorReportReceiver=");
    422                         pw.print(errorReportReceiver.flattenToShortString());
    423                     }
    424                     pw.println();
    425         }
    426         if (whitelistManager) {
    427             pw.print(prefix); pw.print("whitelistManager="); pw.println(whitelistManager);
    428         }
    429         if (isolatedEntryPoint != null || isolatedEntryPointArgs != null) {
    430             pw.print(prefix); pw.print("isolatedEntryPoint="); pw.println(isolatedEntryPoint);
    431             pw.print(prefix); pw.print("isolatedEntryPointArgs=");
    432             pw.println(Arrays.toString(isolatedEntryPointArgs));
    433         }
    434         if (activities.size() > 0) {
    435             pw.print(prefix); pw.println("Activities:");
    436             for (int i=0; i<activities.size(); i++) {
    437                 pw.print(prefix); pw.print("  - "); pw.println(activities.get(i));
    438             }
    439         }
    440         if (recentTasks.size() > 0) {
    441             pw.print(prefix); pw.println("Recent Tasks:");
    442             for (int i=0; i<recentTasks.size(); i++) {
    443                 pw.print(prefix); pw.print("  - "); pw.println(recentTasks.get(i));
    444             }
    445         }
    446         if (services.size() > 0) {
    447             pw.print(prefix); pw.println("Services:");
    448             for (int i=0; i<services.size(); i++) {
    449                 pw.print(prefix); pw.print("  - "); pw.println(services.valueAt(i));
    450             }
    451         }
    452         if (executingServices.size() > 0) {
    453             pw.print(prefix); pw.print("Executing Services (fg=");
    454             pw.print(execServicesFg); pw.println(")");
    455             for (int i=0; i<executingServices.size(); i++) {
    456                 pw.print(prefix); pw.print("  - "); pw.println(executingServices.valueAt(i));
    457             }
    458         }
    459         if (connections.size() > 0) {
    460             pw.print(prefix); pw.println("Connections:");
    461             for (int i=0; i<connections.size(); i++) {
    462                 pw.print(prefix); pw.print("  - "); pw.println(connections.valueAt(i));
    463             }
    464         }
    465         if (pubProviders.size() > 0) {
    466             pw.print(prefix); pw.println("Published Providers:");
    467             for (int i=0; i<pubProviders.size(); i++) {
    468                 pw.print(prefix); pw.print("  - "); pw.println(pubProviders.keyAt(i));
    469                 pw.print(prefix); pw.print("    -> "); pw.println(pubProviders.valueAt(i));
    470             }
    471         }
    472         if (conProviders.size() > 0) {
    473             pw.print(prefix); pw.println("Connected Providers:");
    474             for (int i=0; i<conProviders.size(); i++) {
    475                 pw.print(prefix); pw.print("  - "); pw.println(conProviders.get(i).toShortString());
    476             }
    477         }
    478         if (!curReceivers.isEmpty()) {
    479             pw.print(prefix); pw.println("Current Receivers:");
    480             for (int i=0; i < curReceivers.size(); i++) {
    481                 pw.print(prefix); pw.print("  - "); pw.println(curReceivers.valueAt(i));
    482             }
    483         }
    484         if (receivers.size() > 0) {
    485             pw.print(prefix); pw.println("Receivers:");
    486             for (int i=0; i<receivers.size(); i++) {
    487                 pw.print(prefix); pw.print("  - "); pw.println(receivers.valueAt(i));
    488             }
    489         }
    490     }
    491 
    492     ProcessRecord(ActivityManagerService _service, BatteryStatsImpl _batteryStats,
    493             ApplicationInfo _info, String _processName, int _uid) {
    494         mService = _service;
    495         mBatteryStats = _batteryStats;
    496         info = _info;
    497         isolated = _info.uid != _uid;
    498         uid = _uid;
    499         userId = UserHandle.getUserId(_uid);
    500         processName = _processName;
    501         pkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.longVersionCode));
    502         maxAdj = ProcessList.UNKNOWN_ADJ;
    503         curRawAdj = setRawAdj = ProcessList.INVALID_ADJ;
    504         curAdj = setAdj = verifiedAdj = ProcessList.INVALID_ADJ;
    505         persistent = false;
    506         removed = false;
    507         lastStateTime = lastPssTime = nextPssTime = SystemClock.uptimeMillis();
    508     }
    509 
    510     public void setPid(int _pid) {
    511         pid = _pid;
    512         procStatFile = null;
    513         shortStringName = null;
    514         stringName = null;
    515     }
    516 
    517     public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
    518         if (thread == null) {
    519             final ProcessState origBase = baseProcessTracker;
    520             if (origBase != null) {
    521                 origBase.setState(ProcessStats.STATE_NOTHING,
    522                         tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
    523                 origBase.makeInactive();
    524             }
    525             baseProcessTracker = tracker.getProcessStateLocked(info.packageName, uid,
    526                     info.longVersionCode, processName);
    527             baseProcessTracker.makeActive();
    528             for (int i=0; i<pkgList.size(); i++) {
    529                 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
    530                 if (holder.state != null && holder.state != origBase) {
    531                     holder.state.makeInactive();
    532                 }
    533                 holder.state = tracker.getProcessStateLocked(pkgList.keyAt(i), uid,
    534                         info.longVersionCode, processName);
    535                 if (holder.state != baseProcessTracker) {
    536                     holder.state.makeActive();
    537                 }
    538             }
    539         }
    540         thread = _thread;
    541     }
    542 
    543     public void makeInactive(ProcessStatsService tracker) {
    544         thread = null;
    545         final ProcessState origBase = baseProcessTracker;
    546         if (origBase != null) {
    547             if (origBase != null) {
    548                 origBase.setState(ProcessStats.STATE_NOTHING,
    549                         tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
    550                 origBase.makeInactive();
    551             }
    552             baseProcessTracker = null;
    553             for (int i=0; i<pkgList.size(); i++) {
    554                 ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
    555                 if (holder.state != null && holder.state != origBase) {
    556                     holder.state.makeInactive();
    557                 }
    558                 holder.state = null;
    559             }
    560         }
    561     }
    562 
    563     public void clearRecentTasks() {
    564         for (int i = recentTasks.size() - 1; i >= 0; i--) {
    565             recentTasks.get(i).clearRootProcess();
    566         }
    567         recentTasks.clear();
    568     }
    569 
    570     /**
    571      * This method returns true if any of the activities within the process record are interesting
    572      * to the user. See HistoryRecord.isInterestingToUserLocked()
    573      */
    574     public boolean isInterestingToUserLocked() {
    575         final int size = activities.size();
    576         for (int i = 0 ; i < size ; i++) {
    577             ActivityRecord r = activities.get(i);
    578             if (r.isInterestingToUserLocked()) {
    579                 return true;
    580             }
    581         }
    582 
    583         final int servicesSize = services.size();
    584         for (int i = 0; i < servicesSize; i++) {
    585             ServiceRecord r = services.valueAt(i);
    586             if (r.isForeground) {
    587                 return true;
    588             }
    589         }
    590         return false;
    591     }
    592 
    593     public void stopFreezingAllLocked() {
    594         int i = activities.size();
    595         while (i > 0) {
    596             i--;
    597             activities.get(i).stopFreezingScreenLocked(true);
    598         }
    599     }
    600 
    601     public void unlinkDeathRecipient() {
    602         if (deathRecipient != null && thread != null) {
    603             thread.asBinder().unlinkToDeath(deathRecipient, 0);
    604         }
    605         deathRecipient = null;
    606     }
    607 
    608     void updateHasAboveClientLocked() {
    609         hasAboveClient = false;
    610         for (int i=connections.size()-1; i>=0; i--) {
    611             ConnectionRecord cr = connections.valueAt(i);
    612             if ((cr.flags&Context.BIND_ABOVE_CLIENT) != 0) {
    613                 hasAboveClient = true;
    614                 break;
    615             }
    616         }
    617     }
    618 
    619     int modifyRawOomAdj(int adj) {
    620         if (hasAboveClient) {
    621             // If this process has bound to any services with BIND_ABOVE_CLIENT,
    622             // then we need to drop its adjustment to be lower than the service's
    623             // in order to honor the request.  We want to drop it by one adjustment
    624             // level...  but there is special meaning applied to various levels so
    625             // we will skip some of them.
    626             if (adj < ProcessList.FOREGROUND_APP_ADJ) {
    627                 // System process will not get dropped, ever
    628             } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
    629                 adj = ProcessList.VISIBLE_APP_ADJ;
    630             } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
    631                 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
    632             } else if (adj < ProcessList.CACHED_APP_MIN_ADJ) {
    633                 adj = ProcessList.CACHED_APP_MIN_ADJ;
    634             } else if (adj < ProcessList.CACHED_APP_MAX_ADJ) {
    635                 adj++;
    636             }
    637         }
    638         return adj;
    639     }
    640 
    641     void scheduleCrash(String message) {
    642         // Checking killedbyAm should keep it from showing the crash dialog if the process
    643         // was already dead for a good / normal reason.
    644         if (!killedByAm) {
    645             if (thread != null) {
    646                 if (pid == Process.myPid()) {
    647                     Slog.w(TAG, "scheduleCrash: trying to crash system process!");
    648                     return;
    649                 }
    650                 long ident = Binder.clearCallingIdentity();
    651                 try {
    652                     thread.scheduleCrash(message);
    653                 } catch (RemoteException e) {
    654                     // If it's already dead our work is done. If it's wedged just kill it.
    655                     // We won't get the crash dialog or the error reporting.
    656                     kill("scheduleCrash for '" + message + "' failed", true);
    657                 } finally {
    658                     Binder.restoreCallingIdentity(ident);
    659                 }
    660             }
    661         }
    662     }
    663 
    664     void kill(String reason, boolean noisy) {
    665         if (!killedByAm) {
    666             Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill");
    667             if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) {
    668                 mService.reportUidInfoMessageLocked(TAG,
    669                         "Killing " + toShortString() + " (adj " + setAdj + "): " + reason,
    670                         info.uid);
    671             }
    672             if (pid > 0) {
    673                 EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
    674                 Process.killProcessQuiet(pid);
    675                 ActivityManagerService.killProcessGroup(uid, pid);
    676             } else {
    677                 pendingStart = false;
    678             }
    679             if (!persistent) {
    680                 killed = true;
    681                 killedByAm = true;
    682             }
    683             Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    684         }
    685     }
    686 
    687     public void writeToProto(ProtoOutputStream proto, long fieldId) {
    688         long token = proto.start(fieldId);
    689         proto.write(ProcessRecordProto.PID, pid);
    690         proto.write(ProcessRecordProto.PROCESS_NAME, processName);
    691         if (info.uid < Process.FIRST_APPLICATION_UID) {
    692             proto.write(ProcessRecordProto.UID, uid);
    693         } else {
    694             proto.write(ProcessRecordProto.USER_ID, userId);
    695             proto.write(ProcessRecordProto.APP_ID, UserHandle.getAppId(info.uid));
    696             if (uid != info.uid) {
    697                 proto.write(ProcessRecordProto.ISOLATED_APP_ID, UserHandle.getAppId(uid));
    698             }
    699         }
    700         proto.write(ProcessRecordProto.PERSISTENT, persistent);
    701         proto.end(token);
    702     }
    703 
    704     public String toShortString() {
    705         if (shortStringName != null) {
    706             return shortStringName;
    707         }
    708         StringBuilder sb = new StringBuilder(128);
    709         toShortString(sb);
    710         return shortStringName = sb.toString();
    711     }
    712 
    713     void toShortString(StringBuilder sb) {
    714         sb.append(pid);
    715         sb.append(':');
    716         sb.append(processName);
    717         sb.append('/');
    718         if (info.uid < Process.FIRST_APPLICATION_UID) {
    719             sb.append(uid);
    720         } else {
    721             sb.append('u');
    722             sb.append(userId);
    723             int appId = UserHandle.getAppId(info.uid);
    724             if (appId >= Process.FIRST_APPLICATION_UID) {
    725                 sb.append('a');
    726                 sb.append(appId - Process.FIRST_APPLICATION_UID);
    727             } else {
    728                 sb.append('s');
    729                 sb.append(appId);
    730             }
    731             if (uid != info.uid) {
    732                 sb.append('i');
    733                 sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
    734             }
    735         }
    736     }
    737 
    738     public String toString() {
    739         if (stringName != null) {
    740             return stringName;
    741         }
    742         StringBuilder sb = new StringBuilder(128);
    743         sb.append("ProcessRecord{");
    744         sb.append(Integer.toHexString(System.identityHashCode(this)));
    745         sb.append(' ');
    746         toShortString(sb);
    747         sb.append('}');
    748         return stringName = sb.toString();
    749     }
    750 
    751     public String makeAdjReason() {
    752         if (adjSource != null || adjTarget != null) {
    753             StringBuilder sb = new StringBuilder(128);
    754             sb.append(' ');
    755             if (adjTarget instanceof ComponentName) {
    756                 sb.append(((ComponentName)adjTarget).flattenToShortString());
    757             } else if (adjTarget != null) {
    758                 sb.append(adjTarget.toString());
    759             } else {
    760                 sb.append("{null}");
    761             }
    762             sb.append("<=");
    763             if (adjSource instanceof ProcessRecord) {
    764                 sb.append("Proc{");
    765                 sb.append(((ProcessRecord)adjSource).toShortString());
    766                 sb.append("}");
    767             } else if (adjSource != null) {
    768                 sb.append(adjSource.toString());
    769             } else {
    770                 sb.append("{null}");
    771             }
    772             return sb.toString();
    773         }
    774         return null;
    775     }
    776 
    777     /*
    778      *  Return true if package has been added false if not
    779      */
    780     public boolean addPackage(String pkg, long versionCode, ProcessStatsService tracker) {
    781         if (!pkgList.containsKey(pkg)) {
    782             ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
    783                     versionCode);
    784             if (baseProcessTracker != null) {
    785                 holder.state = tracker.getProcessStateLocked(
    786                         pkg, uid, versionCode, processName);
    787                 pkgList.put(pkg, holder);
    788                 if (holder.state != baseProcessTracker) {
    789                     holder.state.makeActive();
    790                 }
    791             } else {
    792                 pkgList.put(pkg, holder);
    793             }
    794             return true;
    795         }
    796         return false;
    797     }
    798 
    799     public int getSetAdjWithServices() {
    800         if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
    801             if (hasStartedServices) {
    802                 return ProcessList.SERVICE_B_ADJ;
    803             }
    804         }
    805         return setAdj;
    806     }
    807 
    808     public void forceProcessStateUpTo(int newState) {
    809         if (repProcState > newState) {
    810             curProcState = repProcState = newState;
    811         }
    812     }
    813 
    814     /*
    815      *  Delete all packages from list except the package indicated in info
    816      */
    817     public void resetPackageList(ProcessStatsService tracker) {
    818         final int N = pkgList.size();
    819         if (baseProcessTracker != null) {
    820             long now = SystemClock.uptimeMillis();
    821             baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
    822                     tracker.getMemFactorLocked(), now, pkgList);
    823             if (N != 1) {
    824                 for (int i=0; i<N; i++) {
    825                     ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
    826                     if (holder.state != null && holder.state != baseProcessTracker) {
    827                         holder.state.makeInactive();
    828                     }
    829 
    830                 }
    831                 pkgList.clear();
    832                 ProcessState ps = tracker.getProcessStateLocked(
    833                         info.packageName, uid, info.longVersionCode, processName);
    834                 ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
    835                         info.longVersionCode);
    836                 holder.state = ps;
    837                 pkgList.put(info.packageName, holder);
    838                 if (ps != baseProcessTracker) {
    839                     ps.makeActive();
    840                 }
    841             }
    842         } else if (N != 1) {
    843             pkgList.clear();
    844             pkgList.put(info.packageName, new ProcessStats.ProcessStateHolder(info.longVersionCode));
    845         }
    846     }
    847 
    848     public String[] getPackageList() {
    849         int size = pkgList.size();
    850         if (size == 0) {
    851             return null;
    852         }
    853         String list[] = new String[size];
    854         for (int i=0; i<pkgList.size(); i++) {
    855             list[i] = pkgList.keyAt(i);
    856         }
    857         return list;
    858     }
    859 }
    860