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