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