ProcessRecord.java revision 810c052d9b117217152c2a609ccec056a2a61d1e
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
17package com.android.server.am;
18
19import android.util.ArraySet;
20import com.android.internal.app.ProcessStats;
21import com.android.internal.os.BatteryStatsImpl;
22
23import android.app.ActivityManager;
24import android.app.Dialog;
25import android.app.IApplicationThread;
26import android.app.IInstrumentationWatcher;
27import android.app.IUiAutomationConnection;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.pm.ApplicationInfo;
31import android.content.res.CompatibilityInfo;
32import android.os.Bundle;
33import android.os.IBinder;
34import android.os.Process;
35import android.os.SystemClock;
36import android.os.UserHandle;
37import android.util.ArrayMap;
38import android.util.PrintWriterPrinter;
39import android.util.TimeUtils;
40
41import java.io.PrintWriter;
42import java.util.ArrayList;
43
44/**
45 * Full information about a particular process that
46 * is currently running.
47 */
48final class ProcessRecord {
49    private final BatteryStatsImpl mBatteryStats; // where to collect runtime statistics
50    final ApplicationInfo info; // all about the first app in the process
51    final boolean isolated;     // true if this is a special isolated process
52    final int uid;              // uid of process; may be different from 'info' if isolated
53    final int userId;           // user of process.
54    final String processName;   // name of the process
55    // List of packages running in the process
56    final ArrayMap<String, ProcessStats.ProcessStateHolder> pkgList
57            = new ArrayMap<String, ProcessStats.ProcessStateHolder>();
58    ArraySet<String> pkgDeps;   // additional packages we have a dependency on
59    IApplicationThread thread;  // the actual proc...  may be null only if
60                                // 'persistent' is true (in which case we
61                                // are in the process of launching the app)
62    ProcessStats.ProcessState baseProcessTracker;
63    BatteryStatsImpl.Uid.Proc curProcBatteryStats;
64    int pid;                    // The process of this application; 0 if none
65    boolean starting;           // True if the process is being started
66    long lastActivityTime;      // For managing the LRU list
67    long lastPssTime;           // Last time we retrieved PSS data
68    long nextPssTime;           // Next time we want to request PSS data
69    long lastStateTime;         // Last time setProcState changed
70    long initialIdlePss;        // Initial memory pss of process for idle maintenance.
71    long lastPss;               // Last computed memory pss.
72    long lastCachedPss;         // Last computed pss when in cached state.
73    int maxAdj;                 // Maximum OOM adjustment for this process
74    int curRawAdj;              // Current OOM unlimited adjustment for this process
75    int setRawAdj;              // Last set OOM unlimited adjustment for this process
76    int curAdj;                 // Current OOM adjustment for this process
77    int setAdj;                 // Last set OOM adjustment for this process
78    int curSchedGroup;          // Currently desired scheduling class
79    int setSchedGroup;          // Last set to background scheduling class
80    int trimMemoryLevel;        // Last selected memory trimming level
81    int curProcState = -1;      // Currently computed process state: ActivityManager.PROCESS_STATE_*
82    int repProcState = -1;      // Last reported process state
83    int setProcState = -1;      // Last set process state in process tracker
84    int pssProcState = -1;      // The proc state we are currently requesting pss for
85    boolean serviceb;           // Process currently is on the service B list
86    boolean serviceHighRam;     // We are forcing to service B list due to its RAM use
87    boolean setIsForeground;    // Running foreground UI when last set?
88    boolean notCachedSinceIdle; // Has this process not been in a cached state since last idle?
89    boolean hasClientActivities;  // Are there any client services with activities?
90    boolean hasStartedServices; // Are there any started services running in this process?
91    boolean foregroundServices; // Running any services that are foreground?
92    boolean foregroundActivities; // Running any activities that are foreground?
93    boolean repForegroundActivities; // Last reported foreground activities.
94    boolean systemNoUi;         // This is a system process, but not currently showing UI.
95    boolean hasShownUi;         // Has UI been shown in this process since it was started?
96    boolean pendingUiClean;     // Want to clean up resources from showing UI?
97    boolean hasAboveClient;     // Bound using BIND_ABOVE_CLIENT, so want to be lower
98    boolean treatLikeActivity;  // Bound using BIND_TREAT_LIKE_ACTIVITY
99    boolean bad;                // True if disabled in the bad process list
100    boolean killedByAm;         // True when proc has been killed by activity manager, not for RAM
101    boolean procStateChanged;   // Keep track of whether we changed 'setAdj'.
102    String waitingToKill;       // Process is waiting to be killed when in the bg, and reason
103    IBinder forcingToForeground;// Token that is forcing this process to be foreground
104    int adjSeq;                 // Sequence id for identifying oom_adj assignment cycles
105    int lruSeq;                 // Sequence id for identifying LRU update cycles
106    CompatibilityInfo compat;   // last used compatibility mode
107    IBinder.DeathRecipient deathRecipient; // Who is watching for the death.
108    ComponentName instrumentationClass;// class installed to instrument app
109    ApplicationInfo instrumentationInfo; // the application being instrumented
110    String instrumentationProfileFile; // where to save profiling
111    IInstrumentationWatcher instrumentationWatcher; // who is waiting
112    IUiAutomationConnection instrumentationUiAutomationConnection; // Connection to use the UI introspection APIs.
113    Bundle instrumentationArguments;// as given to us
114    ComponentName instrumentationResultClass;// copy of instrumentationClass
115    boolean usingWrapper;       // Set to true when process was launched with a wrapper attached
116    BroadcastRecord curReceiver;// receiver currently running in the app
117    long lastWakeTime;          // How long proc held wake lock at last check
118    long lastCpuTime;           // How long proc has run CPU at last check
119    long curCpuTime;            // How long proc has run CPU most recently
120    long lastRequestedGc;       // When we last asked the app to do a gc
121    long lastLowMemory;         // When we last told the app that memory is low
122    boolean reportLowMemory;    // Set to true when waiting to report low mem
123    boolean empty;              // Is this an empty background process?
124    boolean cached;             // Is this a cached process?
125    String adjType;             // Debugging: primary thing impacting oom_adj.
126    int adjTypeCode;            // Debugging: adj code to report to app.
127    Object adjSource;           // Debugging: option dependent object.
128    int adjSourceProcState;     // Debugging: proc state of adjSource's process.
129    Object adjTarget;           // Debugging: target component impacting oom_adj.
130    Runnable crashHandler;      // Optional local handler to be invoked in the process crash.
131
132    // contains HistoryRecord objects
133    final ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
134    // all ServiceRecord running in this process
135    final ArraySet<ServiceRecord> services = new ArraySet<ServiceRecord>();
136    // services that are currently executing code (need to remain foreground).
137    final ArraySet<ServiceRecord> executingServices
138             = new ArraySet<ServiceRecord>();
139    // All ConnectionRecord this process holds
140    final ArraySet<ConnectionRecord> connections
141            = new ArraySet<ConnectionRecord>();
142    // all IIntentReceivers that are registered from this process.
143    final ArraySet<ReceiverList> receivers = new ArraySet<ReceiverList>();
144    // class (String) -> ContentProviderRecord
145    final ArrayMap<String, ContentProviderRecord> pubProviders
146            = new ArrayMap<String, ContentProviderRecord>();
147    // All ContentProviderRecord process is using
148    final ArrayList<ContentProviderConnection> conProviders
149            = new ArrayList<ContentProviderConnection>();
150
151    boolean execServicesFg;     // do we need to be executing services in the foreground?
152    boolean persistent;         // always keep this application running?
153    boolean crashing;           // are we in the process of crashing?
154    Dialog crashDialog;         // dialog being displayed due to crash.
155    boolean forceCrashReport;   // suppress normal auto-dismiss of crash dialog & report UI?
156    boolean notResponding;      // does the app have a not responding dialog?
157    Dialog anrDialog;           // dialog being displayed due to app not resp.
158    boolean removed;            // has app package been removed from device?
159    boolean debugging;          // was app launched for debugging?
160    boolean waitedForDebugger;  // has process show wait for debugger dialog?
161    Dialog waitDialog;          // current wait for debugger dialog
162
163    String shortStringName;     // caching of toShortString() result.
164    String stringName;          // caching of toString() result.
165
166    // These reports are generated & stored when an app gets into an error condition.
167    // They will be "null" when all is OK.
168    ActivityManager.ProcessErrorStateInfo crashingReport;
169    ActivityManager.ProcessErrorStateInfo notRespondingReport;
170
171    // Who will be notified of the error. This is usually an activity in the
172    // app that installed the package.
173    ComponentName errorReportReceiver;
174
175    void dump(PrintWriter pw, String prefix) {
176        final long now = SystemClock.uptimeMillis();
177
178        pw.print(prefix); pw.print("user #"); pw.print(userId);
179                pw.print(" uid="); pw.print(info.uid);
180        if (uid != info.uid) {
181            pw.print(" ISOLATED uid="); pw.print(uid);
182        }
183        pw.println();
184        if (info.className != null) {
185            pw.print(prefix); pw.print("class="); pw.println(info.className);
186        }
187        if (info.manageSpaceActivityName != null) {
188            pw.print(prefix); pw.print("manageSpaceActivityName=");
189            pw.println(info.manageSpaceActivityName);
190        }
191        pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir);
192                pw.print(" publicDir="); pw.print(info.publicSourceDir);
193                pw.print(" data="); pw.println(info.dataDir);
194        pw.print(prefix); pw.print("packageList={");
195        for (int i=0; i<pkgList.size(); i++) {
196            if (i > 0) pw.print(", ");
197            pw.print(pkgList.keyAt(i));
198        }
199        pw.println("}");
200        if (pkgDeps != null) {
201            pw.print(prefix); pw.print("packageDependencies={");
202            for (int i=0; i<pkgDeps.size(); i++) {
203                if (i > 0) pw.print(", ");
204                pw.print(pkgDeps.valueAt(i));
205            }
206            pw.println("}");
207        }
208        pw.print(prefix); pw.print("compat="); pw.println(compat);
209        if (instrumentationClass != null || instrumentationProfileFile != null
210                || instrumentationArguments != null) {
211            pw.print(prefix); pw.print("instrumentationClass=");
212                    pw.print(instrumentationClass);
213                    pw.print(" instrumentationProfileFile=");
214                    pw.println(instrumentationProfileFile);
215            pw.print(prefix); pw.print("instrumentationArguments=");
216                    pw.println(instrumentationArguments);
217            pw.print(prefix); pw.print("instrumentationInfo=");
218                    pw.println(instrumentationInfo);
219            if (instrumentationInfo != null) {
220                instrumentationInfo.dump(new PrintWriterPrinter(pw), prefix + "  ");
221            }
222        }
223        pw.print(prefix); pw.print("thread="); pw.println(thread);
224        pw.print(prefix); pw.print("pid="); pw.print(pid); pw.print(" starting=");
225                pw.println(starting);
226        pw.print(prefix); pw.print("lastActivityTime=");
227                TimeUtils.formatDuration(lastActivityTime, now, pw);
228                pw.print(" lastPssTime=");
229                TimeUtils.formatDuration(lastPssTime, now, pw);
230                pw.print(" nextPssTime=");
231                TimeUtils.formatDuration(nextPssTime, now, pw);
232                pw.println();
233        pw.print(prefix); pw.print("adjSeq="); pw.print(adjSeq);
234                pw.print(" lruSeq="); pw.print(lruSeq);
235                pw.print(" lastPss="); pw.print(lastPss);
236                pw.print(" lastCachedPss="); pw.println(lastCachedPss);
237        pw.print(prefix); pw.print("cached="); pw.print(cached);
238                pw.print(" empty="); pw.println(empty);
239        if (serviceb) {
240            pw.print(prefix); pw.print("serviceb="); pw.print(serviceb);
241                    pw.print(" serviceHighRam="); pw.println(serviceHighRam);
242        }
243        if (notCachedSinceIdle) {
244            pw.print(prefix); pw.print("notCachedSinceIdle="); pw.print(notCachedSinceIdle);
245                    pw.print(" initialIdlePss="); pw.println(initialIdlePss);
246        }
247        pw.print(prefix); pw.print("oom: max="); pw.print(maxAdj);
248                pw.print(" curRaw="); pw.print(curRawAdj);
249                pw.print(" setRaw="); pw.print(setRawAdj);
250                pw.print(" cur="); pw.print(curAdj);
251                pw.print(" set="); pw.println(setAdj);
252        pw.print(prefix); pw.print("curSchedGroup="); pw.print(curSchedGroup);
253                pw.print(" setSchedGroup="); pw.print(setSchedGroup);
254                pw.print(" systemNoUi="); pw.print(systemNoUi);
255                pw.print(" trimMemoryLevel="); pw.println(trimMemoryLevel);
256        pw.print(prefix); pw.print("curProcState="); pw.print(curProcState);
257                pw.print(" repProcState="); pw.print(repProcState);
258                pw.print(" pssProcState="); pw.print(pssProcState);
259                pw.print(" setProcState="); pw.print(setProcState);
260                pw.print(" lastStateTime=");
261                TimeUtils.formatDuration(lastStateTime, now, pw);
262                pw.println();
263        if (hasShownUi || pendingUiClean || hasAboveClient || treatLikeActivity) {
264            pw.print(prefix); pw.print("hasShownUi="); pw.print(hasShownUi);
265                    pw.print(" pendingUiClean="); pw.print(pendingUiClean);
266                    pw.print(" hasAboveClient="); pw.print(hasAboveClient);
267                    pw.print(" treatLikeActivity="); pw.println(treatLikeActivity);
268        }
269        if (setIsForeground || foregroundServices || forcingToForeground != null) {
270            pw.print(prefix); pw.print("setIsForeground="); pw.print(setIsForeground);
271                    pw.print(" foregroundServices="); pw.print(foregroundServices);
272                    pw.print(" forcingToForeground="); pw.println(forcingToForeground);
273        }
274        if (persistent || removed) {
275            pw.print(prefix); pw.print("persistent="); pw.print(persistent);
276                    pw.print(" removed="); pw.println(removed);
277        }
278        if (hasClientActivities || foregroundActivities || repForegroundActivities) {
279            pw.print(prefix); pw.print("hasClientActivities="); pw.print(hasClientActivities);
280                    pw.print(" foregroundActivities="); pw.print(foregroundActivities);
281                    pw.print(" (rep="); pw.print(repForegroundActivities); pw.println(")");
282        }
283        if (hasStartedServices) {
284            pw.print(prefix); pw.print("hasStartedServices="); pw.println(hasStartedServices);
285        }
286        if (setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
287            long wtime;
288            synchronized (mBatteryStats) {
289                wtime = mBatteryStats.getProcessWakeTime(info.uid,
290                        pid, SystemClock.elapsedRealtime());
291            }
292            pw.print(prefix); pw.print("lastWakeTime="); pw.print(lastWakeTime);
293                    pw.print(" timeUsed=");
294                    TimeUtils.formatDuration(wtime-lastWakeTime, pw); pw.println("");
295            pw.print(prefix); pw.print("lastCpuTime="); pw.print(lastCpuTime);
296                    pw.print(" timeUsed=");
297                    TimeUtils.formatDuration(curCpuTime-lastCpuTime, pw); pw.println("");
298        }
299        pw.print(prefix); pw.print("lastRequestedGc=");
300                TimeUtils.formatDuration(lastRequestedGc, now, pw);
301                pw.print(" lastLowMemory=");
302                TimeUtils.formatDuration(lastLowMemory, now, pw);
303                pw.print(" reportLowMemory="); pw.println(reportLowMemory);
304        if (killedByAm || waitingToKill != null) {
305            pw.print(prefix); pw.print("killedByAm="); pw.print(killedByAm);
306                    pw.print(" waitingToKill="); pw.println(waitingToKill);
307        }
308        if (debugging || crashing || crashDialog != null || notResponding
309                || anrDialog != null || bad) {
310            pw.print(prefix); pw.print("debugging="); pw.print(debugging);
311                    pw.print(" crashing="); pw.print(crashing);
312                    pw.print(" "); pw.print(crashDialog);
313                    pw.print(" notResponding="); pw.print(notResponding);
314                    pw.print(" " ); pw.print(anrDialog);
315                    pw.print(" bad="); pw.print(bad);
316
317                    // crashing or notResponding is always set before errorReportReceiver
318                    if (errorReportReceiver != null) {
319                        pw.print(" errorReportReceiver=");
320                        pw.print(errorReportReceiver.flattenToShortString());
321                    }
322                    pw.println();
323        }
324        if (activities.size() > 0) {
325            pw.print(prefix); pw.println("Activities:");
326            for (int i=0; i<activities.size(); i++) {
327                pw.print(prefix); pw.print("  - "); pw.println(activities.get(i));
328            }
329        }
330        if (services.size() > 0) {
331            pw.print(prefix); pw.println("Services:");
332            for (int i=0; i<services.size(); i++) {
333                pw.print(prefix); pw.print("  - "); pw.println(services.valueAt(i));
334            }
335        }
336        if (executingServices.size() > 0) {
337            pw.print(prefix); pw.print("Executing Services (fg=");
338            pw.print(execServicesFg); pw.println(")");
339            for (int i=0; i<executingServices.size(); i++) {
340                pw.print(prefix); pw.print("  - "); pw.println(executingServices.valueAt(i));
341            }
342        }
343        if (connections.size() > 0) {
344            pw.print(prefix); pw.println("Connections:");
345            for (int i=0; i<connections.size(); i++) {
346                pw.print(prefix); pw.print("  - "); pw.println(connections.valueAt(i));
347            }
348        }
349        if (pubProviders.size() > 0) {
350            pw.print(prefix); pw.println("Published Providers:");
351            for (int i=0; i<pubProviders.size(); i++) {
352                pw.print(prefix); pw.print("  - "); pw.println(pubProviders.keyAt(i));
353                pw.print(prefix); pw.print("    -> "); pw.println(pubProviders.valueAt(i));
354            }
355        }
356        if (conProviders.size() > 0) {
357            pw.print(prefix); pw.println("Connected Providers:");
358            for (int i=0; i<conProviders.size(); i++) {
359                pw.print(prefix); pw.print("  - "); pw.println(conProviders.get(i).toShortString());
360            }
361        }
362        if (curReceiver != null) {
363            pw.print(prefix); pw.print("curReceiver="); pw.println(curReceiver);
364        }
365        if (receivers.size() > 0) {
366            pw.print(prefix); pw.println("Receivers:");
367            for (int i=0; i<receivers.size(); i++) {
368                pw.print(prefix); pw.print("  - "); pw.println(receivers.valueAt(i));
369            }
370        }
371    }
372
373    ProcessRecord(BatteryStatsImpl _batteryStats, ApplicationInfo _info,
374            String _processName, int _uid) {
375        mBatteryStats = _batteryStats;
376        info = _info;
377        isolated = _info.uid != _uid;
378        uid = _uid;
379        userId = UserHandle.getUserId(_uid);
380        processName = _processName;
381        pkgList.put(_info.packageName, new ProcessStats.ProcessStateHolder(_info.versionCode));
382        maxAdj = ProcessList.UNKNOWN_ADJ;
383        curRawAdj = setRawAdj = -100;
384        curAdj = setAdj = -100;
385        persistent = false;
386        removed = false;
387        lastStateTime = lastPssTime = nextPssTime = SystemClock.uptimeMillis();
388    }
389
390    public void setPid(int _pid) {
391        pid = _pid;
392        shortStringName = null;
393        stringName = null;
394    }
395
396    public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
397        if (thread == null) {
398            final ProcessStats.ProcessState origBase = baseProcessTracker;
399            if (origBase != null) {
400                origBase.setState(ProcessStats.STATE_NOTHING,
401                        tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
402                origBase.makeInactive();
403            }
404            baseProcessTracker = tracker.getProcessStateLocked(info.packageName, info.uid,
405                    info.versionCode, processName);
406            baseProcessTracker.makeActive();
407            for (int i=0; i<pkgList.size(); i++) {
408                ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
409                if (holder.state != null && holder.state != origBase) {
410                    holder.state.makeInactive();
411                }
412                holder.state = tracker.getProcessStateLocked(pkgList.keyAt(i), info.uid,
413                        info.versionCode, processName);
414                if (holder.state != baseProcessTracker) {
415                    holder.state.makeActive();
416                }
417            }
418        }
419        thread = _thread;
420    }
421
422    public void makeInactive(ProcessStatsService tracker) {
423        thread = null;
424        final ProcessStats.ProcessState origBase = baseProcessTracker;
425        if (origBase != null) {
426            if (origBase != null) {
427                origBase.setState(ProcessStats.STATE_NOTHING,
428                        tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
429                origBase.makeInactive();
430            }
431            baseProcessTracker = null;
432            for (int i=0; i<pkgList.size(); i++) {
433                ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
434                if (holder.state != null && holder.state != origBase) {
435                    holder.state.makeInactive();
436                }
437                holder.state = null;
438            }
439        }
440    }
441
442    /**
443     * This method returns true if any of the activities within the process record are interesting
444     * to the user. See HistoryRecord.isInterestingToUserLocked()
445     */
446    public boolean isInterestingToUserLocked() {
447        final int size = activities.size();
448        for (int i = 0 ; i < size ; i++) {
449            ActivityRecord r = activities.get(i);
450            if (r.isInterestingToUserLocked()) {
451                return true;
452            }
453        }
454        return false;
455    }
456
457    public void stopFreezingAllLocked() {
458        int i = activities.size();
459        while (i > 0) {
460            i--;
461            activities.get(i).stopFreezingScreenLocked(true);
462        }
463    }
464
465    public void unlinkDeathRecipient() {
466        if (deathRecipient != null && thread != null) {
467            thread.asBinder().unlinkToDeath(deathRecipient, 0);
468        }
469        deathRecipient = null;
470    }
471
472    void updateHasAboveClientLocked() {
473        hasAboveClient = false;
474        for (int i=connections.size()-1; i>=0; i--) {
475            ConnectionRecord cr = connections.valueAt(i);
476            if ((cr.flags&Context.BIND_ABOVE_CLIENT) != 0) {
477                hasAboveClient = true;
478                break;
479            }
480        }
481    }
482
483    int modifyRawOomAdj(int adj) {
484        if (hasAboveClient) {
485            // If this process has bound to any services with BIND_ABOVE_CLIENT,
486            // then we need to drop its adjustment to be lower than the service's
487            // in order to honor the request.  We want to drop it by one adjustment
488            // level...  but there is special meaning applied to various levels so
489            // we will skip some of them.
490            if (adj < ProcessList.FOREGROUND_APP_ADJ) {
491                // System process will not get dropped, ever
492            } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
493                adj = ProcessList.VISIBLE_APP_ADJ;
494            } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
495                adj = ProcessList.PERCEPTIBLE_APP_ADJ;
496            } else if (adj < ProcessList.CACHED_APP_MIN_ADJ) {
497                adj = ProcessList.CACHED_APP_MIN_ADJ;
498            } else if (adj < ProcessList.CACHED_APP_MAX_ADJ) {
499                adj++;
500            }
501        }
502        return adj;
503    }
504
505    public String toShortString() {
506        if (shortStringName != null) {
507            return shortStringName;
508        }
509        StringBuilder sb = new StringBuilder(128);
510        toShortString(sb);
511        return shortStringName = sb.toString();
512    }
513
514    void toShortString(StringBuilder sb) {
515        sb.append(pid);
516        sb.append(':');
517        sb.append(processName);
518        sb.append('/');
519        if (info.uid < Process.FIRST_APPLICATION_UID) {
520            sb.append(uid);
521        } else {
522            sb.append('u');
523            sb.append(userId);
524            int appId = UserHandle.getAppId(info.uid);
525            if (appId >= Process.FIRST_APPLICATION_UID) {
526                sb.append('a');
527                sb.append(appId - Process.FIRST_APPLICATION_UID);
528            } else {
529                sb.append('s');
530                sb.append(appId);
531            }
532            if (uid != info.uid) {
533                sb.append('i');
534                sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
535            }
536        }
537    }
538
539    public String toString() {
540        if (stringName != null) {
541            return stringName;
542        }
543        StringBuilder sb = new StringBuilder(128);
544        sb.append("ProcessRecord{");
545        sb.append(Integer.toHexString(System.identityHashCode(this)));
546        sb.append(' ');
547        toShortString(sb);
548        sb.append('}');
549        return stringName = sb.toString();
550    }
551
552    public String makeAdjReason() {
553        if (adjSource != null || adjTarget != null) {
554            StringBuilder sb = new StringBuilder(128);
555            sb.append(' ');
556            if (adjTarget instanceof ComponentName) {
557                sb.append(((ComponentName)adjTarget).flattenToShortString());
558            } else if (adjTarget != null) {
559                sb.append(adjTarget.toString());
560            } else {
561                sb.append("{null}");
562            }
563            sb.append("<=");
564            if (adjSource instanceof ProcessRecord) {
565                sb.append("Proc{");
566                sb.append(((ProcessRecord)adjSource).toShortString());
567                sb.append("}");
568            } else if (adjSource != null) {
569                sb.append(adjSource.toString());
570            } else {
571                sb.append("{null}");
572            }
573            return sb.toString();
574        }
575        return null;
576    }
577
578    /*
579     *  Return true if package has been added false if not
580     */
581    public boolean addPackage(String pkg, int versionCode, ProcessStatsService tracker) {
582        if (!pkgList.containsKey(pkg)) {
583            ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
584                    versionCode);
585            if (baseProcessTracker != null) {
586                holder.state = tracker.getProcessStateLocked(
587                        pkg, info.uid, versionCode, processName);
588                pkgList.put(pkg, holder);
589                if (holder.state != baseProcessTracker) {
590                    holder.state.makeActive();
591                }
592            } else {
593                pkgList.put(pkg, holder);
594            }
595            return true;
596        }
597        return false;
598    }
599
600    public int getSetAdjWithServices() {
601        if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
602            if (hasStartedServices) {
603                return ProcessList.SERVICE_B_ADJ;
604            }
605        }
606        return setAdj;
607    }
608
609    public void forceProcessStateUpTo(int newState) {
610        if (repProcState > newState) {
611            curProcState = repProcState = newState;
612        }
613    }
614
615    /*
616     *  Delete all packages from list except the package indicated in info
617     */
618    public void resetPackageList(ProcessStatsService tracker) {
619        final int N = pkgList.size();
620        if (baseProcessTracker != null) {
621            long now = SystemClock.uptimeMillis();
622            baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
623                    tracker.getMemFactorLocked(), now, pkgList);
624            if (N != 1) {
625                for (int i=0; i<N; i++) {
626                    ProcessStats.ProcessStateHolder holder = pkgList.valueAt(i);
627                    if (holder.state != null && holder.state != baseProcessTracker) {
628                        holder.state.makeInactive();
629                    }
630
631                }
632                pkgList.clear();
633                ProcessStats.ProcessState ps = tracker.getProcessStateLocked(
634                        info.packageName, info.uid, info.versionCode, processName);
635                ProcessStats.ProcessStateHolder holder = new ProcessStats.ProcessStateHolder(
636                        info.versionCode);
637                holder.state = ps;
638                pkgList.put(info.packageName, holder);
639                if (ps != baseProcessTracker) {
640                    ps.makeActive();
641                }
642            }
643        } else if (N != 1) {
644            pkgList.clear();
645            pkgList.put(info.packageName, new ProcessStats.ProcessStateHolder(info.versionCode));
646        }
647    }
648
649    public String[] getPackageList() {
650        int size = pkgList.size();
651        if (size == 0) {
652            return null;
653        }
654        String list[] = new String[size];
655        for (int i=0; i<pkgList.size(); i++) {
656            list[i] = pkgList.keyAt(i);
657        }
658        return list;
659    }
660}
661