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