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