ActivityManagerService.java revision faa4b3cb06f3b10ece1f1d246a3530fc2f30a6da
1/*
2 * Copyright (C) 2006-2008 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.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
21import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
22import static android.content.pm.PackageManager.PERMISSION_GRANTED;
23import static com.android.internal.util.XmlUtils.readBooleanAttribute;
24import static com.android.internal.util.XmlUtils.readIntAttribute;
25import static com.android.internal.util.XmlUtils.readLongAttribute;
26import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
27import static com.android.internal.util.XmlUtils.writeIntAttribute;
28import static com.android.internal.util.XmlUtils.writeLongAttribute;
29import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
30import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
31import static org.xmlpull.v1.XmlPullParser.START_TAG;
32import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID;
33
34import android.Manifest;
35import android.app.AppOpsManager;
36import android.app.IActivityContainer;
37import android.app.IActivityContainerCallback;
38import android.app.IAppTask;
39import android.app.admin.DevicePolicyManager;
40import android.app.usage.UsageStats;
41import android.app.usage.UsageStatsManagerInternal;
42import android.appwidget.AppWidgetManager;
43import android.graphics.Rect;
44import android.os.BatteryStats;
45import android.os.PersistableBundle;
46import android.service.voice.IVoiceInteractionSession;
47import android.util.ArrayMap;
48import android.util.ArraySet;
49import android.util.SparseIntArray;
50
51import com.android.internal.R;
52import com.android.internal.annotations.GuardedBy;
53import com.android.internal.app.IAppOpsService;
54import com.android.internal.app.IVoiceInteractor;
55import com.android.internal.app.ProcessMap;
56import com.android.internal.app.ProcessStats;
57import com.android.internal.content.PackageMonitor;
58import com.android.internal.os.BackgroundThread;
59import com.android.internal.os.BatteryStatsImpl;
60import com.android.internal.os.ProcessCpuTracker;
61import com.android.internal.os.TransferPipe;
62import com.android.internal.os.Zygote;
63import com.android.internal.util.FastPrintWriter;
64import com.android.internal.util.FastXmlSerializer;
65import com.android.internal.util.MemInfoReader;
66import com.android.internal.util.Preconditions;
67import com.android.server.AppOpsService;
68import com.android.server.AttributeCache;
69import com.android.server.IntentResolver;
70import com.android.server.LocalServices;
71import com.android.server.ServiceThread;
72import com.android.server.SystemService;
73import com.android.server.SystemServiceManager;
74import com.android.server.Watchdog;
75import com.android.server.am.ActivityStack.ActivityState;
76import com.android.server.firewall.IntentFirewall;
77import com.android.server.pm.UserManagerService;
78import com.android.server.wm.AppTransition;
79import com.android.server.wm.WindowManagerService;
80import com.google.android.collect.Lists;
81import com.google.android.collect.Maps;
82
83import libcore.io.IoUtils;
84
85import org.xmlpull.v1.XmlPullParser;
86import org.xmlpull.v1.XmlPullParserException;
87import org.xmlpull.v1.XmlSerializer;
88
89import android.app.Activity;
90import android.app.ActivityManager;
91import android.app.ActivityManager.RunningTaskInfo;
92import android.app.ActivityManager.StackInfo;
93import android.app.ActivityManagerInternal;
94import android.app.ActivityManagerNative;
95import android.app.ActivityOptions;
96import android.app.ActivityThread;
97import android.app.AlertDialog;
98import android.app.AppGlobals;
99import android.app.ApplicationErrorReport;
100import android.app.Dialog;
101import android.app.IActivityController;
102import android.app.IApplicationThread;
103import android.app.IInstrumentationWatcher;
104import android.app.INotificationManager;
105import android.app.IProcessObserver;
106import android.app.IServiceConnection;
107import android.app.IStopUserCallback;
108import android.app.IUiAutomationConnection;
109import android.app.IUserSwitchObserver;
110import android.app.Instrumentation;
111import android.app.Notification;
112import android.app.NotificationManager;
113import android.app.PendingIntent;
114import android.app.backup.IBackupManager;
115import android.content.ActivityNotFoundException;
116import android.content.BroadcastReceiver;
117import android.content.ClipData;
118import android.content.ComponentCallbacks2;
119import android.content.ComponentName;
120import android.content.ContentProvider;
121import android.content.ContentResolver;
122import android.content.Context;
123import android.content.DialogInterface;
124import android.content.IContentProvider;
125import android.content.IIntentReceiver;
126import android.content.IIntentSender;
127import android.content.Intent;
128import android.content.IntentFilter;
129import android.content.IntentSender;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.ConfigurationInfo;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageManager;
135import android.content.pm.InstrumentationInfo;
136import android.content.pm.PackageInfo;
137import android.content.pm.PackageManager;
138import android.content.pm.ParceledListSlice;
139import android.content.pm.UserInfo;
140import android.content.pm.PackageManager.NameNotFoundException;
141import android.content.pm.PathPermission;
142import android.content.pm.ProviderInfo;
143import android.content.pm.ResolveInfo;
144import android.content.pm.ServiceInfo;
145import android.content.res.CompatibilityInfo;
146import android.content.res.Configuration;
147import android.net.Proxy;
148import android.net.ProxyInfo;
149import android.net.Uri;
150import android.os.Binder;
151import android.os.Build;
152import android.os.Bundle;
153import android.os.Debug;
154import android.os.DropBoxManager;
155import android.os.Environment;
156import android.os.FactoryTest;
157import android.os.FileObserver;
158import android.os.FileUtils;
159import android.os.Handler;
160import android.os.IBinder;
161import android.os.IPermissionController;
162import android.os.IRemoteCallback;
163import android.os.IUserManager;
164import android.os.Looper;
165import android.os.Message;
166import android.os.Parcel;
167import android.os.ParcelFileDescriptor;
168import android.os.Process;
169import android.os.RemoteCallbackList;
170import android.os.RemoteException;
171import android.os.SELinux;
172import android.os.ServiceManager;
173import android.os.StrictMode;
174import android.os.SystemClock;
175import android.os.SystemProperties;
176import android.os.UpdateLock;
177import android.os.UserHandle;
178import android.provider.Settings;
179import android.text.format.DateUtils;
180import android.text.format.Time;
181import android.util.AtomicFile;
182import android.util.EventLog;
183import android.util.Log;
184import android.util.Pair;
185import android.util.PrintWriterPrinter;
186import android.util.Slog;
187import android.util.SparseArray;
188import android.util.TimeUtils;
189import android.util.Xml;
190import android.view.Gravity;
191import android.view.LayoutInflater;
192import android.view.View;
193import android.view.WindowManager;
194
195import java.io.BufferedInputStream;
196import java.io.BufferedOutputStream;
197import java.io.DataInputStream;
198import java.io.DataOutputStream;
199import java.io.File;
200import java.io.FileDescriptor;
201import java.io.FileInputStream;
202import java.io.FileNotFoundException;
203import java.io.FileOutputStream;
204import java.io.IOException;
205import java.io.InputStreamReader;
206import java.io.PrintWriter;
207import java.io.StringWriter;
208import java.lang.ref.WeakReference;
209import java.util.ArrayList;
210import java.util.Arrays;
211import java.util.Collections;
212import java.util.Comparator;
213import java.util.HashMap;
214import java.util.HashSet;
215import java.util.Iterator;
216import java.util.List;
217import java.util.Locale;
218import java.util.Map;
219import java.util.Set;
220import java.util.concurrent.atomic.AtomicBoolean;
221import java.util.concurrent.atomic.AtomicLong;
222
223public final class ActivityManagerService extends ActivityManagerNative
224        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
225
226    private static final String USER_DATA_DIR = "/data/user/";
227    // File that stores last updated system version and called preboot receivers
228    static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat";
229
230    static final String TAG = "ActivityManager";
231    static final String TAG_MU = "ActivityManagerServiceMU";
232    static final boolean DEBUG = false;
233    static final boolean localLOGV = DEBUG;
234    static final boolean DEBUG_BACKUP = localLOGV || false;
235    static final boolean DEBUG_BROADCAST = localLOGV || false;
236    static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
237    static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
238    static final boolean DEBUG_CLEANUP = localLOGV || false;
239    static final boolean DEBUG_CONFIGURATION = localLOGV || false;
240    static final boolean DEBUG_FOCUS = false;
241    static final boolean DEBUG_IMMERSIVE = localLOGV || false;
242    static final boolean DEBUG_MU = localLOGV || false;
243    static final boolean DEBUG_OOM_ADJ = localLOGV || false;
244    static final boolean DEBUG_LRU = localLOGV || false;
245    static final boolean DEBUG_PAUSE = localLOGV || false;
246    static final boolean DEBUG_POWER = localLOGV || false;
247    static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
248    static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
249    static final boolean DEBUG_PROCESSES = localLOGV || false;
250    static final boolean DEBUG_PROVIDER = localLOGV || false;
251    static final boolean DEBUG_RESULTS = localLOGV || false;
252    static final boolean DEBUG_SERVICE = localLOGV || false;
253    static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
254    static final boolean DEBUG_STACK = localLOGV || false;
255    static final boolean DEBUG_SWITCH = localLOGV || false;
256    static final boolean DEBUG_TASKS = localLOGV || false;
257    static final boolean DEBUG_THUMBNAILS = localLOGV || false;
258    static final boolean DEBUG_TRANSITION = localLOGV || false;
259    static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
260    static final boolean DEBUG_USER_LEAVING = localLOGV || false;
261    static final boolean DEBUG_VISBILITY = localLOGV || false;
262    static final boolean DEBUG_PSS = localLOGV || false;
263    static final boolean DEBUG_LOCKSCREEN = localLOGV || false;
264    static final boolean VALIDATE_TOKENS = false;
265    static final boolean SHOW_ACTIVITY_START_TIME = true;
266
267    // Control over CPU and battery monitoring.
268    static final long BATTERY_STATS_TIME = 30*60*1000;      // write battery stats every 30 minutes.
269    static final boolean MONITOR_CPU_USAGE = true;
270    static final long MONITOR_CPU_MIN_TIME = 5*1000;        // don't sample cpu less than every 5 seconds.
271    static final long MONITOR_CPU_MAX_TIME = 0x0fffffff;    // wait possibly forever for next cpu sample.
272    static final boolean MONITOR_THREAD_CPU_USAGE = false;
273
274    // The flags that are set for all calls we make to the package manager.
275    static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
276
277    private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
278
279    static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
280
281    // Maximum number of recent tasks that we can remember.
282    static final int MAX_RECENT_TASKS = ActivityManager.isLowRamDeviceStatic() ? 100 : 200;
283
284    // Maximum number recent bitmaps to keep in memory.
285    static final int MAX_RECENT_BITMAPS = 5;
286
287    // Amount of time after a call to stopAppSwitches() during which we will
288    // prevent further untrusted switches from happening.
289    static final long APP_SWITCH_DELAY_TIME = 5*1000;
290
291    // How long we wait for a launched process to attach to the activity manager
292    // before we decide it's never going to come up for real.
293    static final int PROC_START_TIMEOUT = 10*1000;
294
295    // How long we wait for a launched process to attach to the activity manager
296    // before we decide it's never going to come up for real, when the process was
297    // started with a wrapper for instrumentation (such as Valgrind) because it
298    // could take much longer than usual.
299    static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000;
300
301    // How long to wait after going idle before forcing apps to GC.
302    static final int GC_TIMEOUT = 5*1000;
303
304    // The minimum amount of time between successive GC requests for a process.
305    static final int GC_MIN_INTERVAL = 60*1000;
306
307    // The minimum amount of time between successive PSS requests for a process.
308    static final int FULL_PSS_MIN_INTERVAL = 10*60*1000;
309
310    // The minimum amount of time between successive PSS requests for a process
311    // when the request is due to the memory state being lowered.
312    static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
313
314    // The rate at which we check for apps using excessive power -- 15 mins.
315    static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
316
317    // The minimum sample duration we will allow before deciding we have
318    // enough data on wake locks to start killing things.
319    static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
320
321    // The minimum sample duration we will allow before deciding we have
322    // enough data on CPU usage to start killing things.
323    static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
324
325    // How long we allow a receiver to run before giving up on it.
326    static final int BROADCAST_FG_TIMEOUT = 10*1000;
327    static final int BROADCAST_BG_TIMEOUT = 60*1000;
328
329    // How long we wait until we timeout on key dispatching.
330    static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
331
332    // How long we wait until we timeout on key dispatching during instrumentation.
333    static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
334
335    // Amount of time we wait for observers to handle a user switch before
336    // giving up on them and unfreezing the screen.
337    static final int USER_SWITCH_TIMEOUT = 2*1000;
338
339    // Maximum number of users we allow to be running at a time.
340    static final int MAX_RUNNING_USERS = 3;
341
342    // How long to wait in getAssistContextExtras for the activity and foreground services
343    // to respond with the result.
344    static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500;
345
346    // Maximum number of persisted Uri grants a package is allowed
347    static final int MAX_PERSISTED_URI_GRANTS = 128;
348
349    static final int MY_PID = Process.myPid();
350
351    static final String[] EMPTY_STRING_ARRAY = new String[0];
352
353    // How many bytes to write into the dropbox log before truncating
354    static final int DROPBOX_MAX_SIZE = 256 * 1024;
355
356    // Access modes for handleIncomingUser.
357    static final int ALLOW_NON_FULL = 0;
358    static final int ALLOW_NON_FULL_IN_PROFILE = 1;
359    static final int ALLOW_FULL_ONLY = 2;
360
361    static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000;
362
363    /** All system services */
364    SystemServiceManager mSystemServiceManager;
365
366    /** Run all ActivityStacks through this */
367    ActivityStackSupervisor mStackSupervisor;
368
369    public IntentFirewall mIntentFirewall;
370
371    // Whether we should show our dialogs (ANR, crash, etc) or just perform their
372    // default actuion automatically.  Important for devices without direct input
373    // devices.
374    private boolean mShowDialogs = true;
375
376    BroadcastQueue mFgBroadcastQueue;
377    BroadcastQueue mBgBroadcastQueue;
378    // Convenient for easy iteration over the queues. Foreground is first
379    // so that dispatch of foreground broadcasts gets precedence.
380    final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
381
382    BroadcastQueue broadcastQueueForIntent(Intent intent) {
383        final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
384        if (DEBUG_BACKGROUND_BROADCAST) {
385            Slog.i(TAG, "Broadcast intent " + intent + " on "
386                    + (isFg ? "foreground" : "background")
387                    + " queue");
388        }
389        return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
390    }
391
392    BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
393        for (BroadcastQueue queue : mBroadcastQueues) {
394            BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
395            if (r != null) {
396                return r;
397            }
398        }
399        return null;
400    }
401
402    /**
403     * Activity we have told the window manager to have key focus.
404     */
405    ActivityRecord mFocusedActivity = null;
406
407    /**
408     * List of intents that were used to start the most recent tasks.
409     */
410    ArrayList<TaskRecord> mRecentTasks;
411    ArraySet<TaskRecord> mTmpRecents = new ArraySet<TaskRecord>();
412
413    public class PendingAssistExtras extends Binder implements Runnable {
414        public final ActivityRecord activity;
415        public boolean haveResult = false;
416        public Bundle result = null;
417        public PendingAssistExtras(ActivityRecord _activity) {
418            activity = _activity;
419        }
420        @Override
421        public void run() {
422            Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity);
423            synchronized (this) {
424                haveResult = true;
425                notifyAll();
426            }
427        }
428    }
429
430    final ArrayList<PendingAssistExtras> mPendingAssistExtras
431            = new ArrayList<PendingAssistExtras>();
432
433    /**
434     * Process management.
435     */
436    final ProcessList mProcessList = new ProcessList();
437
438    /**
439     * All of the applications we currently have running organized by name.
440     * The keys are strings of the application package name (as
441     * returned by the package manager), and the keys are ApplicationRecord
442     * objects.
443     */
444    final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
445
446    /**
447     * Tracking long-term execution of processes to look for abuse and other
448     * bad app behavior.
449     */
450    final ProcessStatsService mProcessStats;
451
452    /**
453     * The currently running isolated processes.
454     */
455    final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
456
457    /**
458     * Counter for assigning isolated process uids, to avoid frequently reusing the
459     * same ones.
460     */
461    int mNextIsolatedProcessUid = 0;
462
463    /**
464     * The currently running heavy-weight process, if any.
465     */
466    ProcessRecord mHeavyWeightProcess = null;
467
468    /**
469     * The last time that various processes have crashed.
470     */
471    final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
472
473    /**
474     * Information about a process that is currently marked as bad.
475     */
476    static final class BadProcessInfo {
477        BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
478            this.time = time;
479            this.shortMsg = shortMsg;
480            this.longMsg = longMsg;
481            this.stack = stack;
482        }
483
484        final long time;
485        final String shortMsg;
486        final String longMsg;
487        final String stack;
488    }
489
490    /**
491     * Set of applications that we consider to be bad, and will reject
492     * incoming broadcasts from (which the user has no control over).
493     * Processes are added to this set when they have crashed twice within
494     * a minimum amount of time; they are removed from it when they are
495     * later restarted (hopefully due to some user action).  The value is the
496     * time it was added to the list.
497     */
498    final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>();
499
500    /**
501     * All of the processes we currently have running organized by pid.
502     * The keys are the pid running the application.
503     *
504     * <p>NOTE: This object is protected by its own lock, NOT the global
505     * activity manager lock!
506     */
507    final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
508
509    /**
510     * All of the processes that have been forced to be foreground.  The key
511     * is the pid of the caller who requested it (we hold a death
512     * link on it).
513     */
514    abstract class ForegroundToken implements IBinder.DeathRecipient {
515        int pid;
516        IBinder token;
517    }
518    final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>();
519
520    /**
521     * List of records for processes that someone had tried to start before the
522     * system was ready.  We don't start them at that point, but ensure they
523     * are started by the time booting is complete.
524     */
525    final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>();
526
527    /**
528     * List of persistent applications that are in the process
529     * of being started.
530     */
531    final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>();
532
533    /**
534     * Processes that are being forcibly torn down.
535     */
536    final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>();
537
538    /**
539     * List of running applications, sorted by recent usage.
540     * The first entry in the list is the least recently used.
541     */
542    final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>();
543
544    /**
545     * Where in mLruProcesses that the processes hosting activities start.
546     */
547    int mLruProcessActivityStart = 0;
548
549    /**
550     * Where in mLruProcesses that the processes hosting services start.
551     * This is after (lower index) than mLruProcessesActivityStart.
552     */
553    int mLruProcessServiceStart = 0;
554
555    /**
556     * List of processes that should gc as soon as things are idle.
557     */
558    final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>();
559
560    /**
561     * Processes we want to collect PSS data from.
562     */
563    final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>();
564
565    /**
566     * Last time we requested PSS data of all processes.
567     */
568    long mLastFullPssTime = SystemClock.uptimeMillis();
569
570    /**
571     * If set, the next time we collect PSS data we should do a full collection
572     * with data from native processes and the kernel.
573     */
574    boolean mFullPssPending = false;
575
576    /**
577     * This is the process holding what we currently consider to be
578     * the "home" activity.
579     */
580    ProcessRecord mHomeProcess;
581
582    /**
583     * This is the process holding the activity the user last visited that
584     * is in a different process from the one they are currently in.
585     */
586    ProcessRecord mPreviousProcess;
587
588    /**
589     * The time at which the previous process was last visible.
590     */
591    long mPreviousProcessVisibleTime;
592
593    /**
594     * Which uses have been started, so are allowed to run code.
595     */
596    final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
597
598    /**
599     * LRU list of history of current users.  Most recently current is at the end.
600     */
601    final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
602
603    /**
604     * Constant array of the users that are currently started.
605     */
606    int[] mStartedUserArray = new int[] { 0 };
607
608    /**
609     * Registered observers of the user switching mechanics.
610     */
611    final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
612            = new RemoteCallbackList<IUserSwitchObserver>();
613
614    /**
615     * Currently active user switch.
616     */
617    Object mCurUserSwitchCallback;
618
619    /**
620     * Packages that the user has asked to have run in screen size
621     * compatibility mode instead of filling the screen.
622     */
623    final CompatModePackages mCompatModePackages;
624
625    /**
626     * Set of IntentSenderRecord objects that are currently active.
627     */
628    final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
629            = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
630
631    /**
632     * Fingerprints (hashCode()) of stack traces that we've
633     * already logged DropBox entries for.  Guarded by itself.  If
634     * something (rogue user app) forces this over
635     * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
636     */
637    private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
638    private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
639
640    /**
641     * Strict Mode background batched logging state.
642     *
643     * The string buffer is guarded by itself, and its lock is also
644     * used to determine if another batched write is already
645     * in-flight.
646     */
647    private final StringBuilder mStrictModeBuffer = new StringBuilder();
648
649    /**
650     * Keeps track of all IIntentReceivers that have been registered for
651     * broadcasts.  Hash keys are the receiver IBinder, hash value is
652     * a ReceiverList.
653     */
654    final HashMap<IBinder, ReceiverList> mRegisteredReceivers =
655            new HashMap<IBinder, ReceiverList>();
656
657    /**
658     * Resolver for broadcast intents to registered receivers.
659     * Holds BroadcastFilter (subclass of IntentFilter).
660     */
661    final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
662            = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
663        @Override
664        protected boolean allowFilterResult(
665                BroadcastFilter filter, List<BroadcastFilter> dest) {
666            IBinder target = filter.receiverList.receiver.asBinder();
667            for (int i=dest.size()-1; i>=0; i--) {
668                if (dest.get(i).receiverList.receiver.asBinder() == target) {
669                    return false;
670                }
671            }
672            return true;
673        }
674
675        @Override
676        protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
677            if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
678                    || userId == filter.owningUserId) {
679                return super.newResult(filter, match, userId);
680            }
681            return null;
682        }
683
684        @Override
685        protected BroadcastFilter[] newArray(int size) {
686            return new BroadcastFilter[size];
687        }
688
689        @Override
690        protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
691            return packageName.equals(filter.packageName);
692        }
693    };
694
695    /**
696     * State of all active sticky broadcasts per user.  Keys are the action of the
697     * sticky Intent, values are an ArrayList of all broadcasted intents with
698     * that action (which should usually be one).  The SparseArray is keyed
699     * by the user ID the sticky is for, and can include UserHandle.USER_ALL
700     * for stickies that are sent to all users.
701     */
702    final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts =
703            new SparseArray<ArrayMap<String, ArrayList<Intent>>>();
704
705    final ActiveServices mServices;
706
707    /**
708     * Backup/restore process management
709     */
710    String mBackupAppName = null;
711    BackupRecord mBackupTarget = null;
712
713    final ProviderMap mProviderMap;
714
715    /**
716     * List of content providers who have clients waiting for them.  The
717     * application is currently being launched and the provider will be
718     * removed from this list once it is published.
719     */
720    final ArrayList<ContentProviderRecord> mLaunchingProviders
721            = new ArrayList<ContentProviderRecord>();
722
723    /**
724     * File storing persisted {@link #mGrantedUriPermissions}.
725     */
726    private final AtomicFile mGrantFile;
727
728    /** XML constants used in {@link #mGrantFile} */
729    private static final String TAG_URI_GRANTS = "uri-grants";
730    private static final String TAG_URI_GRANT = "uri-grant";
731    private static final String ATTR_USER_HANDLE = "userHandle";
732    private static final String ATTR_SOURCE_USER_ID = "sourceUserId";
733    private static final String ATTR_TARGET_USER_ID = "targetUserId";
734    private static final String ATTR_SOURCE_PKG = "sourcePkg";
735    private static final String ATTR_TARGET_PKG = "targetPkg";
736    private static final String ATTR_URI = "uri";
737    private static final String ATTR_MODE_FLAGS = "modeFlags";
738    private static final String ATTR_CREATED_TIME = "createdTime";
739    private static final String ATTR_PREFIX = "prefix";
740
741    /**
742     * Global set of specific {@link Uri} permissions that have been granted.
743     * This optimized lookup structure maps from {@link UriPermission#targetUid}
744     * to {@link UriPermission#uri} to {@link UriPermission}.
745     */
746    @GuardedBy("this")
747    private final SparseArray<ArrayMap<GrantUri, UriPermission>>
748            mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>();
749
750    public static class GrantUri {
751        public final int sourceUserId;
752        public final Uri uri;
753        public boolean prefix;
754
755        public GrantUri(int sourceUserId, Uri uri, boolean prefix) {
756            this.sourceUserId = sourceUserId;
757            this.uri = uri;
758            this.prefix = prefix;
759        }
760
761        @Override
762        public int hashCode() {
763            return toString().hashCode();
764        }
765
766        @Override
767        public boolean equals(Object o) {
768            if (o instanceof GrantUri) {
769                GrantUri other = (GrantUri) o;
770                return uri.equals(other.uri) && (sourceUserId == other.sourceUserId)
771                        && prefix == other.prefix;
772            }
773            return false;
774        }
775
776        @Override
777        public String toString() {
778            String result = Integer.toString(sourceUserId) + " @ " + uri.toString();
779            if (prefix) result += " [prefix]";
780            return result;
781        }
782
783        public String toSafeString() {
784            String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString();
785            if (prefix) result += " [prefix]";
786            return result;
787        }
788
789        public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) {
790            return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle),
791                    ContentProvider.getUriWithoutUserId(uri), false);
792        }
793    }
794
795    CoreSettingsObserver mCoreSettingsObserver;
796
797    /**
798     * Thread-local storage used to carry caller permissions over through
799     * indirect content-provider access.
800     */
801    private class Identity {
802        public int pid;
803        public int uid;
804
805        Identity(int _pid, int _uid) {
806            pid = _pid;
807            uid = _uid;
808        }
809    }
810
811    private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
812
813    /**
814     * All information we have collected about the runtime performance of
815     * any user id that can impact battery performance.
816     */
817    final BatteryStatsService mBatteryStatsService;
818
819    /**
820     * Information about component usage
821     */
822    UsageStatsManagerInternal mUsageStatsService;
823
824    /**
825     * Information about and control over application operations
826     */
827    final AppOpsService mAppOpsService;
828
829    /**
830     * Save recent tasks information across reboots.
831     */
832    final TaskPersister mTaskPersister;
833
834    /**
835     * Current configuration information.  HistoryRecord objects are given
836     * a reference to this object to indicate which configuration they are
837     * currently running in, so this object must be kept immutable.
838     */
839    Configuration mConfiguration = new Configuration();
840
841    /**
842     * Current sequencing integer of the configuration, for skipping old
843     * configurations.
844     */
845    int mConfigurationSeq = 0;
846
847    /**
848     * Hardware-reported OpenGLES version.
849     */
850    final int GL_ES_VERSION;
851
852    /**
853     * List of initialization arguments to pass to all processes when binding applications to them.
854     * For example, references to the commonly used services.
855     */
856    HashMap<String, IBinder> mAppBindArgs;
857
858    /**
859     * Temporary to avoid allocations.  Protected by main lock.
860     */
861    final StringBuilder mStringBuilder = new StringBuilder(256);
862
863    /**
864     * Used to control how we initialize the service.
865     */
866    ComponentName mTopComponent;
867    String mTopAction = Intent.ACTION_MAIN;
868    String mTopData;
869    boolean mProcessesReady = false;
870    boolean mSystemReady = false;
871    boolean mBooting = false;
872    boolean mWaitingUpdate = false;
873    boolean mDidUpdate = false;
874    boolean mOnBattery = false;
875    boolean mLaunchWarningShown = false;
876
877    Context mContext;
878
879    int mFactoryTest;
880
881    boolean mCheckedForSetup;
882
883    /**
884     * The time at which we will allow normal application switches again,
885     * after a call to {@link #stopAppSwitches()}.
886     */
887    long mAppSwitchesAllowedTime;
888
889    /**
890     * This is set to true after the first switch after mAppSwitchesAllowedTime
891     * is set; any switches after that will clear the time.
892     */
893    boolean mDidAppSwitch;
894
895    /**
896     * Last time (in realtime) at which we checked for power usage.
897     */
898    long mLastPowerCheckRealtime;
899
900    /**
901     * Last time (in uptime) at which we checked for power usage.
902     */
903    long mLastPowerCheckUptime;
904
905    /**
906     * Set while we are wanting to sleep, to prevent any
907     * activities from being started/resumed.
908     */
909    private boolean mSleeping = false;
910
911    /**
912     * Set while we are running a voice interaction.  This overrides
913     * sleeping while it is active.
914     */
915    private boolean mRunningVoice = false;
916
917    /**
918     * State of external calls telling us if the device is asleep.
919     */
920    private boolean mWentToSleep = false;
921
922    /**
923     * State of external call telling us if the lock screen is shown.
924     */
925    private boolean mLockScreenShown = false;
926
927    /**
928     * Set if we are shutting down the system, similar to sleeping.
929     */
930    boolean mShuttingDown = false;
931
932    /**
933     * Current sequence id for oom_adj computation traversal.
934     */
935    int mAdjSeq = 0;
936
937    /**
938     * Current sequence id for process LRU updating.
939     */
940    int mLruSeq = 0;
941
942    /**
943     * Keep track of the non-cached/empty process we last found, to help
944     * determine how to distribute cached/empty processes next time.
945     */
946    int mNumNonCachedProcs = 0;
947
948    /**
949     * Keep track of the number of cached hidden procs, to balance oom adj
950     * distribution between those and empty procs.
951     */
952    int mNumCachedHiddenProcs = 0;
953
954    /**
955     * Keep track of the number of service processes we last found, to
956     * determine on the next iteration which should be B services.
957     */
958    int mNumServiceProcs = 0;
959    int mNewNumAServiceProcs = 0;
960    int mNewNumServiceProcs = 0;
961
962    /**
963     * Allow the current computed overall memory level of the system to go down?
964     * This is set to false when we are killing processes for reasons other than
965     * memory management, so that the now smaller process list will not be taken as
966     * an indication that memory is tighter.
967     */
968    boolean mAllowLowerMemLevel = false;
969
970    /**
971     * The last computed memory level, for holding when we are in a state that
972     * processes are going away for other reasons.
973     */
974    int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
975
976    /**
977     * The last total number of process we have, to determine if changes actually look
978     * like a shrinking number of process due to lower RAM.
979     */
980    int mLastNumProcesses;
981
982    /**
983     * The uptime of the last time we performed idle maintenance.
984     */
985    long mLastIdleTime = SystemClock.uptimeMillis();
986
987    /**
988     * Total time spent with RAM that has been added in the past since the last idle time.
989     */
990    long mLowRamTimeSinceLastIdle = 0;
991
992    /**
993     * If RAM is currently low, when that horrible situation started.
994     */
995    long mLowRamStartTime = 0;
996
997    /**
998     * For reporting to battery stats the current top application.
999     */
1000    private String mCurResumedPackage = null;
1001    private int mCurResumedUid = -1;
1002
1003    /**
1004     * For reporting to battery stats the apps currently running foreground
1005     * service.  The ProcessMap is package/uid tuples; each of these contain
1006     * an array of the currently foreground processes.
1007     */
1008    final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages
1009            = new ProcessMap<ArrayList<ProcessRecord>>();
1010
1011    /**
1012     * This is set if we had to do a delayed dexopt of an app before launching
1013     * it, to increase the ANR timeouts in that case.
1014     */
1015    boolean mDidDexOpt;
1016
1017    /**
1018     * Set if the systemServer made a call to enterSafeMode.
1019     */
1020    boolean mSafeMode;
1021
1022    String mDebugApp = null;
1023    boolean mWaitForDebugger = false;
1024    boolean mDebugTransient = false;
1025    String mOrigDebugApp = null;
1026    boolean mOrigWaitForDebugger = false;
1027    boolean mAlwaysFinishActivities = false;
1028    IActivityController mController = null;
1029    String mProfileApp = null;
1030    ProcessRecord mProfileProc = null;
1031    String mProfileFile;
1032    ParcelFileDescriptor mProfileFd;
1033    int mProfileType = 0;
1034    boolean mAutoStopProfiler = false;
1035    String mOpenGlTraceApp = null;
1036
1037    static class ProcessChangeItem {
1038        static final int CHANGE_ACTIVITIES = 1<<0;
1039        static final int CHANGE_PROCESS_STATE = 1<<1;
1040        int changes;
1041        int uid;
1042        int pid;
1043        int processState;
1044        boolean foregroundActivities;
1045    }
1046
1047    final RemoteCallbackList<IProcessObserver> mProcessObservers
1048            = new RemoteCallbackList<IProcessObserver>();
1049    ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
1050
1051    final ArrayList<ProcessChangeItem> mPendingProcessChanges
1052            = new ArrayList<ProcessChangeItem>();
1053    final ArrayList<ProcessChangeItem> mAvailProcessChanges
1054            = new ArrayList<ProcessChangeItem>();
1055
1056    /**
1057     * Runtime CPU use collection thread.  This object's lock is used to
1058     * protect all related state.
1059     */
1060    final Thread mProcessCpuThread;
1061
1062    /**
1063     * Used to collect process stats when showing not responding dialog.
1064     * Protected by mProcessCpuThread.
1065     */
1066    final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker(
1067            MONITOR_THREAD_CPU_USAGE);
1068    final AtomicLong mLastCpuTime = new AtomicLong(0);
1069    final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true);
1070
1071    long mLastWriteTime = 0;
1072
1073    /**
1074     * Used to retain an update lock when the foreground activity is in
1075     * immersive mode.
1076     */
1077    final UpdateLock mUpdateLock = new UpdateLock("immersive");
1078
1079    /**
1080     * Set to true after the system has finished booting.
1081     */
1082    boolean mBooted = false;
1083
1084    int mProcessLimit = ProcessList.MAX_CACHED_APPS;
1085    int mProcessLimitOverride = -1;
1086
1087    WindowManagerService mWindowManager;
1088
1089    final ActivityThread mSystemThread;
1090
1091    int mCurrentUserId = 0;
1092    int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack
1093
1094    /**
1095     * Mapping from each known user ID to the profile group ID it is associated with.
1096     */
1097    SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
1098
1099    private UserManagerService mUserManager;
1100
1101    private final class AppDeathRecipient implements IBinder.DeathRecipient {
1102        final ProcessRecord mApp;
1103        final int mPid;
1104        final IApplicationThread mAppThread;
1105
1106        AppDeathRecipient(ProcessRecord app, int pid,
1107                IApplicationThread thread) {
1108            if (localLOGV) Slog.v(
1109                TAG, "New death recipient " + this
1110                + " for thread " + thread.asBinder());
1111            mApp = app;
1112            mPid = pid;
1113            mAppThread = thread;
1114        }
1115
1116        @Override
1117        public void binderDied() {
1118            if (localLOGV) Slog.v(
1119                TAG, "Death received in " + this
1120                + " for thread " + mAppThread.asBinder());
1121            synchronized(ActivityManagerService.this) {
1122                appDiedLocked(mApp, mPid, mAppThread);
1123            }
1124        }
1125    }
1126
1127    static final int SHOW_ERROR_MSG = 1;
1128    static final int SHOW_NOT_RESPONDING_MSG = 2;
1129    static final int SHOW_FACTORY_ERROR_MSG = 3;
1130    static final int UPDATE_CONFIGURATION_MSG = 4;
1131    static final int GC_BACKGROUND_PROCESSES_MSG = 5;
1132    static final int WAIT_FOR_DEBUGGER_MSG = 6;
1133    static final int SERVICE_TIMEOUT_MSG = 12;
1134    static final int UPDATE_TIME_ZONE = 13;
1135    static final int SHOW_UID_ERROR_MSG = 14;
1136    static final int IM_FEELING_LUCKY_MSG = 15;
1137    static final int PROC_START_TIMEOUT_MSG = 20;
1138    static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
1139    static final int KILL_APPLICATION_MSG = 22;
1140    static final int FINALIZE_PENDING_INTENT_MSG = 23;
1141    static final int POST_HEAVY_NOTIFICATION_MSG = 24;
1142    static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
1143    static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
1144    static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
1145    static final int CLEAR_DNS_CACHE_MSG = 28;
1146    static final int UPDATE_HTTP_PROXY_MSG = 29;
1147    static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
1148    static final int DISPATCH_PROCESSES_CHANGED = 31;
1149    static final int DISPATCH_PROCESS_DIED = 32;
1150    static final int REPORT_MEM_USAGE_MSG = 33;
1151    static final int REPORT_USER_SWITCH_MSG = 34;
1152    static final int CONTINUE_USER_SWITCH_MSG = 35;
1153    static final int USER_SWITCH_TIMEOUT_MSG = 36;
1154    static final int IMMERSIVE_MODE_LOCK_MSG = 37;
1155    static final int PERSIST_URI_GRANTS_MSG = 38;
1156    static final int REQUEST_ALL_PSS_MSG = 39;
1157    static final int START_PROFILES_MSG = 40;
1158    static final int UPDATE_TIME = 41;
1159    static final int SYSTEM_USER_START_MSG = 42;
1160    static final int SYSTEM_USER_CURRENT_MSG = 43;
1161    static final int ENTER_ANIMATION_COMPLETE_MSG = 44;
1162    static final int ENABLE_SCREEN_AFTER_BOOT_MSG = 45;
1163
1164    static final int FIRST_ACTIVITY_STACK_MSG = 100;
1165    static final int FIRST_BROADCAST_QUEUE_MSG = 200;
1166    static final int FIRST_COMPAT_MODE_MSG = 300;
1167    static final int FIRST_SUPERVISOR_STACK_MSG = 100;
1168
1169    AlertDialog mUidAlert;
1170    CompatModeDialog mCompatModeDialog;
1171    long mLastMemUsageReportTime = 0;
1172
1173    private LockToAppRequestDialog mLockToAppRequest;
1174
1175    /**
1176     * Flag whether the current user is a "monkey", i.e. whether
1177     * the UI is driven by a UI automation tool.
1178     */
1179    private boolean mUserIsMonkey;
1180
1181    /** Flag whether the device has a recents UI */
1182    final boolean mHasRecents;
1183
1184    final ServiceThread mHandlerThread;
1185    final MainHandler mHandler;
1186
1187    final class MainHandler extends Handler {
1188        public MainHandler(Looper looper) {
1189            super(looper, null, true);
1190        }
1191
1192        @Override
1193        public void handleMessage(Message msg) {
1194            switch (msg.what) {
1195            case SHOW_ERROR_MSG: {
1196                HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1197                boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
1198                        Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
1199                synchronized (ActivityManagerService.this) {
1200                    ProcessRecord proc = (ProcessRecord)data.get("app");
1201                    AppErrorResult res = (AppErrorResult) data.get("result");
1202                    if (proc != null && proc.crashDialog != null) {
1203                        Slog.e(TAG, "App already has crash dialog: " + proc);
1204                        if (res != null) {
1205                            res.set(0);
1206                        }
1207                        return;
1208                    }
1209                    boolean isBackground = (UserHandle.getAppId(proc.uid)
1210                            >= Process.FIRST_APPLICATION_UID
1211                            && proc.pid != MY_PID);
1212                    for (int userId : mCurrentProfileIds) {
1213                        isBackground &= (proc.userId != userId);
1214                    }
1215                    if (isBackground && !showBackground) {
1216                        Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
1217                        if (res != null) {
1218                            res.set(0);
1219                        }
1220                        return;
1221                    }
1222                    if (mShowDialogs && !mSleeping && !mShuttingDown) {
1223                        Dialog d = new AppErrorDialog(mContext,
1224                                ActivityManagerService.this, res, proc);
1225                        d.show();
1226                        proc.crashDialog = d;
1227                    } else {
1228                        // The device is asleep, so just pretend that the user
1229                        // saw a crash dialog and hit "force quit".
1230                        if (res != null) {
1231                            res.set(0);
1232                        }
1233                    }
1234                }
1235
1236                ensureBootCompleted();
1237            } break;
1238            case SHOW_NOT_RESPONDING_MSG: {
1239                synchronized (ActivityManagerService.this) {
1240                    HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1241                    ProcessRecord proc = (ProcessRecord)data.get("app");
1242                    if (proc != null && proc.anrDialog != null) {
1243                        Slog.e(TAG, "App already has anr dialog: " + proc);
1244                        return;
1245                    }
1246
1247                    Intent intent = new Intent("android.intent.action.ANR");
1248                    if (!mProcessesReady) {
1249                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1250                                | Intent.FLAG_RECEIVER_FOREGROUND);
1251                    }
1252                    broadcastIntentLocked(null, null, intent,
1253                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1254                            false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
1255
1256                    if (mShowDialogs) {
1257                        Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
1258                                mContext, proc, (ActivityRecord)data.get("activity"),
1259                                msg.arg1 != 0);
1260                        d.show();
1261                        proc.anrDialog = d;
1262                    } else {
1263                        // Just kill the app if there is no dialog to be shown.
1264                        killAppAtUsersRequest(proc, null);
1265                    }
1266                }
1267
1268                ensureBootCompleted();
1269            } break;
1270            case SHOW_STRICT_MODE_VIOLATION_MSG: {
1271                HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1272                synchronized (ActivityManagerService.this) {
1273                    ProcessRecord proc = (ProcessRecord) data.get("app");
1274                    if (proc == null) {
1275                        Slog.e(TAG, "App not found when showing strict mode dialog.");
1276                        break;
1277                    }
1278                    if (proc.crashDialog != null) {
1279                        Slog.e(TAG, "App already has strict mode dialog: " + proc);
1280                        return;
1281                    }
1282                    AppErrorResult res = (AppErrorResult) data.get("result");
1283                    if (mShowDialogs && !mSleeping && !mShuttingDown) {
1284                        Dialog d = new StrictModeViolationDialog(mContext,
1285                                ActivityManagerService.this, res, proc);
1286                        d.show();
1287                        proc.crashDialog = d;
1288                    } else {
1289                        // The device is asleep, so just pretend that the user
1290                        // saw a crash dialog and hit "force quit".
1291                        res.set(0);
1292                    }
1293                }
1294                ensureBootCompleted();
1295            } break;
1296            case SHOW_FACTORY_ERROR_MSG: {
1297                Dialog d = new FactoryErrorDialog(
1298                    mContext, msg.getData().getCharSequence("msg"));
1299                d.show();
1300                ensureBootCompleted();
1301            } break;
1302            case UPDATE_CONFIGURATION_MSG: {
1303                final ContentResolver resolver = mContext.getContentResolver();
1304                Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1305            } break;
1306            case GC_BACKGROUND_PROCESSES_MSG: {
1307                synchronized (ActivityManagerService.this) {
1308                    performAppGcsIfAppropriateLocked();
1309                }
1310            } break;
1311            case WAIT_FOR_DEBUGGER_MSG: {
1312                synchronized (ActivityManagerService.this) {
1313                    ProcessRecord app = (ProcessRecord)msg.obj;
1314                    if (msg.arg1 != 0) {
1315                        if (!app.waitedForDebugger) {
1316                            Dialog d = new AppWaitingForDebuggerDialog(
1317                                    ActivityManagerService.this,
1318                                    mContext, app);
1319                            app.waitDialog = d;
1320                            app.waitedForDebugger = true;
1321                            d.show();
1322                        }
1323                    } else {
1324                        if (app.waitDialog != null) {
1325                            app.waitDialog.dismiss();
1326                            app.waitDialog = null;
1327                        }
1328                    }
1329                }
1330            } break;
1331            case SERVICE_TIMEOUT_MSG: {
1332                if (mDidDexOpt) {
1333                    mDidDexOpt = false;
1334                    Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1335                    nmsg.obj = msg.obj;
1336                    mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
1337                    return;
1338                }
1339                mServices.serviceTimeout((ProcessRecord)msg.obj);
1340            } break;
1341            case UPDATE_TIME_ZONE: {
1342                synchronized (ActivityManagerService.this) {
1343                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1344                        ProcessRecord r = mLruProcesses.get(i);
1345                        if (r.thread != null) {
1346                            try {
1347                                r.thread.updateTimeZone();
1348                            } catch (RemoteException ex) {
1349                                Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
1350                            }
1351                        }
1352                    }
1353                }
1354            } break;
1355            case CLEAR_DNS_CACHE_MSG: {
1356                synchronized (ActivityManagerService.this) {
1357                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1358                        ProcessRecord r = mLruProcesses.get(i);
1359                        if (r.thread != null) {
1360                            try {
1361                                r.thread.clearDnsCache();
1362                            } catch (RemoteException ex) {
1363                                Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1364                            }
1365                        }
1366                    }
1367                }
1368            } break;
1369            case UPDATE_HTTP_PROXY_MSG: {
1370                ProxyInfo proxy = (ProxyInfo)msg.obj;
1371                String host = "";
1372                String port = "";
1373                String exclList = "";
1374                Uri pacFileUrl = Uri.EMPTY;
1375                if (proxy != null) {
1376                    host = proxy.getHost();
1377                    port = Integer.toString(proxy.getPort());
1378                    exclList = proxy.getExclusionListAsString();
1379                    pacFileUrl = proxy.getPacFileUrl();
1380                }
1381                synchronized (ActivityManagerService.this) {
1382                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1383                        ProcessRecord r = mLruProcesses.get(i);
1384                        if (r.thread != null) {
1385                            try {
1386                                r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
1387                            } catch (RemoteException ex) {
1388                                Slog.w(TAG, "Failed to update http proxy for: " +
1389                                        r.info.processName);
1390                            }
1391                        }
1392                    }
1393                }
1394            } break;
1395            case SHOW_UID_ERROR_MSG: {
1396                String title = "System UIDs Inconsistent";
1397                String text = "UIDs on the system are inconsistent, you need to wipe your"
1398                        + " data partition or your device will be unstable.";
1399                Log.e(TAG, title + ": " + text);
1400                if (mShowDialogs) {
1401                    // XXX This is a temporary dialog, no need to localize.
1402                    AlertDialog d = new BaseErrorDialog(mContext);
1403                    d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1404                    d.setCancelable(false);
1405                    d.setTitle(title);
1406                    d.setMessage(text);
1407                    d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1408                            mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1409                    mUidAlert = d;
1410                    d.show();
1411                }
1412            } break;
1413            case IM_FEELING_LUCKY_MSG: {
1414                if (mUidAlert != null) {
1415                    mUidAlert.dismiss();
1416                    mUidAlert = null;
1417                }
1418            } break;
1419            case PROC_START_TIMEOUT_MSG: {
1420                if (mDidDexOpt) {
1421                    mDidDexOpt = false;
1422                    Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1423                    nmsg.obj = msg.obj;
1424                    mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1425                    return;
1426                }
1427                ProcessRecord app = (ProcessRecord)msg.obj;
1428                synchronized (ActivityManagerService.this) {
1429                    processStartTimedOutLocked(app);
1430                }
1431            } break;
1432            case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1433                synchronized (ActivityManagerService.this) {
1434                    mStackSupervisor.doPendingActivityLaunchesLocked(true);
1435                }
1436            } break;
1437            case KILL_APPLICATION_MSG: {
1438                synchronized (ActivityManagerService.this) {
1439                    int appid = msg.arg1;
1440                    boolean restart = (msg.arg2 == 1);
1441                    Bundle bundle = (Bundle)msg.obj;
1442                    String pkg = bundle.getString("pkg");
1443                    String reason = bundle.getString("reason");
1444                    forceStopPackageLocked(pkg, appid, restart, false, true, false,
1445                            false, UserHandle.USER_ALL, reason);
1446                }
1447            } break;
1448            case FINALIZE_PENDING_INTENT_MSG: {
1449                ((PendingIntentRecord)msg.obj).completeFinalize();
1450            } break;
1451            case POST_HEAVY_NOTIFICATION_MSG: {
1452                INotificationManager inm = NotificationManager.getService();
1453                if (inm == null) {
1454                    return;
1455                }
1456
1457                ActivityRecord root = (ActivityRecord)msg.obj;
1458                ProcessRecord process = root.app;
1459                if (process == null) {
1460                    return;
1461                }
1462
1463                try {
1464                    Context context = mContext.createPackageContext(process.info.packageName, 0);
1465                    String text = mContext.getString(R.string.heavy_weight_notification,
1466                            context.getApplicationInfo().loadLabel(context.getPackageManager()));
1467                    Notification notification = new Notification();
1468                    notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1469                    notification.when = 0;
1470                    notification.flags = Notification.FLAG_ONGOING_EVENT;
1471                    notification.tickerText = text;
1472                    notification.defaults = 0; // please be quiet
1473                    notification.sound = null;
1474                    notification.vibrate = null;
1475                    notification.setLatestEventInfo(context, text,
1476                            mContext.getText(R.string.heavy_weight_notification_detail),
1477                            PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1478                                    PendingIntent.FLAG_CANCEL_CURRENT, null,
1479                                    new UserHandle(root.userId)));
1480
1481                    try {
1482                        int[] outId = new int[1];
1483                        inm.enqueueNotificationWithTag("android", "android", null,
1484                                R.string.heavy_weight_notification,
1485                                notification, outId, root.userId);
1486                    } catch (RuntimeException e) {
1487                        Slog.w(ActivityManagerService.TAG,
1488                                "Error showing notification for heavy-weight app", e);
1489                    } catch (RemoteException e) {
1490                    }
1491                } catch (NameNotFoundException e) {
1492                    Slog.w(TAG, "Unable to create context for heavy notification", e);
1493                }
1494            } break;
1495            case CANCEL_HEAVY_NOTIFICATION_MSG: {
1496                INotificationManager inm = NotificationManager.getService();
1497                if (inm == null) {
1498                    return;
1499                }
1500                try {
1501                    inm.cancelNotificationWithTag("android", null,
1502                            R.string.heavy_weight_notification,  msg.arg1);
1503                } catch (RuntimeException e) {
1504                    Slog.w(ActivityManagerService.TAG,
1505                            "Error canceling notification for service", e);
1506                } catch (RemoteException e) {
1507                }
1508            } break;
1509            case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1510                synchronized (ActivityManagerService.this) {
1511                    checkExcessivePowerUsageLocked(true);
1512                    removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1513                    Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1514                    sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
1515                }
1516            } break;
1517            case SHOW_COMPAT_MODE_DIALOG_MSG: {
1518                synchronized (ActivityManagerService.this) {
1519                    ActivityRecord ar = (ActivityRecord)msg.obj;
1520                    if (mCompatModeDialog != null) {
1521                        if (mCompatModeDialog.mAppInfo.packageName.equals(
1522                                ar.info.applicationInfo.packageName)) {
1523                            return;
1524                        }
1525                        mCompatModeDialog.dismiss();
1526                        mCompatModeDialog = null;
1527                    }
1528                    if (ar != null && false) {
1529                        if (mCompatModePackages.getPackageAskCompatModeLocked(
1530                                ar.packageName)) {
1531                            int mode = mCompatModePackages.computeCompatModeLocked(
1532                                    ar.info.applicationInfo);
1533                            if (mode == ActivityManager.COMPAT_MODE_DISABLED
1534                                    || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1535                                mCompatModeDialog = new CompatModeDialog(
1536                                        ActivityManagerService.this, mContext,
1537                                        ar.info.applicationInfo);
1538                                mCompatModeDialog.show();
1539                            }
1540                        }
1541                    }
1542                }
1543                break;
1544            }
1545            case DISPATCH_PROCESSES_CHANGED: {
1546                dispatchProcessesChanged();
1547                break;
1548            }
1549            case DISPATCH_PROCESS_DIED: {
1550                final int pid = msg.arg1;
1551                final int uid = msg.arg2;
1552                dispatchProcessDied(pid, uid);
1553                break;
1554            }
1555            case REPORT_MEM_USAGE_MSG: {
1556                final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj;
1557                Thread thread = new Thread() {
1558                    @Override public void run() {
1559                        final SparseArray<ProcessMemInfo> infoMap
1560                                = new SparseArray<ProcessMemInfo>(memInfos.size());
1561                        for (int i=0, N=memInfos.size(); i<N; i++) {
1562                            ProcessMemInfo mi = memInfos.get(i);
1563                            infoMap.put(mi.pid, mi);
1564                        }
1565                        updateCpuStatsNow();
1566                        synchronized (mProcessCpuThread) {
1567                            final int N = mProcessCpuTracker.countStats();
1568                            for (int i=0; i<N; i++) {
1569                                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
1570                                if (st.vsize > 0) {
1571                                    long pss = Debug.getPss(st.pid, null);
1572                                    if (pss > 0) {
1573                                        if (infoMap.indexOfKey(st.pid) < 0) {
1574                                            ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid,
1575                                                    ProcessList.NATIVE_ADJ, -1, "native", null);
1576                                            mi.pss = pss;
1577                                            memInfos.add(mi);
1578                                        }
1579                                    }
1580                                }
1581                            }
1582                        }
1583
1584                        long totalPss = 0;
1585                        for (int i=0, N=memInfos.size(); i<N; i++) {
1586                            ProcessMemInfo mi = memInfos.get(i);
1587                            if (mi.pss == 0) {
1588                                mi.pss = Debug.getPss(mi.pid, null);
1589                            }
1590                            totalPss += mi.pss;
1591                        }
1592                        Collections.sort(memInfos, new Comparator<ProcessMemInfo>() {
1593                            @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) {
1594                                if (lhs.oomAdj != rhs.oomAdj) {
1595                                    return lhs.oomAdj < rhs.oomAdj ? -1 : 1;
1596                                }
1597                                if (lhs.pss != rhs.pss) {
1598                                    return lhs.pss < rhs.pss ? 1 : -1;
1599                                }
1600                                return 0;
1601                            }
1602                        });
1603
1604                        StringBuilder tag = new StringBuilder(128);
1605                        StringBuilder stack = new StringBuilder(128);
1606                        tag.append("Low on memory -- ");
1607                        appendMemBucket(tag, totalPss, "total", false);
1608                        appendMemBucket(stack, totalPss, "total", true);
1609
1610                        StringBuilder logBuilder = new StringBuilder(1024);
1611                        logBuilder.append("Low on memory:\n");
1612
1613                        boolean firstLine = true;
1614                        int lastOomAdj = Integer.MIN_VALUE;
1615                        for (int i=0, N=memInfos.size(); i<N; i++) {
1616                            ProcessMemInfo mi = memInfos.get(i);
1617
1618                            if (mi.oomAdj != ProcessList.NATIVE_ADJ
1619                                    && (mi.oomAdj < ProcessList.SERVICE_ADJ
1620                                            || mi.oomAdj == ProcessList.HOME_APP_ADJ
1621                                            || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) {
1622                                if (lastOomAdj != mi.oomAdj) {
1623                                    lastOomAdj = mi.oomAdj;
1624                                    if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
1625                                        tag.append(" / ");
1626                                    }
1627                                    if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) {
1628                                        if (firstLine) {
1629                                            stack.append(":");
1630                                            firstLine = false;
1631                                        }
1632                                        stack.append("\n\t at ");
1633                                    } else {
1634                                        stack.append("$");
1635                                    }
1636                                } else {
1637                                    tag.append(" ");
1638                                    stack.append("$");
1639                                }
1640                                if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) {
1641                                    appendMemBucket(tag, mi.pss, mi.name, false);
1642                                }
1643                                appendMemBucket(stack, mi.pss, mi.name, true);
1644                                if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ
1645                                        && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) {
1646                                    stack.append("(");
1647                                    for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
1648                                        if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) {
1649                                            stack.append(DUMP_MEM_OOM_LABEL[k]);
1650                                            stack.append(":");
1651                                            stack.append(DUMP_MEM_OOM_ADJ[k]);
1652                                        }
1653                                    }
1654                                    stack.append(")");
1655                                }
1656                            }
1657
1658                            logBuilder.append("  ");
1659                            logBuilder.append(ProcessList.makeOomAdjString(mi.oomAdj));
1660                            logBuilder.append(' ');
1661                            logBuilder.append(ProcessList.makeProcStateString(mi.procState));
1662                            logBuilder.append(' ');
1663                            ProcessList.appendRamKb(logBuilder, mi.pss);
1664                            logBuilder.append(" kB: ");
1665                            logBuilder.append(mi.name);
1666                            logBuilder.append(" (");
1667                            logBuilder.append(mi.pid);
1668                            logBuilder.append(") ");
1669                            logBuilder.append(mi.adjType);
1670                            logBuilder.append('\n');
1671                            if (mi.adjReason != null) {
1672                                logBuilder.append("                      ");
1673                                logBuilder.append(mi.adjReason);
1674                                logBuilder.append('\n');
1675                            }
1676                        }
1677
1678                        logBuilder.append("           ");
1679                        ProcessList.appendRamKb(logBuilder, totalPss);
1680                        logBuilder.append(" kB: TOTAL\n");
1681
1682                        long[] infos = new long[Debug.MEMINFO_COUNT];
1683                        Debug.getMemInfo(infos);
1684                        logBuilder.append("  MemInfo: ");
1685                        logBuilder.append(infos[Debug.MEMINFO_SLAB]).append(" kB slab, ");
1686                        logBuilder.append(infos[Debug.MEMINFO_SHMEM]).append(" kB shmem, ");
1687                        logBuilder.append(infos[Debug.MEMINFO_BUFFERS]).append(" kB buffers, ");
1688                        logBuilder.append(infos[Debug.MEMINFO_CACHED]).append(" kB cached, ");
1689                        logBuilder.append(infos[Debug.MEMINFO_FREE]).append(" kB free\n");
1690                        if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) {
1691                            logBuilder.append("  ZRAM: ");
1692                            logBuilder.append(infos[Debug.MEMINFO_ZRAM_TOTAL]);
1693                            logBuilder.append(" kB RAM, ");
1694                            logBuilder.append(infos[Debug.MEMINFO_SWAP_TOTAL]);
1695                            logBuilder.append(" kB swap total, ");
1696                            logBuilder.append(infos[Debug.MEMINFO_SWAP_FREE]);
1697                            logBuilder.append(" kB swap free\n");
1698                        }
1699                        Slog.i(TAG, logBuilder.toString());
1700
1701                        StringBuilder dropBuilder = new StringBuilder(1024);
1702                        /*
1703                        StringWriter oomSw = new StringWriter();
1704                        PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256);
1705                        StringWriter catSw = new StringWriter();
1706                        PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
1707                        String[] emptyArgs = new String[] { };
1708                        dumpApplicationMemoryUsage(null, oomPw, "  ", emptyArgs, true, catPw);
1709                        oomPw.flush();
1710                        String oomString = oomSw.toString();
1711                        */
1712                        dropBuilder.append(stack);
1713                        dropBuilder.append('\n');
1714                        dropBuilder.append('\n');
1715                        dropBuilder.append(logBuilder);
1716                        dropBuilder.append('\n');
1717                        /*
1718                        dropBuilder.append(oomString);
1719                        dropBuilder.append('\n');
1720                        */
1721                        StringWriter catSw = new StringWriter();
1722                        synchronized (ActivityManagerService.this) {
1723                            PrintWriter catPw = new FastPrintWriter(catSw, false, 256);
1724                            String[] emptyArgs = new String[] { };
1725                            catPw.println();
1726                            dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
1727                            catPw.println();
1728                            mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1729                                    false, false, null);
1730                            catPw.println();
1731                            dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
1732                            catPw.flush();
1733                        }
1734                        dropBuilder.append(catSw.toString());
1735                        addErrorToDropBox("lowmem", null, "system_server", null,
1736                                null, tag.toString(), dropBuilder.toString(), null, null);
1737                        //Slog.i(TAG, "Sent to dropbox:");
1738                        //Slog.i(TAG, dropBuilder.toString());
1739                        synchronized (ActivityManagerService.this) {
1740                            long now = SystemClock.uptimeMillis();
1741                            if (mLastMemUsageReportTime < now) {
1742                                mLastMemUsageReportTime = now;
1743                            }
1744                        }
1745                    }
1746                };
1747                thread.start();
1748                break;
1749            }
1750            case REPORT_USER_SWITCH_MSG: {
1751                dispatchUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
1752                break;
1753            }
1754            case CONTINUE_USER_SWITCH_MSG: {
1755                continueUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
1756                break;
1757            }
1758            case USER_SWITCH_TIMEOUT_MSG: {
1759                timeoutUserSwitch((UserStartedState) msg.obj, msg.arg1, msg.arg2);
1760                break;
1761            }
1762            case IMMERSIVE_MODE_LOCK_MSG: {
1763                final boolean nextState = (msg.arg1 != 0);
1764                if (mUpdateLock.isHeld() != nextState) {
1765                    if (DEBUG_IMMERSIVE) {
1766                        final ActivityRecord r = (ActivityRecord) msg.obj;
1767                        Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1768                    }
1769                    if (nextState) {
1770                        mUpdateLock.acquire();
1771                    } else {
1772                        mUpdateLock.release();
1773                    }
1774                }
1775                break;
1776            }
1777            case PERSIST_URI_GRANTS_MSG: {
1778                writeGrantedUriPermissions();
1779                break;
1780            }
1781            case REQUEST_ALL_PSS_MSG: {
1782                requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
1783                break;
1784            }
1785            case START_PROFILES_MSG: {
1786                synchronized (ActivityManagerService.this) {
1787                    startProfilesLocked();
1788                }
1789                break;
1790            }
1791            case UPDATE_TIME: {
1792                synchronized (ActivityManagerService.this) {
1793                    for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1794                        ProcessRecord r = mLruProcesses.get(i);
1795                        if (r.thread != null) {
1796                            try {
1797                                r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true);
1798                            } catch (RemoteException ex) {
1799                                Slog.w(TAG, "Failed to update preferences for: " + r.info.processName);
1800                            }
1801                        }
1802                    }
1803                }
1804                break;
1805            }
1806            case SYSTEM_USER_START_MSG: {
1807                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
1808                        Integer.toString(msg.arg1), msg.arg1);
1809                mSystemServiceManager.startUser(msg.arg1);
1810                break;
1811            }
1812            case SYSTEM_USER_CURRENT_MSG: {
1813                mBatteryStatsService.noteEvent(
1814                        BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
1815                        Integer.toString(msg.arg2), msg.arg2);
1816                mBatteryStatsService.noteEvent(
1817                        BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
1818                        Integer.toString(msg.arg1), msg.arg1);
1819                mSystemServiceManager.switchUser(msg.arg1);
1820                break;
1821            }
1822            case ENTER_ANIMATION_COMPLETE_MSG: {
1823                synchronized (ActivityManagerService.this) {
1824                    ActivityRecord r = ActivityRecord.forToken((IBinder) msg.obj);
1825                    if (r != null && r.app != null && r.app.thread != null) {
1826                        try {
1827                            r.app.thread.scheduleEnterAnimationComplete(r.appToken);
1828                        } catch (RemoteException e) {
1829                        }
1830                    }
1831                }
1832                break;
1833            }
1834            case ENABLE_SCREEN_AFTER_BOOT_MSG: {
1835                enableScreenAfterBoot();
1836                break;
1837            }
1838            }
1839        }
1840    };
1841
1842    static final int COLLECT_PSS_BG_MSG = 1;
1843
1844    final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) {
1845        @Override
1846        public void handleMessage(Message msg) {
1847            switch (msg.what) {
1848            case COLLECT_PSS_BG_MSG: {
1849                long start = SystemClock.uptimeMillis();
1850                MemInfoReader memInfo = null;
1851                synchronized (ActivityManagerService.this) {
1852                    if (mFullPssPending) {
1853                        mFullPssPending = false;
1854                        memInfo = new MemInfoReader();
1855                    }
1856                }
1857                if (memInfo != null) {
1858                    updateCpuStatsNow();
1859                    long nativeTotalPss = 0;
1860                    synchronized (mProcessCpuThread) {
1861                        final int N = mProcessCpuTracker.countStats();
1862                        for (int j=0; j<N; j++) {
1863                            ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j);
1864                            if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) {
1865                                // This is definitely an application process; skip it.
1866                                continue;
1867                            }
1868                            synchronized (mPidsSelfLocked) {
1869                                if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) {
1870                                    // This is one of our own processes; skip it.
1871                                    continue;
1872                                }
1873                            }
1874                            nativeTotalPss += Debug.getPss(st.pid, null);
1875                        }
1876                    }
1877                    memInfo.readMemInfo();
1878                    synchronized (this) {
1879                        if (DEBUG_PSS) Slog.d(TAG, "Collected native and kernel memory in "
1880                                + (SystemClock.uptimeMillis()-start) + "ms");
1881                        mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(),
1882                                memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(),
1883                                memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()
1884                                        +memInfo.getSlabSizeKb(),
1885                                nativeTotalPss);
1886                    }
1887                }
1888
1889                int i=0, num=0;
1890                long[] tmp = new long[1];
1891                do {
1892                    ProcessRecord proc;
1893                    int procState;
1894                    int pid;
1895                    synchronized (ActivityManagerService.this) {
1896                        if (i >= mPendingPssProcesses.size()) {
1897                            if (DEBUG_PSS) Slog.d(TAG, "Collected PSS of " + num + " of " + i
1898                                    + " processes in " + (SystemClock.uptimeMillis()-start) + "ms");
1899                            mPendingPssProcesses.clear();
1900                            return;
1901                        }
1902                        proc = mPendingPssProcesses.get(i);
1903                        procState = proc.pssProcState;
1904                        if (proc.thread != null && procState == proc.setProcState) {
1905                            pid = proc.pid;
1906                        } else {
1907                            proc = null;
1908                            pid = 0;
1909                        }
1910                        i++;
1911                    }
1912                    if (proc != null) {
1913                        long pss = Debug.getPss(pid, tmp);
1914                        synchronized (ActivityManagerService.this) {
1915                            if (proc.thread != null && proc.setProcState == procState
1916                                    && proc.pid == pid) {
1917                                num++;
1918                                proc.lastPssTime = SystemClock.uptimeMillis();
1919                                proc.baseProcessTracker.addPss(pss, tmp[0], true, proc.pkgList);
1920                                if (DEBUG_PSS) Slog.d(TAG, "PSS of " + proc.toShortString()
1921                                        + ": " + pss + " lastPss=" + proc.lastPss
1922                                        + " state=" + ProcessList.makeProcStateString(procState));
1923                                if (proc.initialIdlePss == 0) {
1924                                    proc.initialIdlePss = pss;
1925                                }
1926                                proc.lastPss = pss;
1927                                if (procState >= ActivityManager.PROCESS_STATE_HOME) {
1928                                    proc.lastCachedPss = pss;
1929                                }
1930                            }
1931                        }
1932                    }
1933                } while (true);
1934            }
1935            }
1936        }
1937    };
1938
1939    /**
1940     * Monitor for package changes and update our internal state.
1941     */
1942    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
1943        @Override
1944        public void onPackageRemoved(String packageName, int uid) {
1945            // Remove all tasks with activities in the specified package from the list of recent tasks
1946            synchronized (ActivityManagerService.this) {
1947                for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
1948                    TaskRecord tr = mRecentTasks.get(i);
1949                    ComponentName cn = tr.intent.getComponent();
1950                    if (cn != null && cn.getPackageName().equals(packageName)) {
1951                        // If the package name matches, remove the task and kill the process
1952                        removeTaskByIdLocked(tr.taskId, ActivityManager.REMOVE_TASK_KILL_PROCESS);
1953                    }
1954                }
1955            }
1956        }
1957
1958        @Override
1959        public boolean onPackageChanged(String packageName, int uid, String[] components) {
1960            onPackageModified(packageName);
1961            return true;
1962        }
1963
1964        @Override
1965        public void onPackageModified(String packageName) {
1966            final PackageManager pm = mContext.getPackageManager();
1967            final ArrayList<Pair<Intent, Integer>> recentTaskIntents =
1968                    new ArrayList<Pair<Intent, Integer>>();
1969            final ArrayList<Integer> tasksToRemove = new ArrayList<Integer>();
1970            // Copy the list of recent tasks so that we don't hold onto the lock on
1971            // ActivityManagerService for long periods while checking if components exist.
1972            synchronized (ActivityManagerService.this) {
1973                for (int i = mRecentTasks.size() - 1; i >= 0; i--) {
1974                    TaskRecord tr = mRecentTasks.get(i);
1975                    recentTaskIntents.add(new Pair<Intent, Integer>(tr.intent, tr.taskId));
1976                }
1977            }
1978            // Check the recent tasks and filter out all tasks with components that no longer exist.
1979            Intent tmpI = new Intent();
1980            for (int i = recentTaskIntents.size() - 1; i >= 0; i--) {
1981                Pair<Intent, Integer> p = recentTaskIntents.get(i);
1982                ComponentName cn = p.first.getComponent();
1983                if (cn != null && cn.getPackageName().equals(packageName)) {
1984                    try {
1985                        // Add the task to the list to remove if the component no longer exists
1986                        tmpI.setComponent(cn);
1987                        if (pm.queryIntentActivities(tmpI, PackageManager.MATCH_DEFAULT_ONLY).isEmpty()) {
1988                            tasksToRemove.add(p.second);
1989                        }
1990                    } catch (Exception e) {}
1991                }
1992            }
1993            // Prune all the tasks with removed components from the list of recent tasks
1994            synchronized (ActivityManagerService.this) {
1995                for (int i = tasksToRemove.size() - 1; i >= 0; i--) {
1996                    // Remove the task but don't kill the process (since other components in that
1997                    // package may still be running and in the background)
1998                    removeTaskByIdLocked(tasksToRemove.get(i), 0);
1999                }
2000            }
2001        }
2002
2003        @Override
2004        public boolean onHandleForceStop(Intent intent, String[] packages, int uid, boolean doit) {
2005            // Force stop the specified packages
2006            if (packages != null) {
2007                for (String pkg : packages) {
2008                    synchronized (ActivityManagerService.this) {
2009                        if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 0,
2010                                "finished booting")) {
2011                            return true;
2012                        }
2013                    }
2014                }
2015            }
2016            return false;
2017        }
2018    };
2019
2020    public void setSystemProcess() {
2021        try {
2022            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
2023            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
2024            ServiceManager.addService("meminfo", new MemBinder(this));
2025            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2026            ServiceManager.addService("dbinfo", new DbBinder(this));
2027            if (MONITOR_CPU_USAGE) {
2028                ServiceManager.addService("cpuinfo", new CpuBinder(this));
2029            }
2030            ServiceManager.addService("permission", new PermissionController(this));
2031
2032            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2033                    "android", STOCK_PM_FLAGS);
2034            mSystemThread.installSystemApplicationInfo(info);
2035
2036            synchronized (this) {
2037                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2038                app.persistent = true;
2039                app.pid = MY_PID;
2040                app.maxAdj = ProcessList.SYSTEM_ADJ;
2041                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2042                mProcessNames.put(app.processName, app.uid, app);
2043                synchronized (mPidsSelfLocked) {
2044                    mPidsSelfLocked.put(app.pid, app);
2045                }
2046                updateLruProcessLocked(app, false, null);
2047                updateOomAdjLocked();
2048            }
2049        } catch (PackageManager.NameNotFoundException e) {
2050            throw new RuntimeException(
2051                    "Unable to find android system package", e);
2052        }
2053    }
2054
2055    public void setWindowManager(WindowManagerService wm) {
2056        mWindowManager = wm;
2057        mStackSupervisor.setWindowManager(wm);
2058    }
2059
2060    public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
2061        mUsageStatsService = usageStatsManager;
2062    }
2063
2064    public void startObservingNativeCrashes() {
2065        final NativeCrashListener ncl = new NativeCrashListener(this);
2066        ncl.start();
2067    }
2068
2069    public IAppOpsService getAppOpsService() {
2070        return mAppOpsService;
2071    }
2072
2073    static class MemBinder extends Binder {
2074        ActivityManagerService mActivityManagerService;
2075        MemBinder(ActivityManagerService activityManagerService) {
2076            mActivityManagerService = activityManagerService;
2077        }
2078
2079        @Override
2080        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2081            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2082                    != PackageManager.PERMISSION_GRANTED) {
2083                pw.println("Permission Denial: can't dump meminfo from from pid="
2084                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2085                        + " without permission " + android.Manifest.permission.DUMP);
2086                return;
2087            }
2088
2089            mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, "  ", args, false, null);
2090        }
2091    }
2092
2093    static class GraphicsBinder extends Binder {
2094        ActivityManagerService mActivityManagerService;
2095        GraphicsBinder(ActivityManagerService activityManagerService) {
2096            mActivityManagerService = activityManagerService;
2097        }
2098
2099        @Override
2100        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2101            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2102                    != PackageManager.PERMISSION_GRANTED) {
2103                pw.println("Permission Denial: can't dump gfxinfo from from pid="
2104                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2105                        + " without permission " + android.Manifest.permission.DUMP);
2106                return;
2107            }
2108
2109            mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
2110        }
2111    }
2112
2113    static class DbBinder extends Binder {
2114        ActivityManagerService mActivityManagerService;
2115        DbBinder(ActivityManagerService activityManagerService) {
2116            mActivityManagerService = activityManagerService;
2117        }
2118
2119        @Override
2120        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2121            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2122                    != PackageManager.PERMISSION_GRANTED) {
2123                pw.println("Permission Denial: can't dump dbinfo from from pid="
2124                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2125                        + " without permission " + android.Manifest.permission.DUMP);
2126                return;
2127            }
2128
2129            mActivityManagerService.dumpDbInfo(fd, pw, args);
2130        }
2131    }
2132
2133    static class CpuBinder extends Binder {
2134        ActivityManagerService mActivityManagerService;
2135        CpuBinder(ActivityManagerService activityManagerService) {
2136            mActivityManagerService = activityManagerService;
2137        }
2138
2139        @Override
2140        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2141            if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
2142                    != PackageManager.PERMISSION_GRANTED) {
2143                pw.println("Permission Denial: can't dump cpuinfo from from pid="
2144                        + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2145                        + " without permission " + android.Manifest.permission.DUMP);
2146                return;
2147            }
2148
2149            synchronized (mActivityManagerService.mProcessCpuThread) {
2150                pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad());
2151                pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState(
2152                        SystemClock.uptimeMillis()));
2153            }
2154        }
2155    }
2156
2157    public static final class Lifecycle extends SystemService {
2158        private final ActivityManagerService mService;
2159
2160        public Lifecycle(Context context) {
2161            super(context);
2162            mService = new ActivityManagerService(context);
2163        }
2164
2165        @Override
2166        public void onStart() {
2167            mService.start();
2168        }
2169
2170        public ActivityManagerService getService() {
2171            return mService;
2172        }
2173    }
2174
2175    // Note: This method is invoked on the main thread but may need to attach various
2176    // handlers to other threads.  So take care to be explicit about the looper.
2177    public ActivityManagerService(Context systemContext) {
2178        mContext = systemContext;
2179        mFactoryTest = FactoryTest.getMode();
2180        mSystemThread = ActivityThread.currentActivityThread();
2181
2182        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2183
2184        mHandlerThread = new ServiceThread(TAG,
2185                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2186        mHandlerThread.start();
2187        mHandler = new MainHandler(mHandlerThread.getLooper());
2188
2189        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2190                "foreground", BROADCAST_FG_TIMEOUT, false);
2191        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2192                "background", BROADCAST_BG_TIMEOUT, true);
2193        mBroadcastQueues[0] = mFgBroadcastQueue;
2194        mBroadcastQueues[1] = mBgBroadcastQueue;
2195
2196        mServices = new ActiveServices(this);
2197        mProviderMap = new ProviderMap(this);
2198
2199        // TODO: Move creation of battery stats service outside of activity manager service.
2200        File dataDir = Environment.getDataDirectory();
2201        File systemDir = new File(dataDir, "system");
2202        systemDir.mkdirs();
2203        mBatteryStatsService = new BatteryStatsService(new File(
2204                systemDir, "batterystats.bin").toString(), mHandler);
2205        mBatteryStatsService.getActiveStatistics().readLocked();
2206        mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
2207        mOnBattery = DEBUG_POWER ? true
2208                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2209        mBatteryStatsService.getActiveStatistics().setCallback(this);
2210
2211        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2212
2213        mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
2214
2215        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
2216
2217        // User 0 is the first and only user that runs at boot.
2218        mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
2219        mUserLru.add(Integer.valueOf(0));
2220        updateStartedUserArrayLocked();
2221
2222        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2223            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2224
2225        mConfiguration.setToDefaults();
2226        mConfiguration.setLocale(Locale.getDefault());
2227
2228        mConfigurationSeq = mConfiguration.seq = 1;
2229        mProcessCpuTracker.init();
2230
2231        mHasRecents = mContext.getResources().getBoolean(
2232                com.android.internal.R.bool.config_hasRecents);
2233
2234        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
2235        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2236        mStackSupervisor = new ActivityStackSupervisor(this);
2237        mTaskPersister = new TaskPersister(systemDir, mStackSupervisor);
2238
2239        mProcessCpuThread = new Thread("CpuTracker") {
2240            @Override
2241            public void run() {
2242                while (true) {
2243                    try {
2244                        try {
2245                            synchronized(this) {
2246                                final long now = SystemClock.uptimeMillis();
2247                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2248                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2249                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2250                                //        + ", write delay=" + nextWriteDelay);
2251                                if (nextWriteDelay < nextCpuDelay) {
2252                                    nextCpuDelay = nextWriteDelay;
2253                                }
2254                                if (nextCpuDelay > 0) {
2255                                    mProcessCpuMutexFree.set(true);
2256                                    this.wait(nextCpuDelay);
2257                                }
2258                            }
2259                        } catch (InterruptedException e) {
2260                        }
2261                        updateCpuStatsNow();
2262                    } catch (Exception e) {
2263                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
2264                    }
2265                }
2266            }
2267        };
2268
2269        mLockToAppRequest = new LockToAppRequestDialog(mContext, this);
2270
2271        Watchdog.getInstance().addMonitor(this);
2272        Watchdog.getInstance().addThread(mHandler);
2273    }
2274
2275    public void setSystemServiceManager(SystemServiceManager mgr) {
2276        mSystemServiceManager = mgr;
2277    }
2278
2279    private void start() {
2280        Process.removeAllProcessGroups();
2281        mProcessCpuThread.start();
2282
2283        mBatteryStatsService.publish(mContext);
2284        mAppOpsService.publish(mContext);
2285        Slog.d("AppOps", "AppOpsService published");
2286        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
2287    }
2288
2289    public void initPowerManagement() {
2290        mStackSupervisor.initPowerManagement();
2291        mBatteryStatsService.initPowerManagement();
2292    }
2293
2294    @Override
2295    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2296            throws RemoteException {
2297        if (code == SYSPROPS_TRANSACTION) {
2298            // We need to tell all apps about the system property change.
2299            ArrayList<IBinder> procs = new ArrayList<IBinder>();
2300            synchronized(this) {
2301                final int NP = mProcessNames.getMap().size();
2302                for (int ip=0; ip<NP; ip++) {
2303                    SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
2304                    final int NA = apps.size();
2305                    for (int ia=0; ia<NA; ia++) {
2306                        ProcessRecord app = apps.valueAt(ia);
2307                        if (app.thread != null) {
2308                            procs.add(app.thread.asBinder());
2309                        }
2310                    }
2311                }
2312            }
2313
2314            int N = procs.size();
2315            for (int i=0; i<N; i++) {
2316                Parcel data2 = Parcel.obtain();
2317                try {
2318                    procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
2319                } catch (RemoteException e) {
2320                }
2321                data2.recycle();
2322            }
2323        }
2324        try {
2325            return super.onTransact(code, data, reply, flags);
2326        } catch (RuntimeException e) {
2327            // The activity manager only throws security exceptions, so let's
2328            // log all others.
2329            if (!(e instanceof SecurityException)) {
2330                Slog.wtf(TAG, "Activity Manager Crash", e);
2331            }
2332            throw e;
2333        }
2334    }
2335
2336    void updateCpuStats() {
2337        final long now = SystemClock.uptimeMillis();
2338        if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
2339            return;
2340        }
2341        if (mProcessCpuMutexFree.compareAndSet(true, false)) {
2342            synchronized (mProcessCpuThread) {
2343                mProcessCpuThread.notify();
2344            }
2345        }
2346    }
2347
2348    void updateCpuStatsNow() {
2349        synchronized (mProcessCpuThread) {
2350            mProcessCpuMutexFree.set(false);
2351            final long now = SystemClock.uptimeMillis();
2352            boolean haveNewCpuStats = false;
2353
2354            if (MONITOR_CPU_USAGE &&
2355                    mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
2356                mLastCpuTime.set(now);
2357                haveNewCpuStats = true;
2358                mProcessCpuTracker.update();
2359                //Slog.i(TAG, mProcessCpu.printCurrentState());
2360                //Slog.i(TAG, "Total CPU usage: "
2361                //        + mProcessCpu.getTotalCpuPercent() + "%");
2362
2363                // Slog the cpu usage if the property is set.
2364                if ("true".equals(SystemProperties.get("events.cpu"))) {
2365                    int user = mProcessCpuTracker.getLastUserTime();
2366                    int system = mProcessCpuTracker.getLastSystemTime();
2367                    int iowait = mProcessCpuTracker.getLastIoWaitTime();
2368                    int irq = mProcessCpuTracker.getLastIrqTime();
2369                    int softIrq = mProcessCpuTracker.getLastSoftIrqTime();
2370                    int idle = mProcessCpuTracker.getLastIdleTime();
2371
2372                    int total = user + system + iowait + irq + softIrq + idle;
2373                    if (total == 0) total = 1;
2374
2375                    EventLog.writeEvent(EventLogTags.CPU,
2376                            ((user+system+iowait+irq+softIrq) * 100) / total,
2377                            (user * 100) / total,
2378                            (system * 100) / total,
2379                            (iowait * 100) / total,
2380                            (irq * 100) / total,
2381                            (softIrq * 100) / total);
2382                }
2383            }
2384
2385            long[] cpuSpeedTimes = mProcessCpuTracker.getLastCpuSpeedTimes();
2386            final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
2387            synchronized(bstats) {
2388                synchronized(mPidsSelfLocked) {
2389                    if (haveNewCpuStats) {
2390                        if (mOnBattery) {
2391                            int perc = bstats.startAddingCpuLocked();
2392                            int totalUTime = 0;
2393                            int totalSTime = 0;
2394                            final int N = mProcessCpuTracker.countStats();
2395                            for (int i=0; i<N; i++) {
2396                                ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
2397                                if (!st.working) {
2398                                    continue;
2399                                }
2400                                ProcessRecord pr = mPidsSelfLocked.get(st.pid);
2401                                int otherUTime = (st.rel_utime*perc)/100;
2402                                int otherSTime = (st.rel_stime*perc)/100;
2403                                totalUTime += otherUTime;
2404                                totalSTime += otherSTime;
2405                                if (pr != null) {
2406                                    BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats;
2407                                    if (ps == null || !ps.isActive()) {
2408                                        pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked(
2409                                                pr.info.uid, pr.processName);
2410                                    }
2411                                    ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2412                                            st.rel_stime-otherSTime);
2413                                    ps.addSpeedStepTimes(cpuSpeedTimes);
2414                                    pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
2415                                } else {
2416                                    BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
2417                                    if (ps == null || !ps.isActive()) {
2418                                        st.batteryStats = ps = bstats.getProcessStatsLocked(
2419                                                bstats.mapUid(st.uid), st.name);
2420                                    }
2421                                    ps.addCpuTimeLocked(st.rel_utime-otherUTime,
2422                                            st.rel_stime-otherSTime);
2423                                    ps.addSpeedStepTimes(cpuSpeedTimes);
2424                                }
2425                            }
2426                            bstats.finishAddingCpuLocked(perc, totalUTime,
2427                                    totalSTime, cpuSpeedTimes);
2428                        }
2429                    }
2430                }
2431
2432                if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
2433                    mLastWriteTime = now;
2434                    mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
2435                }
2436            }
2437        }
2438    }
2439
2440    @Override
2441    public void batteryNeedsCpuUpdate() {
2442        updateCpuStatsNow();
2443    }
2444
2445    @Override
2446    public void batteryPowerChanged(boolean onBattery) {
2447        // When plugging in, update the CPU stats first before changing
2448        // the plug state.
2449        updateCpuStatsNow();
2450        synchronized (this) {
2451            synchronized(mPidsSelfLocked) {
2452                mOnBattery = DEBUG_POWER ? true : onBattery;
2453            }
2454        }
2455    }
2456
2457    /**
2458     * Initialize the application bind args. These are passed to each
2459     * process when the bindApplication() IPC is sent to the process. They're
2460     * lazily setup to make sure the services are running when they're asked for.
2461     */
2462    private HashMap<String, IBinder> getCommonServicesLocked() {
2463        if (mAppBindArgs == null) {
2464            mAppBindArgs = new HashMap<String, IBinder>();
2465
2466            // Setup the application init args
2467            mAppBindArgs.put("package", ServiceManager.getService("package"));
2468            mAppBindArgs.put("window", ServiceManager.getService("window"));
2469            mAppBindArgs.put(Context.ALARM_SERVICE,
2470                    ServiceManager.getService(Context.ALARM_SERVICE));
2471        }
2472        return mAppBindArgs;
2473    }
2474
2475    final void setFocusedActivityLocked(ActivityRecord r) {
2476        if (mFocusedActivity != r) {
2477            if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedActivityLocked: r=" + r);
2478            mFocusedActivity = r;
2479            if (r.task != null && r.task.voiceInteractor != null) {
2480                startRunningVoiceLocked();
2481            } else {
2482                finishRunningVoiceLocked();
2483            }
2484            mStackSupervisor.setFocusedStack(r);
2485            if (r != null) {
2486                mWindowManager.setFocusedApp(r.appToken, true);
2487            }
2488            applyUpdateLockStateLocked(r);
2489        }
2490    }
2491
2492    final void clearFocusedActivity(ActivityRecord r) {
2493        if (mFocusedActivity == r) {
2494            mFocusedActivity = null;
2495        }
2496    }
2497
2498    @Override
2499    public void setFocusedStack(int stackId) {
2500        if (DEBUG_FOCUS) Slog.d(TAG, "setFocusedStack: stackId=" + stackId);
2501        synchronized (ActivityManagerService.this) {
2502            ActivityStack stack = mStackSupervisor.getStack(stackId);
2503            if (stack != null) {
2504                ActivityRecord r = stack.topRunningActivityLocked(null);
2505                if (r != null) {
2506                    setFocusedActivityLocked(r);
2507                }
2508            }
2509        }
2510    }
2511
2512    @Override
2513    public void notifyActivityDrawn(IBinder token) {
2514        if (DEBUG_VISBILITY) Slog.d(TAG, "notifyActivityDrawn: token=" + token);
2515        synchronized (this) {
2516            ActivityRecord r= mStackSupervisor.isInAnyStackLocked(token);
2517            if (r != null) {
2518                r.task.stack.notifyActivityDrawnLocked(r);
2519            }
2520        }
2521    }
2522
2523    final void applyUpdateLockStateLocked(ActivityRecord r) {
2524        // Modifications to the UpdateLock state are done on our handler, outside
2525        // the activity manager's locks.  The new state is determined based on the
2526        // state *now* of the relevant activity record.  The object is passed to
2527        // the handler solely for logging detail, not to be consulted/modified.
2528        final boolean nextState = r != null && r.immersive;
2529        mHandler.sendMessage(
2530                mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
2531    }
2532
2533    final void showAskCompatModeDialogLocked(ActivityRecord r) {
2534        Message msg = Message.obtain();
2535        msg.what = SHOW_COMPAT_MODE_DIALOG_MSG;
2536        msg.obj = r.task.askedCompatMode ? null : r;
2537        mHandler.sendMessage(msg);
2538    }
2539
2540    private final int updateLruProcessInternalLocked(ProcessRecord app, long now, int index,
2541            String what, Object obj, ProcessRecord srcApp) {
2542        app.lastActivityTime = now;
2543
2544        if (app.activities.size() > 0) {
2545            // Don't want to touch dependent processes that are hosting activities.
2546            return index;
2547        }
2548
2549        int lrui = mLruProcesses.lastIndexOf(app);
2550        if (lrui < 0) {
2551            Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: "
2552                    + what + " " + obj + " from " + srcApp);
2553            return index;
2554        }
2555
2556        if (lrui >= index) {
2557            // Don't want to cause this to move dependent processes *back* in the
2558            // list as if they were less frequently used.
2559            return index;
2560        }
2561
2562        if (lrui >= mLruProcessActivityStart) {
2563            // Don't want to touch dependent processes that are hosting activities.
2564            return index;
2565        }
2566
2567        mLruProcesses.remove(lrui);
2568        if (index > 0) {
2569            index--;
2570        }
2571        if (DEBUG_LRU) Slog.d(TAG, "Moving dep from " + lrui + " to " + index
2572                + " in LRU list: " + app);
2573        mLruProcesses.add(index, app);
2574        return index;
2575    }
2576
2577    final void removeLruProcessLocked(ProcessRecord app) {
2578        int lrui = mLruProcesses.lastIndexOf(app);
2579        if (lrui >= 0) {
2580            if (lrui <= mLruProcessActivityStart) {
2581                mLruProcessActivityStart--;
2582            }
2583            if (lrui <= mLruProcessServiceStart) {
2584                mLruProcessServiceStart--;
2585            }
2586            mLruProcesses.remove(lrui);
2587        }
2588    }
2589
2590    final void updateLruProcessLocked(ProcessRecord app, boolean activityChange,
2591            ProcessRecord client) {
2592        final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities
2593                || app.treatLikeActivity;
2594        final boolean hasService = false; // not impl yet. app.services.size() > 0;
2595        if (!activityChange && hasActivity) {
2596            // The process has activities, so we are only allowing activity-based adjustments
2597            // to move it.  It should be kept in the front of the list with other
2598            // processes that have activities, and we don't want those to change their
2599            // order except due to activity operations.
2600            return;
2601        }
2602
2603        mLruSeq++;
2604        final long now = SystemClock.uptimeMillis();
2605        app.lastActivityTime = now;
2606
2607        // First a quick reject: if the app is already at the position we will
2608        // put it, then there is nothing to do.
2609        if (hasActivity) {
2610            final int N = mLruProcesses.size();
2611            if (N > 0 && mLruProcesses.get(N-1) == app) {
2612                if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top activity: " + app);
2613                return;
2614            }
2615        } else {
2616            if (mLruProcessServiceStart > 0
2617                    && mLruProcesses.get(mLruProcessServiceStart-1) == app) {
2618                if (DEBUG_LRU) Slog.d(TAG, "Not moving, already top other: " + app);
2619                return;
2620            }
2621        }
2622
2623        int lrui = mLruProcesses.lastIndexOf(app);
2624
2625        if (app.persistent && lrui >= 0) {
2626            // We don't care about the position of persistent processes, as long as
2627            // they are in the list.
2628            if (DEBUG_LRU) Slog.d(TAG, "Not moving, persistent: " + app);
2629            return;
2630        }
2631
2632        /* In progress: compute new position first, so we can avoid doing work
2633           if the process is not actually going to move.  Not yet working.
2634        int addIndex;
2635        int nextIndex;
2636        boolean inActivity = false, inService = false;
2637        if (hasActivity) {
2638            // Process has activities, put it at the very tipsy-top.
2639            addIndex = mLruProcesses.size();
2640            nextIndex = mLruProcessServiceStart;
2641            inActivity = true;
2642        } else if (hasService) {
2643            // Process has services, put it at the top of the service list.
2644            addIndex = mLruProcessActivityStart;
2645            nextIndex = mLruProcessServiceStart;
2646            inActivity = true;
2647            inService = true;
2648        } else  {
2649            // Process not otherwise of interest, it goes to the top of the non-service area.
2650            addIndex = mLruProcessServiceStart;
2651            if (client != null) {
2652                int clientIndex = mLruProcesses.lastIndexOf(client);
2653                if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating "
2654                        + app);
2655                if (clientIndex >= 0 && addIndex > clientIndex) {
2656                    addIndex = clientIndex;
2657                }
2658            }
2659            nextIndex = addIndex > 0 ? addIndex-1 : addIndex;
2660        }
2661
2662        Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act="
2663                + mLruProcessActivityStart + "): " + app);
2664        */
2665
2666        if (lrui >= 0) {
2667            if (lrui < mLruProcessActivityStart) {
2668                mLruProcessActivityStart--;
2669            }
2670            if (lrui < mLruProcessServiceStart) {
2671                mLruProcessServiceStart--;
2672            }
2673            /*
2674            if (addIndex > lrui) {
2675                addIndex--;
2676            }
2677            if (nextIndex > lrui) {
2678                nextIndex--;
2679            }
2680            */
2681            mLruProcesses.remove(lrui);
2682        }
2683
2684        /*
2685        mLruProcesses.add(addIndex, app);
2686        if (inActivity) {
2687            mLruProcessActivityStart++;
2688        }
2689        if (inService) {
2690            mLruProcessActivityStart++;
2691        }
2692        */
2693
2694        int nextIndex;
2695        if (hasActivity) {
2696            final int N = mLruProcesses.size();
2697            if (app.activities.size() == 0 && mLruProcessActivityStart < (N-1)) {
2698                // Process doesn't have activities, but has clients with
2699                // activities...  move it up, but one below the top (the top
2700                // should always have a real activity).
2701                if (DEBUG_LRU) Slog.d(TAG, "Adding to second-top of LRU activity list: " + app);
2702                mLruProcesses.add(N-1, app);
2703                // To keep it from spamming the LRU list (by making a bunch of clients),
2704                // we will push down any other entries owned by the app.
2705                final int uid = app.info.uid;
2706                for (int i=N-2; i>mLruProcessActivityStart; i--) {
2707                    ProcessRecord subProc = mLruProcesses.get(i);
2708                    if (subProc.info.uid == uid) {
2709                        // We want to push this one down the list.  If the process after
2710                        // it is for the same uid, however, don't do so, because we don't
2711                        // want them internally to be re-ordered.
2712                        if (mLruProcesses.get(i-1).info.uid != uid) {
2713                            if (DEBUG_LRU) Slog.d(TAG, "Pushing uid " + uid + " swapping at " + i
2714                                    + ": " + mLruProcesses.get(i) + " : " + mLruProcesses.get(i-1));
2715                            ProcessRecord tmp = mLruProcesses.get(i);
2716                            mLruProcesses.set(i, mLruProcesses.get(i-1));
2717                            mLruProcesses.set(i-1, tmp);
2718                            i--;
2719                        }
2720                    } else {
2721                        // A gap, we can stop here.
2722                        break;
2723                    }
2724                }
2725            } else {
2726                // Process has activities, put it at the very tipsy-top.
2727                if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU activity list: " + app);
2728                mLruProcesses.add(app);
2729            }
2730            nextIndex = mLruProcessServiceStart;
2731        } else if (hasService) {
2732            // Process has services, put it at the top of the service list.
2733            if (DEBUG_LRU) Slog.d(TAG, "Adding to top of LRU service list: " + app);
2734            mLruProcesses.add(mLruProcessActivityStart, app);
2735            nextIndex = mLruProcessServiceStart;
2736            mLruProcessActivityStart++;
2737        } else  {
2738            // Process not otherwise of interest, it goes to the top of the non-service area.
2739            int index = mLruProcessServiceStart;
2740            if (client != null) {
2741                // If there is a client, don't allow the process to be moved up higher
2742                // in the list than that client.
2743                int clientIndex = mLruProcesses.lastIndexOf(client);
2744                if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG, "Unknown client " + client
2745                        + " when updating " + app);
2746                if (clientIndex <= lrui) {
2747                    // Don't allow the client index restriction to push it down farther in the
2748                    // list than it already is.
2749                    clientIndex = lrui;
2750                }
2751                if (clientIndex >= 0 && index > clientIndex) {
2752                    index = clientIndex;
2753                }
2754            }
2755            if (DEBUG_LRU) Slog.d(TAG, "Adding at " + index + " of LRU list: " + app);
2756            mLruProcesses.add(index, app);
2757            nextIndex = index-1;
2758            mLruProcessActivityStart++;
2759            mLruProcessServiceStart++;
2760        }
2761
2762        // If the app is currently using a content provider or service,
2763        // bump those processes as well.
2764        for (int j=app.connections.size()-1; j>=0; j--) {
2765            ConnectionRecord cr = app.connections.valueAt(j);
2766            if (cr.binding != null && !cr.serviceDead && cr.binding.service != null
2767                    && cr.binding.service.app != null
2768                    && cr.binding.service.app.lruSeq != mLruSeq
2769                    && !cr.binding.service.app.persistent) {
2770                nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex,
2771                        "service connection", cr, app);
2772            }
2773        }
2774        for (int j=app.conProviders.size()-1; j>=0; j--) {
2775            ContentProviderRecord cpr = app.conProviders.get(j).provider;
2776            if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) {
2777                nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex,
2778                        "provider reference", cpr, app);
2779            }
2780        }
2781    }
2782
2783    final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) {
2784        if (uid == Process.SYSTEM_UID) {
2785            // The system gets to run in any process.  If there are multiple
2786            // processes with the same uid, just pick the first (this
2787            // should never happen).
2788            SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName);
2789            if (procs == null) return null;
2790            final int N = procs.size();
2791            for (int i = 0; i < N; i++) {
2792                if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
2793            }
2794        }
2795        ProcessRecord proc = mProcessNames.get(processName, uid);
2796        if (false && proc != null && !keepIfLarge
2797                && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY
2798                && proc.lastCachedPss >= 4000) {
2799            // Turn this condition on to cause killing to happen regularly, for testing.
2800            if (proc.baseProcessTracker != null) {
2801                proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
2802            }
2803            killUnneededProcessLocked(proc, Long.toString(proc.lastCachedPss)
2804                    + "k from cached");
2805        } else if (proc != null && !keepIfLarge
2806                && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
2807                && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2808            if (DEBUG_PSS) Slog.d(TAG, "May not keep " + proc + ": pss=" + proc.lastCachedPss);
2809            if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) {
2810                if (proc.baseProcessTracker != null) {
2811                    proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss);
2812                }
2813                killUnneededProcessLocked(proc, Long.toString(proc.lastCachedPss)
2814                        + "k from cached");
2815            }
2816        }
2817        return proc;
2818    }
2819
2820    void ensurePackageDexOpt(String packageName) {
2821        IPackageManager pm = AppGlobals.getPackageManager();
2822        try {
2823            if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) {
2824                mDidDexOpt = true;
2825            }
2826        } catch (RemoteException e) {
2827        }
2828    }
2829
2830    boolean isNextTransitionForward() {
2831        int transit = mWindowManager.getPendingAppTransition();
2832        return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
2833                || transit == AppTransition.TRANSIT_TASK_OPEN
2834                || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
2835    }
2836
2837    int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
2838            String processName, String abiOverride, int uid, Runnable crashHandler) {
2839        synchronized(this) {
2840            ApplicationInfo info = new ApplicationInfo();
2841            // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid.
2842            // For isolated processes, the former contains the parent's uid and the latter the
2843            // actual uid of the isolated process.
2844            // In the special case introduced by this method (which is, starting an isolated
2845            // process directly from the SystemServer without an actual parent app process) the
2846            // closest thing to a parent's uid is SYSTEM_UID.
2847            // The only important thing here is to keep AI.uid != PR.uid, in order to trigger
2848            // the |isolated| logic in the ProcessRecord constructor.
2849            info.uid = Process.SYSTEM_UID;
2850            info.processName = processName;
2851            info.className = entryPoint;
2852            info.packageName = "android";
2853            ProcessRecord proc = startProcessLocked(processName, info /* info */,
2854                    false /* knownToBeDead */, 0 /* intentFlags */, ""  /* hostingType */,
2855                    null /* hostingName */, true /* allowWhileBooting */, true /* isolated */,
2856                    uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs,
2857                    crashHandler);
2858            return proc != null ? proc.pid : 0;
2859        }
2860    }
2861
2862    final ProcessRecord startProcessLocked(String processName,
2863            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
2864            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2865            boolean isolated, boolean keepIfLarge) {
2866        return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
2867                hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
2868                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
2869                null /* crashHandler */);
2870    }
2871
2872    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
2873            boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
2874            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
2875            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
2876        ProcessRecord app;
2877        if (!isolated) {
2878            app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
2879        } else {
2880            // If this is an isolated process, it can't re-use an existing process.
2881            app = null;
2882        }
2883        // We don't have to do anything more if:
2884        // (1) There is an existing application record; and
2885        // (2) The caller doesn't think it is dead, OR there is no thread
2886        //     object attached to it so we know it couldn't have crashed; and
2887        // (3) There is a pid assigned to it, so it is either starting or
2888        //     already running.
2889        if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
2890                + " app=" + app + " knownToBeDead=" + knownToBeDead
2891                + " thread=" + (app != null ? app.thread : null)
2892                + " pid=" + (app != null ? app.pid : -1));
2893        if (app != null && app.pid > 0) {
2894            if (!knownToBeDead || app.thread == null) {
2895                // We already have the app running, or are waiting for it to
2896                // come up (we have a pid but not yet its thread), so keep it.
2897                if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
2898                // If this is a new package in the process, add the package to the list
2899                app.addPackage(info.packageName, info.versionCode, mProcessStats);
2900                return app;
2901            }
2902
2903            // An application record is attached to a previous process,
2904            // clean it up now.
2905            if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
2906            Process.killProcessGroup(app.info.uid, app.pid);
2907            handleAppDiedLocked(app, true, true);
2908        }
2909
2910        String hostingNameStr = hostingName != null
2911                ? hostingName.flattenToShortString() : null;
2912
2913        if (!isolated) {
2914            if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2915                // If we are in the background, then check to see if this process
2916                // is bad.  If so, we will just silently fail.
2917                if (mBadProcesses.get(info.processName, info.uid) != null) {
2918                    if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2919                            + "/" + info.processName);
2920                    return null;
2921                }
2922            } else {
2923                // When the user is explicitly starting a process, then clear its
2924                // crash count so that we won't make it bad until they see at
2925                // least one crash dialog again, and make the process good again
2926                // if it had been bad.
2927                if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
2928                        + "/" + info.processName);
2929                mProcessCrashTimes.remove(info.processName, info.uid);
2930                if (mBadProcesses.get(info.processName, info.uid) != null) {
2931                    EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2932                            UserHandle.getUserId(info.uid), info.uid,
2933                            info.processName);
2934                    mBadProcesses.remove(info.processName, info.uid);
2935                    if (app != null) {
2936                        app.bad = false;
2937                    }
2938                }
2939            }
2940        }
2941
2942        if (app == null) {
2943            app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
2944            app.crashHandler = crashHandler;
2945            if (app == null) {
2946                Slog.w(TAG, "Failed making new process record for "
2947                        + processName + "/" + info.uid + " isolated=" + isolated);
2948                return null;
2949            }
2950            mProcessNames.put(processName, app.uid, app);
2951            if (isolated) {
2952                mIsolatedProcesses.put(app.uid, app);
2953            }
2954        } else {
2955            // If this is a new package in the process, add the package to the list
2956            app.addPackage(info.packageName, info.versionCode, mProcessStats);
2957        }
2958
2959        // If the system is not ready yet, then hold off on starting this
2960        // process until it is.
2961        if (!mProcessesReady
2962                && !isAllowedWhileBooting(info)
2963                && !allowWhileBooting) {
2964            if (!mProcessesOnHold.contains(app)) {
2965                mProcessesOnHold.add(app);
2966            }
2967            if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
2968            return app;
2969        }
2970
2971        startProcessLocked(
2972                app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
2973        return (app.pid != 0) ? app : null;
2974    }
2975
2976    boolean isAllowedWhileBooting(ApplicationInfo ai) {
2977        return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2978    }
2979
2980    private final void startProcessLocked(ProcessRecord app,
2981            String hostingType, String hostingNameStr) {
2982        startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */,
2983                null /* entryPoint */, null /* entryPointArgs */);
2984    }
2985
2986    private final void startProcessLocked(ProcessRecord app, String hostingType,
2987            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
2988        if (app.pid > 0 && app.pid != MY_PID) {
2989            synchronized (mPidsSelfLocked) {
2990                mPidsSelfLocked.remove(app.pid);
2991                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2992            }
2993            app.setPid(0);
2994        }
2995
2996        if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2997                "startProcessLocked removing on hold: " + app);
2998        mProcessesOnHold.remove(app);
2999
3000        updateCpuStats();
3001
3002        try {
3003            int uid = app.uid;
3004
3005            int[] gids = null;
3006            int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
3007            if (!app.isolated) {
3008                int[] permGids = null;
3009                try {
3010                    final PackageManager pm = mContext.getPackageManager();
3011                    permGids = pm.getPackageGids(app.info.packageName);
3012
3013                    if (Environment.isExternalStorageEmulated()) {
3014                        if (pm.checkPermission(
3015                                android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
3016                                app.info.packageName) == PERMISSION_GRANTED) {
3017                            mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
3018                        } else {
3019                            mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
3020                        }
3021                    }
3022                } catch (PackageManager.NameNotFoundException e) {
3023                    Slog.w(TAG, "Unable to retrieve gids", e);
3024                }
3025
3026                /*
3027                 * Add shared application and profile GIDs so applications can share some
3028                 * resources like shared libraries and access user-wide resources
3029                 */
3030                if (permGids == null) {
3031                    gids = new int[2];
3032                } else {
3033                    gids = new int[permGids.length + 2];
3034                    System.arraycopy(permGids, 0, gids, 2, permGids.length);
3035                }
3036                gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
3037                gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
3038            }
3039            if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
3040                if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3041                        && mTopComponent != null
3042                        && app.processName.equals(mTopComponent.getPackageName())) {
3043                    uid = 0;
3044                }
3045                if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL
3046                        && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
3047                    uid = 0;
3048                }
3049            }
3050            int debugFlags = 0;
3051            if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3052                debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
3053                // Also turn on CheckJNI for debuggable apps. It's quite
3054                // awkward to turn on otherwise.
3055                debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3056            }
3057            // Run the app in safe mode if its manifest requests so or the
3058            // system is booted in safe mode.
3059            if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
3060                mSafeMode == true) {
3061                debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
3062            }
3063            if ("1".equals(SystemProperties.get("debug.checkjni"))) {
3064                debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
3065            }
3066            if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
3067                debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
3068            }
3069            if ("1".equals(SystemProperties.get("debug.assert"))) {
3070                debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
3071            }
3072
3073            String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
3074            if (requiredAbi == null) {
3075                requiredAbi = Build.SUPPORTED_ABIS[0];
3076            }
3077
3078            // Start the process.  It will either succeed and return a result containing
3079            // the PID of the new process, or else throw a RuntimeException.
3080            boolean isActivityProcess = (entryPoint == null);
3081            if (entryPoint == null) entryPoint = "android.app.ActivityThread";
3082            Process.ProcessStartResult startResult = Process.start(entryPoint,
3083                    app.processName, uid, uid, gids, debugFlags, mountExternal,
3084                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, entryPointArgs);
3085
3086            if (app.isolated) {
3087                mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid);
3088            }
3089            mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
3090
3091            EventLog.writeEvent(EventLogTags.AM_PROC_START,
3092                    UserHandle.getUserId(uid), startResult.pid, uid,
3093                    app.processName, hostingType,
3094                    hostingNameStr != null ? hostingNameStr : "");
3095
3096            if (app.persistent) {
3097                Watchdog.getInstance().processStarted(app.processName, startResult.pid);
3098            }
3099
3100            StringBuilder buf = mStringBuilder;
3101            buf.setLength(0);
3102            buf.append("Start proc ");
3103            buf.append(app.processName);
3104            if (!isActivityProcess) {
3105                buf.append(" [");
3106                buf.append(entryPoint);
3107                buf.append("]");
3108            }
3109            buf.append(" for ");
3110            buf.append(hostingType);
3111            if (hostingNameStr != null) {
3112                buf.append(" ");
3113                buf.append(hostingNameStr);
3114            }
3115            buf.append(": pid=");
3116            buf.append(startResult.pid);
3117            buf.append(" uid=");
3118            buf.append(uid);
3119            buf.append(" gids={");
3120            if (gids != null) {
3121                for (int gi=0; gi<gids.length; gi++) {
3122                    if (gi != 0) buf.append(", ");
3123                    buf.append(gids[gi]);
3124
3125                }
3126            }
3127            buf.append("}");
3128            if (requiredAbi != null) {
3129                buf.append(" abi=");
3130                buf.append(requiredAbi);
3131            }
3132            Slog.i(TAG, buf.toString());
3133            app.setPid(startResult.pid);
3134            app.usingWrapper = startResult.usingWrapper;
3135            app.removed = false;
3136            app.killedByAm = false;
3137            synchronized (mPidsSelfLocked) {
3138                this.mPidsSelfLocked.put(startResult.pid, app);
3139                if (isActivityProcess) {
3140                    Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
3141                    msg.obj = app;
3142                    mHandler.sendMessageDelayed(msg, startResult.usingWrapper
3143                            ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
3144                }
3145            }
3146        } catch (RuntimeException e) {
3147            // XXX do better error recovery.
3148            app.setPid(0);
3149            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
3150            if (app.isolated) {
3151                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
3152            }
3153            Slog.e(TAG, "Failure starting process " + app.processName, e);
3154        }
3155    }
3156
3157    void updateUsageStats(ActivityRecord component, boolean resumed) {
3158        if (DEBUG_SWITCH) Slog.d(TAG, "updateUsageStats: comp=" + component + "res=" + resumed);
3159        final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3160        if (resumed) {
3161            if (mUsageStatsService != null) {
3162                mUsageStatsService.reportEvent(component.realActivity, component.userId,
3163                        System.currentTimeMillis(),
3164                        UsageStats.Event.MOVE_TO_FOREGROUND);
3165            }
3166            synchronized (stats) {
3167                stats.noteActivityResumedLocked(component.app.uid);
3168            }
3169        } else {
3170            if (mUsageStatsService != null) {
3171                mUsageStatsService.reportEvent(component.realActivity, component.userId,
3172                        System.currentTimeMillis(),
3173                        UsageStats.Event.MOVE_TO_BACKGROUND);
3174            }
3175            synchronized (stats) {
3176                stats.noteActivityPausedLocked(component.app.uid);
3177            }
3178        }
3179    }
3180
3181    Intent getHomeIntent() {
3182        Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
3183        intent.setComponent(mTopComponent);
3184        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
3185            intent.addCategory(Intent.CATEGORY_HOME);
3186        }
3187        return intent;
3188    }
3189
3190    boolean startHomeActivityLocked(int userId) {
3191        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3192                && mTopAction == null) {
3193            // We are running in factory test mode, but unable to find
3194            // the factory test app, so just sit around displaying the
3195            // error message and don't try to start anything.
3196            return false;
3197        }
3198        Intent intent = getHomeIntent();
3199        ActivityInfo aInfo =
3200            resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
3201        if (aInfo != null) {
3202            intent.setComponent(new ComponentName(
3203                    aInfo.applicationInfo.packageName, aInfo.name));
3204            // Don't do this if the home app is currently being
3205            // instrumented.
3206            aInfo = new ActivityInfo(aInfo);
3207            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
3208            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
3209                    aInfo.applicationInfo.uid, true);
3210            if (app == null || app.instrumentationClass == null) {
3211                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
3212                mStackSupervisor.startHomeActivity(intent, aInfo);
3213            }
3214        }
3215
3216        return true;
3217    }
3218
3219    private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
3220        ActivityInfo ai = null;
3221        ComponentName comp = intent.getComponent();
3222        try {
3223            if (comp != null) {
3224                ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
3225            } else {
3226                ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
3227                        intent,
3228                        intent.resolveTypeIfNeeded(mContext.getContentResolver()),
3229                            flags, userId);
3230
3231                if (info != null) {
3232                    ai = info.activityInfo;
3233                }
3234            }
3235        } catch (RemoteException e) {
3236            // ignore
3237        }
3238
3239        return ai;
3240    }
3241
3242    /**
3243     * Starts the "new version setup screen" if appropriate.
3244     */
3245    void startSetupActivityLocked() {
3246        // Only do this once per boot.
3247        if (mCheckedForSetup) {
3248            return;
3249        }
3250
3251        // We will show this screen if the current one is a different
3252        // version than the last one shown, and we are not running in
3253        // low-level factory test mode.
3254        final ContentResolver resolver = mContext.getContentResolver();
3255        if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL &&
3256                Settings.Global.getInt(resolver,
3257                        Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
3258            mCheckedForSetup = true;
3259
3260            // See if we should be showing the platform update setup UI.
3261            Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
3262            List<ResolveInfo> ris = mContext.getPackageManager()
3263                    .queryIntentActivities(intent, PackageManager.GET_META_DATA);
3264
3265            // We don't allow third party apps to replace this.
3266            ResolveInfo ri = null;
3267            for (int i=0; ris != null && i<ris.size(); i++) {
3268                if ((ris.get(i).activityInfo.applicationInfo.flags
3269                        & ApplicationInfo.FLAG_SYSTEM) != 0) {
3270                    ri = ris.get(i);
3271                    break;
3272                }
3273            }
3274
3275            if (ri != null) {
3276                String vers = ri.activityInfo.metaData != null
3277                        ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
3278                        : null;
3279                if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
3280                    vers = ri.activityInfo.applicationInfo.metaData.getString(
3281                            Intent.METADATA_SETUP_VERSION);
3282                }
3283                String lastVers = Settings.Secure.getString(
3284                        resolver, Settings.Secure.LAST_SETUP_SHOWN);
3285                if (vers != null && !vers.equals(lastVers)) {
3286                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3287                    intent.setComponent(new ComponentName(
3288                            ri.activityInfo.packageName, ri.activityInfo.name));
3289                    mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo,
3290                            null, null, null, null, 0, 0, 0, null, 0, null, false, null, null);
3291                }
3292            }
3293        }
3294    }
3295
3296    CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
3297        return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
3298    }
3299
3300    void enforceNotIsolatedCaller(String caller) {
3301        if (UserHandle.isIsolated(Binder.getCallingUid())) {
3302            throw new SecurityException("Isolated process not allowed to call " + caller);
3303        }
3304    }
3305
3306    @Override
3307    public int getFrontActivityScreenCompatMode() {
3308        enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
3309        synchronized (this) {
3310            return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
3311        }
3312    }
3313
3314    @Override
3315    public void setFrontActivityScreenCompatMode(int mode) {
3316        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3317                "setFrontActivityScreenCompatMode");
3318        synchronized (this) {
3319            mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
3320        }
3321    }
3322
3323    @Override
3324    public int getPackageScreenCompatMode(String packageName) {
3325        enforceNotIsolatedCaller("getPackageScreenCompatMode");
3326        synchronized (this) {
3327            return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
3328        }
3329    }
3330
3331    @Override
3332    public void setPackageScreenCompatMode(String packageName, int mode) {
3333        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3334                "setPackageScreenCompatMode");
3335        synchronized (this) {
3336            mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
3337        }
3338    }
3339
3340    @Override
3341    public boolean getPackageAskScreenCompat(String packageName) {
3342        enforceNotIsolatedCaller("getPackageAskScreenCompat");
3343        synchronized (this) {
3344            return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
3345        }
3346    }
3347
3348    @Override
3349    public void setPackageAskScreenCompat(String packageName, boolean ask) {
3350        enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
3351                "setPackageAskScreenCompat");
3352        synchronized (this) {
3353            mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
3354        }
3355    }
3356
3357    private void dispatchProcessesChanged() {
3358        int N;
3359        synchronized (this) {
3360            N = mPendingProcessChanges.size();
3361            if (mActiveProcessChanges.length < N) {
3362                mActiveProcessChanges = new ProcessChangeItem[N];
3363            }
3364            mPendingProcessChanges.toArray(mActiveProcessChanges);
3365            mAvailProcessChanges.addAll(mPendingProcessChanges);
3366            mPendingProcessChanges.clear();
3367            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
3368        }
3369
3370        int i = mProcessObservers.beginBroadcast();
3371        while (i > 0) {
3372            i--;
3373            final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3374            if (observer != null) {
3375                try {
3376                    for (int j=0; j<N; j++) {
3377                        ProcessChangeItem item = mActiveProcessChanges[j];
3378                        if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
3379                            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
3380                                    + item.pid + " uid=" + item.uid + ": "
3381                                    + item.foregroundActivities);
3382                            observer.onForegroundActivitiesChanged(item.pid, item.uid,
3383                                    item.foregroundActivities);
3384                        }
3385                        if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) {
3386                            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "PROCSTATE CHANGED pid="
3387                                    + item.pid + " uid=" + item.uid + ": " + item.processState);
3388                            observer.onProcessStateChanged(item.pid, item.uid, item.processState);
3389                        }
3390                    }
3391                } catch (RemoteException e) {
3392                }
3393            }
3394        }
3395        mProcessObservers.finishBroadcast();
3396    }
3397
3398    private void dispatchProcessDied(int pid, int uid) {
3399        int i = mProcessObservers.beginBroadcast();
3400        while (i > 0) {
3401            i--;
3402            final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
3403            if (observer != null) {
3404                try {
3405                    observer.onProcessDied(pid, uid);
3406                } catch (RemoteException e) {
3407                }
3408            }
3409        }
3410        mProcessObservers.finishBroadcast();
3411    }
3412
3413    @Override
3414    public final int startActivity(IApplicationThread caller, String callingPackage,
3415            Intent intent, String resolvedType, IBinder resultTo,
3416            String resultWho, int requestCode, int startFlags,
3417            String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
3418        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
3419                resultWho, requestCode,
3420                startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
3421    }
3422
3423    @Override
3424    public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
3425            Intent intent, String resolvedType, IBinder resultTo,
3426            String resultWho, int requestCode, int startFlags,
3427            String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
3428        enforceNotIsolatedCaller("startActivity");
3429        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3430                false, ALLOW_FULL_ONLY, "startActivity", null);
3431        // TODO: Switch to user app stacks here.
3432        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
3433                null, null, resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
3434                null, null, options, userId, null);
3435    }
3436
3437    @Override
3438    public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
3439            Intent intent, String resolvedType, IBinder resultTo,
3440            String resultWho, int requestCode, int startFlags, String profileFile,
3441            ParcelFileDescriptor profileFd, Bundle options, int userId) {
3442        enforceNotIsolatedCaller("startActivityAndWait");
3443        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3444                false, ALLOW_FULL_ONLY, "startActivityAndWait", null);
3445        WaitResult res = new WaitResult();
3446        // TODO: Switch to user app stacks here.
3447        mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
3448                null, null, resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
3449                res, null, options, userId, null);
3450        return res;
3451    }
3452
3453    @Override
3454    public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
3455            Intent intent, String resolvedType, IBinder resultTo,
3456            String resultWho, int requestCode, int startFlags, Configuration config,
3457            Bundle options, int userId) {
3458        enforceNotIsolatedCaller("startActivityWithConfig");
3459        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3460                false, ALLOW_FULL_ONLY, "startActivityWithConfig", null);
3461        // TODO: Switch to user app stacks here.
3462        int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
3463                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
3464                null, null, null, config, options, userId, null);
3465        return ret;
3466    }
3467
3468    @Override
3469    public int startActivityIntentSender(IApplicationThread caller,
3470            IntentSender intent, Intent fillInIntent, String resolvedType,
3471            IBinder resultTo, String resultWho, int requestCode,
3472            int flagsMask, int flagsValues, Bundle options) {
3473        enforceNotIsolatedCaller("startActivityIntentSender");
3474        // Refuse possible leaked file descriptors
3475        if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
3476            throw new IllegalArgumentException("File descriptors passed in Intent");
3477        }
3478
3479        IIntentSender sender = intent.getTarget();
3480        if (!(sender instanceof PendingIntentRecord)) {
3481            throw new IllegalArgumentException("Bad PendingIntent object");
3482        }
3483
3484        PendingIntentRecord pir = (PendingIntentRecord)sender;
3485
3486        synchronized (this) {
3487            // If this is coming from the currently resumed activity, it is
3488            // effectively saying that app switches are allowed at this point.
3489            final ActivityStack stack = getFocusedStack();
3490            if (stack.mResumedActivity != null &&
3491                    stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) {
3492                mAppSwitchesAllowedTime = 0;
3493            }
3494        }
3495        int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
3496                resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null);
3497        return ret;
3498    }
3499
3500    @Override
3501    public int startVoiceActivity(String callingPackage, int callingPid, int callingUid,
3502            Intent intent, String resolvedType, IVoiceInteractionSession session,
3503            IVoiceInteractor interactor, int startFlags, String profileFile,
3504            ParcelFileDescriptor profileFd, Bundle options, int userId) {
3505        if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION)
3506                != PackageManager.PERMISSION_GRANTED) {
3507            String msg = "Permission Denial: startVoiceActivity() from pid="
3508                    + Binder.getCallingPid()
3509                    + ", uid=" + Binder.getCallingUid()
3510                    + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION;
3511            Slog.w(TAG, msg);
3512            throw new SecurityException(msg);
3513        }
3514        if (session == null || interactor == null) {
3515            throw new NullPointerException("null session or interactor");
3516        }
3517        userId = handleIncomingUser(callingPid, callingUid, userId,
3518                false, ALLOW_FULL_ONLY, "startVoiceActivity", null);
3519        // TODO: Switch to user app stacks here.
3520        return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent,
3521                resolvedType, session, interactor, null, null, 0, startFlags,
3522                profileFile, profileFd, null, null, options, userId, null);
3523    }
3524
3525    @Override
3526    public boolean startNextMatchingActivity(IBinder callingActivity,
3527            Intent intent, Bundle options) {
3528        // Refuse possible leaked file descriptors
3529        if (intent != null && intent.hasFileDescriptors() == true) {
3530            throw new IllegalArgumentException("File descriptors passed in Intent");
3531        }
3532
3533        synchronized (this) {
3534            final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity);
3535            if (r == null) {
3536                ActivityOptions.abort(options);
3537                return false;
3538            }
3539            if (r.app == null || r.app.thread == null) {
3540                // The caller is not running...  d'oh!
3541                ActivityOptions.abort(options);
3542                return false;
3543            }
3544            intent = new Intent(intent);
3545            // The caller is not allowed to change the data.
3546            intent.setDataAndType(r.intent.getData(), r.intent.getType());
3547            // And we are resetting to find the next component...
3548            intent.setComponent(null);
3549
3550            final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3551
3552            ActivityInfo aInfo = null;
3553            try {
3554                List<ResolveInfo> resolves =
3555                    AppGlobals.getPackageManager().queryIntentActivities(
3556                            intent, r.resolvedType,
3557                            PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
3558                            UserHandle.getCallingUserId());
3559
3560                // Look for the original activity in the list...
3561                final int N = resolves != null ? resolves.size() : 0;
3562                for (int i=0; i<N; i++) {
3563                    ResolveInfo rInfo = resolves.get(i);
3564                    if (rInfo.activityInfo.packageName.equals(r.packageName)
3565                            && rInfo.activityInfo.name.equals(r.info.name)) {
3566                        // We found the current one...  the next matching is
3567                        // after it.
3568                        i++;
3569                        if (i<N) {
3570                            aInfo = resolves.get(i).activityInfo;
3571                        }
3572                        if (debug) {
3573                            Slog.v(TAG, "Next matching activity: found current " + r.packageName
3574                                    + "/" + r.info.name);
3575                            Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName
3576                                    + "/" + aInfo.name);
3577                        }
3578                        break;
3579                    }
3580                }
3581            } catch (RemoteException e) {
3582            }
3583
3584            if (aInfo == null) {
3585                // Nobody who is next!
3586                ActivityOptions.abort(options);
3587                if (debug) Slog.d(TAG, "Next matching activity: nothing found");
3588                return false;
3589            }
3590
3591            intent.setComponent(new ComponentName(
3592                    aInfo.applicationInfo.packageName, aInfo.name));
3593            intent.setFlags(intent.getFlags()&~(
3594                    Intent.FLAG_ACTIVITY_FORWARD_RESULT|
3595                    Intent.FLAG_ACTIVITY_CLEAR_TOP|
3596                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
3597                    Intent.FLAG_ACTIVITY_NEW_TASK));
3598
3599            // Okay now we need to start the new activity, replacing the
3600            // currently running activity.  This is a little tricky because
3601            // we want to start the new one as if the current one is finished,
3602            // but not finish the current one first so that there is no flicker.
3603            // And thus...
3604            final boolean wasFinishing = r.finishing;
3605            r.finishing = true;
3606
3607            // Propagate reply information over to the new activity.
3608            final ActivityRecord resultTo = r.resultTo;
3609            final String resultWho = r.resultWho;
3610            final int requestCode = r.requestCode;
3611            r.resultTo = null;
3612            if (resultTo != null) {
3613                resultTo.removeResultsLocked(r, resultWho, requestCode);
3614            }
3615
3616            final long origId = Binder.clearCallingIdentity();
3617            int res = mStackSupervisor.startActivityLocked(r.app.thread, intent,
3618                    r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null,
3619                    resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0,
3620                    options, false, null, null);
3621            Binder.restoreCallingIdentity(origId);
3622
3623            r.finishing = wasFinishing;
3624            if (res != ActivityManager.START_SUCCESS) {
3625                return false;
3626            }
3627            return true;
3628        }
3629    }
3630
3631    @Override
3632    public final int startActivityFromRecents(int taskId, Bundle options) {
3633        if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) {
3634            String msg = "Permission Denial: startActivityFromRecents called without " +
3635                    START_TASKS_FROM_RECENTS;
3636            Slog.w(TAG, msg);
3637            throw new SecurityException(msg);
3638        }
3639        final int callingUid;
3640        final String callingPackage;
3641        final Intent intent;
3642        final int userId;
3643        synchronized (this) {
3644            final TaskRecord task = recentTaskForIdLocked(taskId);
3645            if (task == null) {
3646                throw new ActivityNotFoundException("Task " + taskId + " not found.");
3647            }
3648            callingUid = task.mCallingUid;
3649            callingPackage = task.mCallingPackage;
3650            intent = task.intent;
3651            userId = task.userId;
3652        }
3653        return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0,
3654                options, userId, null);
3655    }
3656
3657    final int startActivityInPackage(int uid, String callingPackage,
3658            Intent intent, String resolvedType, IBinder resultTo,
3659            String resultWho, int requestCode, int startFlags, Bundle options, int userId,
3660                    IActivityContainer container) {
3661
3662        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3663                false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
3664
3665        // TODO: Switch to user app stacks here.
3666        int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent, resolvedType,
3667                null, null, resultTo, resultWho, requestCode, startFlags,
3668                null, null, null, null, options, userId, container);
3669        return ret;
3670    }
3671
3672    @Override
3673    public final int startActivities(IApplicationThread caller, String callingPackage,
3674            Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
3675            int userId) {
3676        enforceNotIsolatedCaller("startActivities");
3677        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3678                false, ALLOW_FULL_ONLY, "startActivity", null);
3679        // TODO: Switch to user app stacks here.
3680        int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents,
3681                resolvedTypes, resultTo, options, userId);
3682        return ret;
3683    }
3684
3685    final int startActivitiesInPackage(int uid, String callingPackage,
3686            Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3687            Bundle options, int userId) {
3688
3689        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
3690                false, ALLOW_FULL_ONLY, "startActivityInPackage", null);
3691        // TODO: Switch to user app stacks here.
3692        int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes,
3693                resultTo, options, userId);
3694        return ret;
3695    }
3696
3697    //explicitly remove thd old information in mRecentTasks when removing existing user.
3698    private void removeRecentTasksForUserLocked(int userId) {
3699        if(userId <= 0) {
3700            Slog.i(TAG, "Can't remove recent task on user " + userId);
3701            return;
3702        }
3703
3704        for (int i = mRecentTasks.size() - 1; i >= 0; --i) {
3705            TaskRecord tr = mRecentTasks.get(i);
3706            if (tr.userId == userId) {
3707                if(DEBUG_TASKS) Slog.i(TAG, "remove RecentTask " + tr
3708                        + " when finishing user" + userId);
3709                tr.disposeThumbnail();
3710                mRecentTasks.remove(i);
3711            }
3712        }
3713
3714        // Remove tasks from persistent storage.
3715        mTaskPersister.wakeup(null, true);
3716    }
3717
3718    final void addRecentTaskLocked(TaskRecord task) {
3719        int N = mRecentTasks.size();
3720        // Quick case: check if the top-most recent task is the same.
3721        if (N > 0 && mRecentTasks.get(0) == task) {
3722            return;
3723        }
3724        // Another quick case: never add voice sessions.
3725        if (task.voiceSession != null) {
3726            return;
3727        }
3728        // Remove any existing entries that are the same kind of task.
3729        final Intent intent = task.intent;
3730        final boolean document = intent != null && intent.isDocument();
3731        final ComponentName comp = intent.getComponent();
3732
3733        int maxRecents = task.maxRecents - 1;
3734        for (int i=0; i<N; i++) {
3735            final TaskRecord tr = mRecentTasks.get(i);
3736            if (task != tr) {
3737                if (task.userId != tr.userId) {
3738                    continue;
3739                }
3740                if (i > MAX_RECENT_BITMAPS) {
3741                    tr.freeLastThumbnail();
3742                }
3743                final Intent trIntent = tr.intent;
3744                if ((task.affinity == null || !task.affinity.equals(tr.affinity)) &&
3745                    (intent == null || !intent.filterEquals(trIntent))) {
3746                    continue;
3747                }
3748                final boolean trIsDocument = trIntent != null && trIntent.isDocument();
3749                if (document && trIsDocument) {
3750                    // These are the same document activity (not necessarily the same doc).
3751                    if (maxRecents > 0) {
3752                        --maxRecents;
3753                        continue;
3754                    }
3755                    // Hit the maximum number of documents for this task. Fall through
3756                    // and remove this document from recents.
3757                } else if (document || trIsDocument) {
3758                    // Only one of these is a document. Not the droid we're looking for.
3759                    continue;
3760                }
3761            }
3762
3763            // Either task and tr are the same or, their affinities match or their intents match
3764            // and neither of them is a document, or they are documents using the same activity
3765            // and their maxRecents has been reached.
3766            tr.disposeThumbnail();
3767            mRecentTasks.remove(i);
3768            if (task != tr) {
3769                tr.closeRecentsChain();
3770            }
3771            i--;
3772            N--;
3773            if (task.intent == null) {
3774                // If the new recent task we are adding is not fully
3775                // specified, then replace it with the existing recent task.
3776                task = tr;
3777            }
3778            notifyTaskPersisterLocked(tr, false);
3779        }
3780        if (N >= MAX_RECENT_TASKS) {
3781            final TaskRecord tr = mRecentTasks.remove(N - 1);
3782            tr.disposeThumbnail();
3783            tr.closeRecentsChain();
3784        }
3785        mRecentTasks.add(0, task);
3786    }
3787
3788    @Override
3789    public void reportActivityFullyDrawn(IBinder token) {
3790        synchronized (this) {
3791            ActivityRecord r = ActivityRecord.isInStackLocked(token);
3792            if (r == null) {
3793                return;
3794            }
3795            r.reportFullyDrawnLocked();
3796        }
3797    }
3798
3799    @Override
3800    public void setRequestedOrientation(IBinder token, int requestedOrientation) {
3801        synchronized (this) {
3802            ActivityRecord r = ActivityRecord.isInStackLocked(token);
3803            if (r == null) {
3804                return;
3805            }
3806            final long origId = Binder.clearCallingIdentity();
3807            mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
3808            Configuration config = mWindowManager.updateOrientationFromAppTokens(
3809                    mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
3810            if (config != null) {
3811                r.frozenBeforeDestroy = true;
3812                if (!updateConfigurationLocked(config, r, false, false)) {
3813                    mStackSupervisor.resumeTopActivitiesLocked();
3814                }
3815            }
3816            Binder.restoreCallingIdentity(origId);
3817        }
3818    }
3819
3820    @Override
3821    public int getRequestedOrientation(IBinder token) {
3822        synchronized (this) {
3823            ActivityRecord r = ActivityRecord.isInStackLocked(token);
3824            if (r == null) {
3825                return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
3826            }
3827            return mWindowManager.getAppOrientation(r.appToken);
3828        }
3829    }
3830
3831    /**
3832     * This is the internal entry point for handling Activity.finish().
3833     *
3834     * @param token The Binder token referencing the Activity we want to finish.
3835     * @param resultCode Result code, if any, from this Activity.
3836     * @param resultData Result data (Intent), if any, from this Activity.
3837     * @param finishTask Whether to finish the task associated with this Activity.  Only applies to
3838     *            the root Activity in the task.
3839     *
3840     * @return Returns true if the activity successfully finished, or false if it is still running.
3841     */
3842    @Override
3843    public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
3844            boolean finishTask) {
3845        // Refuse possible leaked file descriptors
3846        if (resultData != null && resultData.hasFileDescriptors() == true) {
3847            throw new IllegalArgumentException("File descriptors passed in Intent");
3848        }
3849
3850        synchronized(this) {
3851            ActivityRecord r = ActivityRecord.isInStackLocked(token);
3852            if (r == null) {
3853                return true;
3854            }
3855            // Keep track of the root activity of the task before we finish it
3856            TaskRecord tr = r.task;
3857            ActivityRecord rootR = tr.getRootActivity();
3858            // Do not allow task to finish in Lock Task mode.
3859            if (tr == mStackSupervisor.mLockTaskModeTask) {
3860                if (rootR == r) {
3861                    mStackSupervisor.showLockTaskToast();
3862                    return false;
3863                }
3864            }
3865            if (mController != null) {
3866                // Find the first activity that is not finishing.
3867                ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0);
3868                if (next != null) {
3869                    // ask watcher if this is allowed
3870                    boolean resumeOK = true;
3871                    try {
3872                        resumeOK = mController.activityResuming(next.packageName);
3873                    } catch (RemoteException e) {
3874                        mController = null;
3875                        Watchdog.getInstance().setActivityController(null);
3876                    }
3877
3878                    if (!resumeOK) {
3879                        return false;
3880                    }
3881                }
3882            }
3883            final long origId = Binder.clearCallingIdentity();
3884            try {
3885                boolean res;
3886                if (finishTask && r == rootR) {
3887                    // If requested, remove the task that is associated to this activity only if it
3888                    // was the root activity in the task.  The result code and data is ignored because
3889                    // we don't support returning them across task boundaries.
3890                    res = removeTaskByIdLocked(tr.taskId, 0);
3891                } else {
3892                    res = tr.stack.requestFinishActivityLocked(token, resultCode,
3893                            resultData, "app-request", true);
3894                }
3895                return res;
3896            } finally {
3897                Binder.restoreCallingIdentity(origId);
3898            }
3899        }
3900    }
3901
3902    @Override
3903    public final void finishHeavyWeightApp() {
3904        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3905                != PackageManager.PERMISSION_GRANTED) {
3906            String msg = "Permission Denial: finishHeavyWeightApp() from pid="
3907                    + Binder.getCallingPid()
3908                    + ", uid=" + Binder.getCallingUid()
3909                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3910            Slog.w(TAG, msg);
3911            throw new SecurityException(msg);
3912        }
3913
3914        synchronized(this) {
3915            if (mHeavyWeightProcess == null) {
3916                return;
3917            }
3918
3919            ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
3920                    mHeavyWeightProcess.activities);
3921            for (int i=0; i<activities.size(); i++) {
3922                ActivityRecord r = activities.get(i);
3923                if (!r.finishing) {
3924                    r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
3925                            null, "finish-heavy", true);
3926                }
3927            }
3928
3929            mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3930                    mHeavyWeightProcess.userId, 0));
3931            mHeavyWeightProcess = null;
3932        }
3933    }
3934
3935    @Override
3936    public void crashApplication(int uid, int initialPid, String packageName,
3937            String message) {
3938        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3939                != PackageManager.PERMISSION_GRANTED) {
3940            String msg = "Permission Denial: crashApplication() from pid="
3941                    + Binder.getCallingPid()
3942                    + ", uid=" + Binder.getCallingUid()
3943                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
3944            Slog.w(TAG, msg);
3945            throw new SecurityException(msg);
3946        }
3947
3948        synchronized(this) {
3949            ProcessRecord proc = null;
3950
3951            // Figure out which process to kill.  We don't trust that initialPid
3952            // still has any relation to current pids, so must scan through the
3953            // list.
3954            synchronized (mPidsSelfLocked) {
3955                for (int i=0; i<mPidsSelfLocked.size(); i++) {
3956                    ProcessRecord p = mPidsSelfLocked.valueAt(i);
3957                    if (p.uid != uid) {
3958                        continue;
3959                    }
3960                    if (p.pid == initialPid) {
3961                        proc = p;
3962                        break;
3963                    }
3964                    if (p.pkgList.containsKey(packageName)) {
3965                        proc = p;
3966                    }
3967                }
3968            }
3969
3970            if (proc == null) {
3971                Slog.w(TAG, "crashApplication: nothing for uid=" + uid
3972                        + " initialPid=" + initialPid
3973                        + " packageName=" + packageName);
3974                return;
3975            }
3976
3977            if (proc.thread != null) {
3978                if (proc.pid == Process.myPid()) {
3979                    Log.w(TAG, "crashApplication: trying to crash self!");
3980                    return;
3981                }
3982                long ident = Binder.clearCallingIdentity();
3983                try {
3984                    proc.thread.scheduleCrash(message);
3985                } catch (RemoteException e) {
3986                }
3987                Binder.restoreCallingIdentity(ident);
3988            }
3989        }
3990    }
3991
3992    @Override
3993    public final void finishSubActivity(IBinder token, String resultWho,
3994            int requestCode) {
3995        synchronized(this) {
3996            final long origId = Binder.clearCallingIdentity();
3997            ActivityRecord r = ActivityRecord.isInStackLocked(token);
3998            if (r != null) {
3999                r.task.stack.finishSubActivityLocked(r, resultWho, requestCode);
4000            }
4001            Binder.restoreCallingIdentity(origId);
4002        }
4003    }
4004
4005    @Override
4006    public boolean finishActivityAffinity(IBinder token) {
4007        synchronized(this) {
4008            final long origId = Binder.clearCallingIdentity();
4009            try {
4010                ActivityRecord r = ActivityRecord.isInStackLocked(token);
4011
4012                ActivityRecord rootR = r.task.getRootActivity();
4013                // Do not allow task to finish in Lock Task mode.
4014                if (r.task == mStackSupervisor.mLockTaskModeTask) {
4015                    if (rootR == r) {
4016                        mStackSupervisor.showLockTaskToast();
4017                        return false;
4018                    }
4019                }
4020                boolean res = false;
4021                if (r != null) {
4022                    res = r.task.stack.finishActivityAffinityLocked(r);
4023                }
4024                return res;
4025            } finally {
4026                Binder.restoreCallingIdentity(origId);
4027            }
4028        }
4029    }
4030
4031    @Override
4032    public void finishVoiceTask(IVoiceInteractionSession session) {
4033        synchronized(this) {
4034            final long origId = Binder.clearCallingIdentity();
4035            try {
4036                mStackSupervisor.finishVoiceTask(session);
4037            } finally {
4038                Binder.restoreCallingIdentity(origId);
4039            }
4040        }
4041
4042    }
4043
4044    @Override
4045    public boolean willActivityBeVisible(IBinder token) {
4046        synchronized(this) {
4047            ActivityStack stack = ActivityRecord.getStackLocked(token);
4048            if (stack != null) {
4049                return stack.willActivityBeVisibleLocked(token);
4050            }
4051            return false;
4052        }
4053    }
4054
4055    @Override
4056    public void overridePendingTransition(IBinder token, String packageName,
4057            int enterAnim, int exitAnim) {
4058        synchronized(this) {
4059            ActivityRecord self = ActivityRecord.isInStackLocked(token);
4060            if (self == null) {
4061                return;
4062            }
4063
4064            final long origId = Binder.clearCallingIdentity();
4065
4066            if (self.state == ActivityState.RESUMED
4067                    || self.state == ActivityState.PAUSING) {
4068                mWindowManager.overridePendingAppTransition(packageName,
4069                        enterAnim, exitAnim, null);
4070            }
4071
4072            Binder.restoreCallingIdentity(origId);
4073        }
4074    }
4075
4076    /**
4077     * Main function for removing an existing process from the activity manager
4078     * as a result of that process going away.  Clears out all connections
4079     * to the process.
4080     */
4081    private final void handleAppDiedLocked(ProcessRecord app,
4082            boolean restarting, boolean allowRestart) {
4083        int pid = app.pid;
4084        cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
4085        if (!restarting) {
4086            removeLruProcessLocked(app);
4087            if (pid > 0) {
4088                ProcessList.remove(pid);
4089            }
4090        }
4091
4092        if (mProfileProc == app) {
4093            clearProfilerLocked();
4094        }
4095
4096        // Remove this application's activities from active lists.
4097        boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app);
4098
4099        app.activities.clear();
4100
4101        if (app.instrumentationClass != null) {
4102            Slog.w(TAG, "Crash of app " + app.processName
4103                  + " running instrumentation " + app.instrumentationClass);
4104            Bundle info = new Bundle();
4105            info.putString("shortMsg", "Process crashed.");
4106            finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
4107        }
4108
4109        if (!restarting) {
4110            if (!mStackSupervisor.resumeTopActivitiesLocked()) {
4111                // If there was nothing to resume, and we are not already
4112                // restarting this process, but there is a visible activity that
4113                // is hosted by the process...  then make sure all visible
4114                // activities are running, taking care of restarting this
4115                // process.
4116                if (hasVisibleActivities) {
4117                    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
4118                }
4119            }
4120        }
4121    }
4122
4123    private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
4124        IBinder threadBinder = thread.asBinder();
4125        // Find the application record.
4126        for (int i=mLruProcesses.size()-1; i>=0; i--) {
4127            ProcessRecord rec = mLruProcesses.get(i);
4128            if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
4129                return i;
4130            }
4131        }
4132        return -1;
4133    }
4134
4135    final ProcessRecord getRecordForAppLocked(
4136            IApplicationThread thread) {
4137        if (thread == null) {
4138            return null;
4139        }
4140
4141        int appIndex = getLRURecordIndexForAppLocked(thread);
4142        return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
4143    }
4144
4145    final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) {
4146        // If there are no longer any background processes running,
4147        // and the app that died was not running instrumentation,
4148        // then tell everyone we are now low on memory.
4149        boolean haveBg = false;
4150        for (int i=mLruProcesses.size()-1; i>=0; i--) {
4151            ProcessRecord rec = mLruProcesses.get(i);
4152            if (rec.thread != null
4153                    && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
4154                haveBg = true;
4155                break;
4156            }
4157        }
4158
4159        if (!haveBg) {
4160            boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
4161            if (doReport) {
4162                long now = SystemClock.uptimeMillis();
4163                if (now < (mLastMemUsageReportTime+5*60*1000)) {
4164                    doReport = false;
4165                } else {
4166                    mLastMemUsageReportTime = now;
4167                }
4168            }
4169            final ArrayList<ProcessMemInfo> memInfos
4170                    = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null;
4171            EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
4172            long now = SystemClock.uptimeMillis();
4173            for (int i=mLruProcesses.size()-1; i>=0; i--) {
4174                ProcessRecord rec = mLruProcesses.get(i);
4175                if (rec == dyingProc || rec.thread == null) {
4176                    continue;
4177                }
4178                if (doReport) {
4179                    memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj,
4180                            rec.setProcState, rec.adjType, rec.makeAdjReason()));
4181                }
4182                if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
4183                    // The low memory report is overriding any current
4184                    // state for a GC request.  Make sure to do
4185                    // heavy/important/visible/foreground processes first.
4186                    if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
4187                        rec.lastRequestedGc = 0;
4188                    } else {
4189                        rec.lastRequestedGc = rec.lastLowMemory;
4190                    }
4191                    rec.reportLowMemory = true;
4192                    rec.lastLowMemory = now;
4193                    mProcessesToGc.remove(rec);
4194                    addProcessToGcListLocked(rec);
4195                }
4196            }
4197            if (doReport) {
4198                Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos);
4199                mHandler.sendMessage(msg);
4200            }
4201            scheduleAppGcsLocked();
4202        }
4203    }
4204
4205    final void appDiedLocked(ProcessRecord app, int pid,
4206            IApplicationThread thread) {
4207
4208        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
4209        synchronized (stats) {
4210            stats.noteProcessDiedLocked(app.info.uid, pid);
4211        }
4212
4213        Process.killProcessGroup(app.info.uid, pid);
4214
4215        // Clean up already done if the process has been re-started.
4216        if (app.pid == pid && app.thread != null &&
4217                app.thread.asBinder() == thread.asBinder()) {
4218            boolean doLowMem = app.instrumentationClass == null;
4219            boolean doOomAdj = doLowMem;
4220            if (!app.killedByAm) {
4221                Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4222                        + ") has died.");
4223                mAllowLowerMemLevel = true;
4224            } else {
4225                // Note that we always want to do oom adj to update our state with the
4226                // new number of procs.
4227                mAllowLowerMemLevel = false;
4228                doLowMem = false;
4229            }
4230            EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
4231            if (DEBUG_CLEANUP) Slog.v(
4232                TAG, "Dying app: " + app + ", pid: " + pid
4233                + ", thread: " + thread.asBinder());
4234            handleAppDiedLocked(app, false, true);
4235
4236            if (doOomAdj) {
4237                updateOomAdjLocked();
4238            }
4239            if (doLowMem) {
4240                doLowMemReportIfNeededLocked(app);
4241            }
4242        } else if (app.pid != pid) {
4243            // A new process has already been started.
4244            Slog.i(TAG, "Process " + app.processName + " (pid " + pid
4245                    + ") has died and restarted (pid " + app.pid + ").");
4246            EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
4247        } else if (DEBUG_PROCESSES) {
4248            Slog.d(TAG, "Received spurious death notification for thread "
4249                    + thread.asBinder());
4250        }
4251    }
4252
4253    /**
4254     * If a stack trace dump file is configured, dump process stack traces.
4255     * @param clearTraces causes the dump file to be erased prior to the new
4256     *    traces being written, if true; when false, the new traces will be
4257     *    appended to any existing file content.
4258     * @param firstPids of dalvik VM processes to dump stack traces for first
4259     * @param lastPids of dalvik VM processes to dump stack traces for last
4260     * @param nativeProcs optional list of native process names to dump stack crawls
4261     * @return file containing stack traces, or null if no dump file is configured
4262     */
4263    public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
4264            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
4265        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4266        if (tracesPath == null || tracesPath.length() == 0) {
4267            return null;
4268        }
4269
4270        File tracesFile = new File(tracesPath);
4271        try {
4272            File tracesDir = tracesFile.getParentFile();
4273            if (!tracesDir.exists()) {
4274                tracesFile.mkdirs();
4275                if (!SELinux.restorecon(tracesDir)) {
4276                    return null;
4277                }
4278            }
4279            FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
4280
4281            if (clearTraces && tracesFile.exists()) tracesFile.delete();
4282            tracesFile.createNewFile();
4283            FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4284        } catch (IOException e) {
4285            Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
4286            return null;
4287        }
4288
4289        dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs);
4290        return tracesFile;
4291    }
4292
4293    private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
4294            ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) {
4295        // Use a FileObserver to detect when traces finish writing.
4296        // The order of traces is considered important to maintain for legibility.
4297        FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
4298            @Override
4299            public synchronized void onEvent(int event, String path) { notify(); }
4300        };
4301
4302        try {
4303            observer.startWatching();
4304
4305            // First collect all of the stacks of the most important pids.
4306            if (firstPids != null) {
4307                try {
4308                    int num = firstPids.size();
4309                    for (int i = 0; i < num; i++) {
4310                        synchronized (observer) {
4311                            Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
4312                            observer.wait(200);  // Wait for write-close, give up after 200msec
4313                        }
4314                    }
4315                } catch (InterruptedException e) {
4316                    Log.wtf(TAG, e);
4317                }
4318            }
4319
4320            // Next collect the stacks of the native pids
4321            if (nativeProcs != null) {
4322                int[] pids = Process.getPidsForCommands(nativeProcs);
4323                if (pids != null) {
4324                    for (int pid : pids) {
4325                        Debug.dumpNativeBacktraceToFile(pid, tracesPath);
4326                    }
4327                }
4328            }
4329
4330            // Lastly, measure CPU usage.
4331            if (processCpuTracker != null) {
4332                processCpuTracker.init();
4333                System.gc();
4334                processCpuTracker.update();
4335                try {
4336                    synchronized (processCpuTracker) {
4337                        processCpuTracker.wait(500); // measure over 1/2 second.
4338                    }
4339                } catch (InterruptedException e) {
4340                }
4341                processCpuTracker.update();
4342
4343                // We'll take the stack crawls of just the top apps using CPU.
4344                final int N = processCpuTracker.countWorkingStats();
4345                int numProcs = 0;
4346                for (int i=0; i<N && numProcs<5; i++) {
4347                    ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i);
4348                    if (lastPids.indexOfKey(stats.pid) >= 0) {
4349                        numProcs++;
4350                        try {
4351                            synchronized (observer) {
4352                                Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
4353                                observer.wait(200);  // Wait for write-close, give up after 200msec
4354                            }
4355                        } catch (InterruptedException e) {
4356                            Log.wtf(TAG, e);
4357                        }
4358
4359                    }
4360                }
4361            }
4362        } finally {
4363            observer.stopWatching();
4364        }
4365    }
4366
4367    final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
4368        if (true || IS_USER_BUILD) {
4369            return;
4370        }
4371        String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
4372        if (tracesPath == null || tracesPath.length() == 0) {
4373            return;
4374        }
4375
4376        StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
4377        StrictMode.allowThreadDiskWrites();
4378        try {
4379            final File tracesFile = new File(tracesPath);
4380            final File tracesDir = tracesFile.getParentFile();
4381            final File tracesTmp = new File(tracesDir, "__tmp__");
4382            try {
4383                if (!tracesDir.exists()) {
4384                    tracesFile.mkdirs();
4385                    if (!SELinux.restorecon(tracesDir.getPath())) {
4386                        return;
4387                    }
4388                }
4389                FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1);  // drwxrwxr-x
4390
4391                if (tracesFile.exists()) {
4392                    tracesTmp.delete();
4393                    tracesFile.renameTo(tracesTmp);
4394                }
4395                StringBuilder sb = new StringBuilder();
4396                Time tobj = new Time();
4397                tobj.set(System.currentTimeMillis());
4398                sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
4399                sb.append(": ");
4400                TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
4401                sb.append(" since ");
4402                sb.append(msg);
4403                FileOutputStream fos = new FileOutputStream(tracesFile);
4404                fos.write(sb.toString().getBytes());
4405                if (app == null) {
4406                    fos.write("\n*** No application process!".getBytes());
4407                }
4408                fos.close();
4409                FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
4410            } catch (IOException e) {
4411                Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
4412                return;
4413            }
4414
4415            if (app != null) {
4416                ArrayList<Integer> firstPids = new ArrayList<Integer>();
4417                firstPids.add(app.pid);
4418                dumpStackTraces(tracesPath, firstPids, null, null, null);
4419            }
4420
4421            File lastTracesFile = null;
4422            File curTracesFile = null;
4423            for (int i=9; i>=0; i--) {
4424                String name = String.format(Locale.US, "slow%02d.txt", i);
4425                curTracesFile = new File(tracesDir, name);
4426                if (curTracesFile.exists()) {
4427                    if (lastTracesFile != null) {
4428                        curTracesFile.renameTo(lastTracesFile);
4429                    } else {
4430                        curTracesFile.delete();
4431                    }
4432                }
4433                lastTracesFile = curTracesFile;
4434            }
4435            tracesFile.renameTo(curTracesFile);
4436            if (tracesTmp.exists()) {
4437                tracesTmp.renameTo(tracesFile);
4438            }
4439        } finally {
4440            StrictMode.setThreadPolicy(oldPolicy);
4441        }
4442    }
4443
4444    final void appNotResponding(ProcessRecord app, ActivityRecord activity,
4445            ActivityRecord parent, boolean aboveSystem, final String annotation) {
4446        ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
4447        SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
4448
4449        if (mController != null) {
4450            try {
4451                // 0 == continue, -1 = kill process immediately
4452                int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
4453                if (res < 0 && app.pid != MY_PID) {
4454                    Process.killProcess(app.pid);
4455                    Process.killProcessGroup(app.info.uid, app.pid);
4456                }
4457            } catch (RemoteException e) {
4458                mController = null;
4459                Watchdog.getInstance().setActivityController(null);
4460            }
4461        }
4462
4463        long anrTime = SystemClock.uptimeMillis();
4464        if (MONITOR_CPU_USAGE) {
4465            updateCpuStatsNow();
4466        }
4467
4468        synchronized (this) {
4469            // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
4470            if (mShuttingDown) {
4471                Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
4472                return;
4473            } else if (app.notResponding) {
4474                Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
4475                return;
4476            } else if (app.crashing) {
4477                Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
4478                return;
4479            }
4480
4481            // In case we come through here for the same app before completing
4482            // this one, mark as anring now so we will bail out.
4483            app.notResponding = true;
4484
4485            // Log the ANR to the event log.
4486            EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
4487                    app.processName, app.info.flags, annotation);
4488
4489            // Dump thread traces as quickly as we can, starting with "interesting" processes.
4490            firstPids.add(app.pid);
4491
4492            int parentPid = app.pid;
4493            if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
4494            if (parentPid != app.pid) firstPids.add(parentPid);
4495
4496            if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
4497
4498            for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
4499                ProcessRecord r = mLruProcesses.get(i);
4500                if (r != null && r.thread != null) {
4501                    int pid = r.pid;
4502                    if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
4503                        if (r.persistent) {
4504                            firstPids.add(pid);
4505                        } else {
4506                            lastPids.put(pid, Boolean.TRUE);
4507                        }
4508                    }
4509                }
4510            }
4511        }
4512
4513        // Log the ANR to the main log.
4514        StringBuilder info = new StringBuilder();
4515        info.setLength(0);
4516        info.append("ANR in ").append(app.processName);
4517        if (activity != null && activity.shortComponentName != null) {
4518            info.append(" (").append(activity.shortComponentName).append(")");
4519        }
4520        info.append("\n");
4521        info.append("PID: ").append(app.pid).append("\n");
4522        if (annotation != null) {
4523            info.append("Reason: ").append(annotation).append("\n");
4524        }
4525        if (parent != null && parent != activity) {
4526            info.append("Parent: ").append(parent.shortComponentName).append("\n");
4527        }
4528
4529        final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
4530
4531        File tracesFile = dumpStackTraces(true, firstPids, processCpuTracker, lastPids,
4532                NATIVE_STACKS_OF_INTEREST);
4533
4534        String cpuInfo = null;
4535        if (MONITOR_CPU_USAGE) {
4536            updateCpuStatsNow();
4537            synchronized (mProcessCpuThread) {
4538                cpuInfo = mProcessCpuTracker.printCurrentState(anrTime);
4539            }
4540            info.append(processCpuTracker.printCurrentLoad());
4541            info.append(cpuInfo);
4542        }
4543
4544        info.append(processCpuTracker.printCurrentState(anrTime));
4545
4546        Slog.e(TAG, info.toString());
4547        if (tracesFile == null) {
4548            // There is no trace file, so dump (only) the alleged culprit's threads to the log
4549            Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
4550        }
4551
4552        addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
4553                cpuInfo, tracesFile, null);
4554
4555        if (mController != null) {
4556            try {
4557                // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
4558                int res = mController.appNotResponding(app.processName, app.pid, info.toString());
4559                if (res != 0) {
4560                    if (res < 0 && app.pid != MY_PID) {
4561                        Process.killProcess(app.pid);
4562                        Process.killProcessGroup(app.info.uid, app.pid);
4563                    } else {
4564                        synchronized (this) {
4565                            mServices.scheduleServiceTimeoutLocked(app);
4566                        }
4567                    }
4568                    return;
4569                }
4570            } catch (RemoteException e) {
4571                mController = null;
4572                Watchdog.getInstance().setActivityController(null);
4573            }
4574        }
4575
4576        // Unless configured otherwise, swallow ANRs in background processes & kill the process.
4577        boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
4578                Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
4579
4580        synchronized (this) {
4581            if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
4582                killUnneededProcessLocked(app, "background ANR");
4583                return;
4584            }
4585
4586            // Set the app's notResponding state, and look up the errorReportReceiver
4587            makeAppNotRespondingLocked(app,
4588                    activity != null ? activity.shortComponentName : null,
4589                    annotation != null ? "ANR " + annotation : "ANR",
4590                    info.toString());
4591
4592            // Bring up the infamous App Not Responding dialog
4593            Message msg = Message.obtain();
4594            HashMap<String, Object> map = new HashMap<String, Object>();
4595            msg.what = SHOW_NOT_RESPONDING_MSG;
4596            msg.obj = map;
4597            msg.arg1 = aboveSystem ? 1 : 0;
4598            map.put("app", app);
4599            if (activity != null) {
4600                map.put("activity", activity);
4601            }
4602
4603            mHandler.sendMessage(msg);
4604        }
4605    }
4606
4607    final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
4608        if (!mLaunchWarningShown) {
4609            mLaunchWarningShown = true;
4610            mHandler.post(new Runnable() {
4611                @Override
4612                public void run() {
4613                    synchronized (ActivityManagerService.this) {
4614                        final Dialog d = new LaunchWarningWindow(mContext, cur, next);
4615                        d.show();
4616                        mHandler.postDelayed(new Runnable() {
4617                            @Override
4618                            public void run() {
4619                                synchronized (ActivityManagerService.this) {
4620                                    d.dismiss();
4621                                    mLaunchWarningShown = false;
4622                                }
4623                            }
4624                        }, 4000);
4625                    }
4626                }
4627            });
4628        }
4629    }
4630
4631    @Override
4632    public boolean clearApplicationUserData(final String packageName,
4633            final IPackageDataObserver observer, int userId) {
4634        enforceNotIsolatedCaller("clearApplicationUserData");
4635        int uid = Binder.getCallingUid();
4636        int pid = Binder.getCallingPid();
4637        userId = handleIncomingUser(pid, uid,
4638                userId, false, ALLOW_FULL_ONLY, "clearApplicationUserData", null);
4639        long callingId = Binder.clearCallingIdentity();
4640        try {
4641            IPackageManager pm = AppGlobals.getPackageManager();
4642            int pkgUid = -1;
4643            synchronized(this) {
4644                try {
4645                    pkgUid = pm.getPackageUid(packageName, userId);
4646                } catch (RemoteException e) {
4647                }
4648                if (pkgUid == -1) {
4649                    Slog.w(TAG, "Invalid packageName: " + packageName);
4650                    if (observer != null) {
4651                        try {
4652                            observer.onRemoveCompleted(packageName, false);
4653                        } catch (RemoteException e) {
4654                            Slog.i(TAG, "Observer no longer exists.");
4655                        }
4656                    }
4657                    return false;
4658                }
4659                if (uid == pkgUid || checkComponentPermission(
4660                        android.Manifest.permission.CLEAR_APP_USER_DATA,
4661                        pid, uid, -1, true)
4662                        == PackageManager.PERMISSION_GRANTED) {
4663                    forceStopPackageLocked(packageName, pkgUid, "clear data");
4664                } else {
4665                    throw new SecurityException("PID " + pid + " does not have permission "
4666                            + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data"
4667                                    + " of package " + packageName);
4668                }
4669            }
4670
4671            try {
4672                // Clear application user data
4673                pm.clearApplicationUserData(packageName, observer, userId);
4674
4675                // Remove all permissions granted from/to this package
4676                removeUriPermissionsForPackageLocked(packageName, userId, true);
4677
4678                Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
4679                        Uri.fromParts("package", packageName, null));
4680                intent.putExtra(Intent.EXTRA_UID, pkgUid);
4681                broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
4682                        null, null, 0, null, null, null, false, false, userId);
4683            } catch (RemoteException e) {
4684            }
4685        } finally {
4686            Binder.restoreCallingIdentity(callingId);
4687        }
4688        return true;
4689    }
4690
4691    @Override
4692    public void killBackgroundProcesses(final String packageName, int userId) {
4693        if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4694                != PackageManager.PERMISSION_GRANTED &&
4695                checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
4696                        != PackageManager.PERMISSION_GRANTED) {
4697            String msg = "Permission Denial: killBackgroundProcesses() from pid="
4698                    + Binder.getCallingPid()
4699                    + ", uid=" + Binder.getCallingUid()
4700                    + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4701            Slog.w(TAG, msg);
4702            throw new SecurityException(msg);
4703        }
4704
4705        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4706                userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null);
4707        long callingId = Binder.clearCallingIdentity();
4708        try {
4709            IPackageManager pm = AppGlobals.getPackageManager();
4710            synchronized(this) {
4711                int appId = -1;
4712                try {
4713                    appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
4714                } catch (RemoteException e) {
4715                }
4716                if (appId == -1) {
4717                    Slog.w(TAG, "Invalid packageName: " + packageName);
4718                    return;
4719                }
4720                killPackageProcessesLocked(packageName, appId, userId,
4721                        ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
4722            }
4723        } finally {
4724            Binder.restoreCallingIdentity(callingId);
4725        }
4726    }
4727
4728    @Override
4729    public void killAllBackgroundProcesses() {
4730        if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
4731                != PackageManager.PERMISSION_GRANTED) {
4732            String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
4733                    + Binder.getCallingPid()
4734                    + ", uid=" + Binder.getCallingUid()
4735                    + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
4736            Slog.w(TAG, msg);
4737            throw new SecurityException(msg);
4738        }
4739
4740        long callingId = Binder.clearCallingIdentity();
4741        try {
4742            synchronized(this) {
4743                ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
4744                final int NP = mProcessNames.getMap().size();
4745                for (int ip=0; ip<NP; ip++) {
4746                    SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
4747                    final int NA = apps.size();
4748                    for (int ia=0; ia<NA; ia++) {
4749                        ProcessRecord app = apps.valueAt(ia);
4750                        if (app.persistent) {
4751                            // we don't kill persistent processes
4752                            continue;
4753                        }
4754                        if (app.removed) {
4755                            procs.add(app);
4756                        } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
4757                            app.removed = true;
4758                            procs.add(app);
4759                        }
4760                    }
4761                }
4762
4763                int N = procs.size();
4764                for (int i=0; i<N; i++) {
4765                    removeProcessLocked(procs.get(i), false, true, "kill all background");
4766                }
4767                mAllowLowerMemLevel = true;
4768                updateOomAdjLocked();
4769                doLowMemReportIfNeededLocked(null);
4770            }
4771        } finally {
4772            Binder.restoreCallingIdentity(callingId);
4773        }
4774    }
4775
4776    @Override
4777    public void forceStopPackage(final String packageName, int userId) {
4778        if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
4779                != PackageManager.PERMISSION_GRANTED) {
4780            String msg = "Permission Denial: forceStopPackage() from pid="
4781                    + Binder.getCallingPid()
4782                    + ", uid=" + Binder.getCallingUid()
4783                    + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
4784            Slog.w(TAG, msg);
4785            throw new SecurityException(msg);
4786        }
4787        final int callingPid = Binder.getCallingPid();
4788        userId = handleIncomingUser(callingPid, Binder.getCallingUid(),
4789                userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null);
4790        long callingId = Binder.clearCallingIdentity();
4791        try {
4792            IPackageManager pm = AppGlobals.getPackageManager();
4793            synchronized(this) {
4794                int[] users = userId == UserHandle.USER_ALL
4795                        ? getUsersLocked() : new int[] { userId };
4796                for (int user : users) {
4797                    int pkgUid = -1;
4798                    try {
4799                        pkgUid = pm.getPackageUid(packageName, user);
4800                    } catch (RemoteException e) {
4801                    }
4802                    if (pkgUid == -1) {
4803                        Slog.w(TAG, "Invalid packageName: " + packageName);
4804                        continue;
4805                    }
4806                    try {
4807                        pm.setPackageStoppedState(packageName, true, user);
4808                    } catch (RemoteException e) {
4809                    } catch (IllegalArgumentException e) {
4810                        Slog.w(TAG, "Failed trying to unstop package "
4811                                + packageName + ": " + e);
4812                    }
4813                    if (isUserRunningLocked(user, false)) {
4814                        forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid);
4815                    }
4816                }
4817            }
4818        } finally {
4819            Binder.restoreCallingIdentity(callingId);
4820        }
4821    }
4822
4823    @Override
4824    public void addPackageDependency(String packageName) {
4825        synchronized (this) {
4826            int callingPid = Binder.getCallingPid();
4827            if (callingPid == Process.myPid()) {
4828                //  Yeah, um, no.
4829                Slog.w(TAG, "Can't addPackageDependency on system process");
4830                return;
4831            }
4832            ProcessRecord proc;
4833            synchronized (mPidsSelfLocked) {
4834                proc = mPidsSelfLocked.get(Binder.getCallingPid());
4835            }
4836            if (proc != null) {
4837                if (proc.pkgDeps == null) {
4838                    proc.pkgDeps = new ArraySet<String>(1);
4839                }
4840                proc.pkgDeps.add(packageName);
4841            }
4842        }
4843    }
4844
4845    /*
4846     * The pkg name and app id have to be specified.
4847     */
4848    @Override
4849    public void killApplicationWithAppId(String pkg, int appid, String reason) {
4850        if (pkg == null) {
4851            return;
4852        }
4853        // Make sure the uid is valid.
4854        if (appid < 0) {
4855            Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
4856            return;
4857        }
4858        int callerUid = Binder.getCallingUid();
4859        // Only the system server can kill an application
4860        if (callerUid == Process.SYSTEM_UID) {
4861            // Post an aysnc message to kill the application
4862            Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
4863            msg.arg1 = appid;
4864            msg.arg2 = 0;
4865            Bundle bundle = new Bundle();
4866            bundle.putString("pkg", pkg);
4867            bundle.putString("reason", reason);
4868            msg.obj = bundle;
4869            mHandler.sendMessage(msg);
4870        } else {
4871            throw new SecurityException(callerUid + " cannot kill pkg: " +
4872                    pkg);
4873        }
4874    }
4875
4876    @Override
4877    public void closeSystemDialogs(String reason) {
4878        enforceNotIsolatedCaller("closeSystemDialogs");
4879
4880        final int pid = Binder.getCallingPid();
4881        final int uid = Binder.getCallingUid();
4882        final long origId = Binder.clearCallingIdentity();
4883        try {
4884            synchronized (this) {
4885                // Only allow this from foreground processes, so that background
4886                // applications can't abuse it to prevent system UI from being shown.
4887                if (uid >= Process.FIRST_APPLICATION_UID) {
4888                    ProcessRecord proc;
4889                    synchronized (mPidsSelfLocked) {
4890                        proc = mPidsSelfLocked.get(pid);
4891                    }
4892                    if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
4893                        Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
4894                                + " from background process " + proc);
4895                        return;
4896                    }
4897                }
4898                closeSystemDialogsLocked(reason);
4899            }
4900        } finally {
4901            Binder.restoreCallingIdentity(origId);
4902        }
4903    }
4904
4905    void closeSystemDialogsLocked(String reason) {
4906        Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
4907        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
4908                | Intent.FLAG_RECEIVER_FOREGROUND);
4909        if (reason != null) {
4910            intent.putExtra("reason", reason);
4911        }
4912        mWindowManager.closeSystemDialogs(reason);
4913
4914        mStackSupervisor.closeSystemDialogsLocked();
4915
4916        broadcastIntentLocked(null, null, intent, null,
4917                null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
4918                Process.SYSTEM_UID, UserHandle.USER_ALL);
4919    }
4920
4921    @Override
4922    public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) {
4923        enforceNotIsolatedCaller("getProcessMemoryInfo");
4924        Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
4925        for (int i=pids.length-1; i>=0; i--) {
4926            ProcessRecord proc;
4927            int oomAdj;
4928            synchronized (this) {
4929                synchronized (mPidsSelfLocked) {
4930                    proc = mPidsSelfLocked.get(pids[i]);
4931                    oomAdj = proc != null ? proc.setAdj : 0;
4932                }
4933            }
4934            infos[i] = new Debug.MemoryInfo();
4935            Debug.getMemoryInfo(pids[i], infos[i]);
4936            if (proc != null) {
4937                synchronized (this) {
4938                    if (proc.thread != null && proc.setAdj == oomAdj) {
4939                        // Record this for posterity if the process has been stable.
4940                        proc.baseProcessTracker.addPss(infos[i].getTotalPss(),
4941                                infos[i].getTotalUss(), false, proc.pkgList);
4942                    }
4943                }
4944            }
4945        }
4946        return infos;
4947    }
4948
4949    @Override
4950    public long[] getProcessPss(int[] pids) {
4951        enforceNotIsolatedCaller("getProcessPss");
4952        long[] pss = new long[pids.length];
4953        for (int i=pids.length-1; i>=0; i--) {
4954            ProcessRecord proc;
4955            int oomAdj;
4956            synchronized (this) {
4957                synchronized (mPidsSelfLocked) {
4958                    proc = mPidsSelfLocked.get(pids[i]);
4959                    oomAdj = proc != null ? proc.setAdj : 0;
4960                }
4961            }
4962            long[] tmpUss = new long[1];
4963            pss[i] = Debug.getPss(pids[i], tmpUss);
4964            if (proc != null) {
4965                synchronized (this) {
4966                    if (proc.thread != null && proc.setAdj == oomAdj) {
4967                        // Record this for posterity if the process has been stable.
4968                        proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList);
4969                    }
4970                }
4971            }
4972        }
4973        return pss;
4974    }
4975
4976    @Override
4977    public void killApplicationProcess(String processName, int uid) {
4978        if (processName == null) {
4979            return;
4980        }
4981
4982        int callerUid = Binder.getCallingUid();
4983        // Only the system server can kill an application
4984        if (callerUid == Process.SYSTEM_UID) {
4985            synchronized (this) {
4986                ProcessRecord app = getProcessRecordLocked(processName, uid, true);
4987                if (app != null && app.thread != null) {
4988                    try {
4989                        app.thread.scheduleSuicide();
4990                    } catch (RemoteException e) {
4991                        // If the other end already died, then our work here is done.
4992                    }
4993                } else {
4994                    Slog.w(TAG, "Process/uid not found attempting kill of "
4995                            + processName + " / " + uid);
4996                }
4997            }
4998        } else {
4999            throw new SecurityException(callerUid + " cannot kill app process: " +
5000                    processName);
5001        }
5002    }
5003
5004    private void forceStopPackageLocked(final String packageName, int uid, String reason) {
5005        forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
5006                false, true, false, false, UserHandle.getUserId(uid), reason);
5007        Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
5008                Uri.fromParts("package", packageName, null));
5009        if (!mProcessesReady) {
5010            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
5011                    | Intent.FLAG_RECEIVER_FOREGROUND);
5012        }
5013        intent.putExtra(Intent.EXTRA_UID, uid);
5014        intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
5015        broadcastIntentLocked(null, null, intent,
5016                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
5017                false, false,
5018                MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
5019    }
5020
5021    private void forceStopUserLocked(int userId, String reason) {
5022        forceStopPackageLocked(null, -1, false, false, true, false, false, userId, reason);
5023        Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
5024        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
5025                | Intent.FLAG_RECEIVER_FOREGROUND);
5026        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
5027        broadcastIntentLocked(null, null, intent,
5028                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
5029                false, false,
5030                MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
5031    }
5032
5033    private final boolean killPackageProcessesLocked(String packageName, int appId,
5034            int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
5035            boolean doit, boolean evenPersistent, String reason) {
5036        ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5037
5038        // Remove all processes this package may have touched: all with the
5039        // same UID (except for the system or root user), and all whose name
5040        // matches the package name.
5041        final int NP = mProcessNames.getMap().size();
5042        for (int ip=0; ip<NP; ip++) {
5043            SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
5044            final int NA = apps.size();
5045            for (int ia=0; ia<NA; ia++) {
5046                ProcessRecord app = apps.valueAt(ia);
5047                if (app.persistent && !evenPersistent) {
5048                    // we don't kill persistent processes
5049                    continue;
5050                }
5051                if (app.removed) {
5052                    if (doit) {
5053                        procs.add(app);
5054                    }
5055                    continue;
5056                }
5057
5058                // Skip process if it doesn't meet our oom adj requirement.
5059                if (app.setAdj < minOomAdj) {
5060                    continue;
5061                }
5062
5063                // If no package is specified, we call all processes under the
5064                // give user id.
5065                if (packageName == null) {
5066                    if (app.userId != userId) {
5067                        continue;
5068                    }
5069                    if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) {
5070                        continue;
5071                    }
5072                // Package has been specified, we want to hit all processes
5073                // that match it.  We need to qualify this by the processes
5074                // that are running under the specified app and user ID.
5075                } else {
5076                    final boolean isDep = app.pkgDeps != null
5077                            && app.pkgDeps.contains(packageName);
5078                    if (!isDep && UserHandle.getAppId(app.uid) != appId) {
5079                        continue;
5080                    }
5081                    if (userId != UserHandle.USER_ALL && app.userId != userId) {
5082                        continue;
5083                    }
5084                    if (!app.pkgList.containsKey(packageName) && !isDep) {
5085                        continue;
5086                    }
5087                }
5088
5089                // Process has passed all conditions, kill it!
5090                if (!doit) {
5091                    return true;
5092                }
5093                app.removed = true;
5094                procs.add(app);
5095            }
5096        }
5097
5098        int N = procs.size();
5099        for (int i=0; i<N; i++) {
5100            removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
5101        }
5102        updateOomAdjLocked();
5103        return N > 0;
5104    }
5105
5106    private final boolean forceStopPackageLocked(String name, int appId,
5107            boolean callerWillRestart, boolean purgeCache, boolean doit,
5108            boolean evenPersistent, boolean uninstalling, int userId, String reason) {
5109        int i;
5110        int N;
5111
5112        if (userId == UserHandle.USER_ALL && name == null) {
5113            Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
5114        }
5115
5116        if (appId < 0 && name != null) {
5117            try {
5118                appId = UserHandle.getAppId(
5119                        AppGlobals.getPackageManager().getPackageUid(name, 0));
5120            } catch (RemoteException e) {
5121            }
5122        }
5123
5124        if (doit) {
5125            if (name != null) {
5126                Slog.i(TAG, "Force stopping " + name + " appid=" + appId
5127                        + " user=" + userId + ": " + reason);
5128            } else {
5129                Slog.i(TAG, "Force stopping u" + userId + ": " + reason);
5130            }
5131
5132            final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
5133            for (int ip=pmap.size()-1; ip>=0; ip--) {
5134                SparseArray<Long> ba = pmap.valueAt(ip);
5135                for (i=ba.size()-1; i>=0; i--) {
5136                    boolean remove = false;
5137                    final int entUid = ba.keyAt(i);
5138                    if (name != null) {
5139                        if (userId == UserHandle.USER_ALL) {
5140                            if (UserHandle.getAppId(entUid) == appId) {
5141                                remove = true;
5142                            }
5143                        } else {
5144                            if (entUid == UserHandle.getUid(userId, appId)) {
5145                                remove = true;
5146                            }
5147                        }
5148                    } else if (UserHandle.getUserId(entUid) == userId) {
5149                        remove = true;
5150                    }
5151                    if (remove) {
5152                        ba.removeAt(i);
5153                    }
5154                }
5155                if (ba.size() == 0) {
5156                    pmap.removeAt(ip);
5157                }
5158            }
5159        }
5160
5161        boolean didSomething = killPackageProcessesLocked(name, appId, userId,
5162                -100, callerWillRestart, true, doit, evenPersistent,
5163                name == null ? ("stop user " + userId) : ("stop " + name));
5164
5165        if (mStackSupervisor.forceStopPackageLocked(name, doit, evenPersistent, userId)) {
5166            if (!doit) {
5167                return true;
5168            }
5169            didSomething = true;
5170        }
5171
5172        if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
5173            if (!doit) {
5174                return true;
5175            }
5176            didSomething = true;
5177        }
5178
5179        if (name == null) {
5180            // Remove all sticky broadcasts from this user.
5181            mStickyBroadcasts.remove(userId);
5182        }
5183
5184        ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
5185        if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
5186                userId, providers)) {
5187            if (!doit) {
5188                return true;
5189            }
5190            didSomething = true;
5191        }
5192        N = providers.size();
5193        for (i=0; i<N; i++) {
5194            removeDyingProviderLocked(null, providers.get(i), true);
5195        }
5196
5197        // Remove transient permissions granted from/to this package/user
5198        removeUriPermissionsForPackageLocked(name, userId, false);
5199
5200        if (name == null || uninstalling) {
5201            // Remove pending intents.  For now we only do this when force
5202            // stopping users, because we have some problems when doing this
5203            // for packages -- app widgets are not currently cleaned up for
5204            // such packages, so they can be left with bad pending intents.
5205            if (mIntentSenderRecords.size() > 0) {
5206                Iterator<WeakReference<PendingIntentRecord>> it
5207                        = mIntentSenderRecords.values().iterator();
5208                while (it.hasNext()) {
5209                    WeakReference<PendingIntentRecord> wpir = it.next();
5210                    if (wpir == null) {
5211                        it.remove();
5212                        continue;
5213                    }
5214                    PendingIntentRecord pir = wpir.get();
5215                    if (pir == null) {
5216                        it.remove();
5217                        continue;
5218                    }
5219                    if (name == null) {
5220                        // Stopping user, remove all objects for the user.
5221                        if (pir.key.userId != userId) {
5222                            // Not the same user, skip it.
5223                            continue;
5224                        }
5225                    } else {
5226                        if (UserHandle.getAppId(pir.uid) != appId) {
5227                            // Different app id, skip it.
5228                            continue;
5229                        }
5230                        if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
5231                            // Different user, skip it.
5232                            continue;
5233                        }
5234                        if (!pir.key.packageName.equals(name)) {
5235                            // Different package, skip it.
5236                            continue;
5237                        }
5238                    }
5239                    if (!doit) {
5240                        return true;
5241                    }
5242                    didSomething = true;
5243                    it.remove();
5244                    pir.canceled = true;
5245                    if (pir.key.activity != null) {
5246                        pir.key.activity.pendingResults.remove(pir.ref);
5247                    }
5248                }
5249            }
5250        }
5251
5252        if (doit) {
5253            if (purgeCache && name != null) {
5254                AttributeCache ac = AttributeCache.instance();
5255                if (ac != null) {
5256                    ac.removePackage(name);
5257                }
5258            }
5259            if (mBooted) {
5260                mStackSupervisor.resumeTopActivitiesLocked();
5261                mStackSupervisor.scheduleIdleLocked();
5262            }
5263        }
5264
5265        return didSomething;
5266    }
5267
5268    private final boolean removeProcessLocked(ProcessRecord app,
5269            boolean callerWillRestart, boolean allowRestart, String reason) {
5270        final String name = app.processName;
5271        final int uid = app.uid;
5272        if (DEBUG_PROCESSES) Slog.d(
5273            TAG, "Force removing proc " + app.toShortString() + " (" + name
5274            + "/" + uid + ")");
5275
5276        mProcessNames.remove(name, uid);
5277        mIsolatedProcesses.remove(app.uid);
5278        if (mHeavyWeightProcess == app) {
5279            mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
5280                    mHeavyWeightProcess.userId, 0));
5281            mHeavyWeightProcess = null;
5282        }
5283        boolean needRestart = false;
5284        if (app.pid > 0 && app.pid != MY_PID) {
5285            int pid = app.pid;
5286            synchronized (mPidsSelfLocked) {
5287                mPidsSelfLocked.remove(pid);
5288                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5289            }
5290            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
5291            if (app.isolated) {
5292                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
5293            }
5294            killUnneededProcessLocked(app, reason);
5295            Process.killProcessGroup(app.info.uid, app.pid);
5296            handleAppDiedLocked(app, true, allowRestart);
5297            removeLruProcessLocked(app);
5298
5299            if (app.persistent && !app.isolated) {
5300                if (!callerWillRestart) {
5301                    addAppLocked(app.info, false, null /* ABI override */);
5302                } else {
5303                    needRestart = true;
5304                }
5305            }
5306        } else {
5307            mRemovedProcesses.add(app);
5308        }
5309
5310        return needRestart;
5311    }
5312
5313    private final void processStartTimedOutLocked(ProcessRecord app) {
5314        final int pid = app.pid;
5315        boolean gone = false;
5316        synchronized (mPidsSelfLocked) {
5317            ProcessRecord knownApp = mPidsSelfLocked.get(pid);
5318            if (knownApp != null && knownApp.thread == null) {
5319                mPidsSelfLocked.remove(pid);
5320                gone = true;
5321            }
5322        }
5323
5324        if (gone) {
5325            Slog.w(TAG, "Process " + app + " failed to attach");
5326            EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
5327                    pid, app.uid, app.processName);
5328            mProcessNames.remove(app.processName, app.uid);
5329            mIsolatedProcesses.remove(app.uid);
5330            if (mHeavyWeightProcess == app) {
5331                mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
5332                        mHeavyWeightProcess.userId, 0));
5333                mHeavyWeightProcess = null;
5334            }
5335            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
5336            if (app.isolated) {
5337                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
5338            }
5339            // Take care of any launching providers waiting for this process.
5340            checkAppInLaunchingProvidersLocked(app, true);
5341            // Take care of any services that are waiting for the process.
5342            mServices.processStartTimedOutLocked(app);
5343            killUnneededProcessLocked(app, "start timeout");
5344            if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
5345                Slog.w(TAG, "Unattached app died before backup, skipping");
5346                try {
5347                    IBackupManager bm = IBackupManager.Stub.asInterface(
5348                            ServiceManager.getService(Context.BACKUP_SERVICE));
5349                    bm.agentDisconnected(app.info.packageName);
5350                } catch (RemoteException e) {
5351                    // Can't happen; the backup manager is local
5352                }
5353            }
5354            if (isPendingBroadcastProcessLocked(pid)) {
5355                Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
5356                skipPendingBroadcastLocked(pid);
5357            }
5358        } else {
5359            Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
5360        }
5361    }
5362
5363    private final boolean attachApplicationLocked(IApplicationThread thread,
5364            int pid) {
5365
5366        // Find the application record that is being attached...  either via
5367        // the pid if we are running in multiple processes, or just pull the
5368        // next app record if we are emulating process with anonymous threads.
5369        ProcessRecord app;
5370        if (pid != MY_PID && pid >= 0) {
5371            synchronized (mPidsSelfLocked) {
5372                app = mPidsSelfLocked.get(pid);
5373            }
5374        } else {
5375            app = null;
5376        }
5377
5378        if (app == null) {
5379            Slog.w(TAG, "No pending application record for pid " + pid
5380                    + " (IApplicationThread " + thread + "); dropping process");
5381            EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
5382            if (pid > 0 && pid != MY_PID) {
5383                Process.killProcessQuiet(pid);
5384                //TODO: Process.killProcessGroup(app.info.uid, pid);
5385            } else {
5386                try {
5387                    thread.scheduleExit();
5388                } catch (Exception e) {
5389                    // Ignore exceptions.
5390                }
5391            }
5392            return false;
5393        }
5394
5395        // If this application record is still attached to a previous
5396        // process, clean it up now.
5397        if (app.thread != null) {
5398            handleAppDiedLocked(app, true, true);
5399        }
5400
5401        // Tell the process all about itself.
5402
5403        if (localLOGV) Slog.v(
5404                TAG, "Binding process pid " + pid + " to record " + app);
5405
5406        final String processName = app.processName;
5407        try {
5408            AppDeathRecipient adr = new AppDeathRecipient(
5409                    app, pid, thread);
5410            thread.asBinder().linkToDeath(adr, 0);
5411            app.deathRecipient = adr;
5412        } catch (RemoteException e) {
5413            app.resetPackageList(mProcessStats);
5414            startProcessLocked(app, "link fail", processName);
5415            return false;
5416        }
5417
5418        EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
5419
5420        app.makeActive(thread, mProcessStats);
5421        app.curAdj = app.setAdj = -100;
5422        app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT;
5423        app.forcingToForeground = null;
5424        updateProcessForegroundLocked(app, false, false);
5425        app.hasShownUi = false;
5426        app.debugging = false;
5427        app.cached = false;
5428
5429        mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
5430
5431        boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
5432        List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
5433
5434        if (!normalMode) {
5435            Slog.i(TAG, "Launching preboot mode app: " + app);
5436        }
5437
5438        if (localLOGV) Slog.v(
5439            TAG, "New app record " + app
5440            + " thread=" + thread.asBinder() + " pid=" + pid);
5441        try {
5442            int testMode = IApplicationThread.DEBUG_OFF;
5443            if (mDebugApp != null && mDebugApp.equals(processName)) {
5444                testMode = mWaitForDebugger
5445                    ? IApplicationThread.DEBUG_WAIT
5446                    : IApplicationThread.DEBUG_ON;
5447                app.debugging = true;
5448                if (mDebugTransient) {
5449                    mDebugApp = mOrigDebugApp;
5450                    mWaitForDebugger = mOrigWaitForDebugger;
5451                }
5452            }
5453            String profileFile = app.instrumentationProfileFile;
5454            ParcelFileDescriptor profileFd = null;
5455            boolean profileAutoStop = false;
5456            if (mProfileApp != null && mProfileApp.equals(processName)) {
5457                mProfileProc = app;
5458                profileFile = mProfileFile;
5459                profileFd = mProfileFd;
5460                profileAutoStop = mAutoStopProfiler;
5461            }
5462            boolean enableOpenGlTrace = false;
5463            if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
5464                enableOpenGlTrace = true;
5465                mOpenGlTraceApp = null;
5466            }
5467
5468            // If the app is being launched for restore or full backup, set it up specially
5469            boolean isRestrictedBackupMode = false;
5470            if (mBackupTarget != null && mBackupAppName.equals(processName)) {
5471                isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
5472                        || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
5473                        || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
5474            }
5475
5476            ensurePackageDexOpt(app.instrumentationInfo != null
5477                    ? app.instrumentationInfo.packageName
5478                    : app.info.packageName);
5479            if (app.instrumentationClass != null) {
5480                ensurePackageDexOpt(app.instrumentationClass.getPackageName());
5481            }
5482            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
5483                    + processName + " with config " + mConfiguration);
5484            ApplicationInfo appInfo = app.instrumentationInfo != null
5485                    ? app.instrumentationInfo : app.info;
5486            app.compat = compatibilityInfoForPackageLocked(appInfo);
5487            if (profileFd != null) {
5488                profileFd = profileFd.dup();
5489            }
5490            thread.bindApplication(processName, appInfo, providers,
5491                    app.instrumentationClass, profileFile, profileFd, profileAutoStop,
5492                    app.instrumentationArguments, app.instrumentationWatcher,
5493                    app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
5494                    isRestrictedBackupMode || !normalMode, app.persistent,
5495                    new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
5496                    mCoreSettingsObserver.getCoreSettingsLocked());
5497            updateLruProcessLocked(app, false, null);
5498            app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
5499        } catch (Exception e) {
5500            // todo: Yikes!  What should we do?  For now we will try to
5501            // start another process, but that could easily get us in
5502            // an infinite loop of restarting processes...
5503            Slog.w(TAG, "Exception thrown during bind!", e);
5504
5505            app.resetPackageList(mProcessStats);
5506            app.unlinkDeathRecipient();
5507            startProcessLocked(app, "bind fail", processName);
5508            return false;
5509        }
5510
5511        // Remove this record from the list of starting applications.
5512        mPersistentStartingProcesses.remove(app);
5513        if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
5514                "Attach application locked removing on hold: " + app);
5515        mProcessesOnHold.remove(app);
5516
5517        boolean badApp = false;
5518        boolean didSomething = false;
5519
5520        // See if the top visible activity is waiting to run in this process...
5521        if (normalMode) {
5522            try {
5523                if (mStackSupervisor.attachApplicationLocked(app)) {
5524                    didSomething = true;
5525                }
5526            } catch (Exception e) {
5527                badApp = true;
5528            }
5529        }
5530
5531        // Find any services that should be running in this process...
5532        if (!badApp) {
5533            try {
5534                didSomething |= mServices.attachApplicationLocked(app, processName);
5535            } catch (Exception e) {
5536                badApp = true;
5537            }
5538        }
5539
5540        // Check if a next-broadcast receiver is in this process...
5541        if (!badApp && isPendingBroadcastProcessLocked(pid)) {
5542            try {
5543                didSomething |= sendPendingBroadcastsLocked(app);
5544            } catch (Exception e) {
5545                // If the app died trying to launch the receiver we declare it 'bad'
5546                badApp = true;
5547            }
5548        }
5549
5550        // Check whether the next backup agent is in this process...
5551        if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
5552            if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
5553            ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
5554            try {
5555                thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
5556                        compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
5557                        mBackupTarget.backupMode);
5558            } catch (Exception e) {
5559                Slog.w(TAG, "Exception scheduling backup agent creation: ");
5560                e.printStackTrace();
5561            }
5562        }
5563
5564        if (badApp) {
5565            // todo: Also need to kill application to deal with all
5566            // kinds of exceptions.
5567            handleAppDiedLocked(app, false, true);
5568            return false;
5569        }
5570
5571        if (!didSomething) {
5572            updateOomAdjLocked();
5573        }
5574
5575        return true;
5576    }
5577
5578    @Override
5579    public final void attachApplication(IApplicationThread thread) {
5580        synchronized (this) {
5581            int callingPid = Binder.getCallingPid();
5582            final long origId = Binder.clearCallingIdentity();
5583            attachApplicationLocked(thread, callingPid);
5584            Binder.restoreCallingIdentity(origId);
5585        }
5586    }
5587
5588    @Override
5589    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
5590        final long origId = Binder.clearCallingIdentity();
5591        synchronized (this) {
5592            ActivityStack stack = ActivityRecord.getStackLocked(token);
5593            if (stack != null) {
5594                ActivityRecord r =
5595                        mStackSupervisor.activityIdleInternalLocked(token, false, config);
5596                if (stopProfiling) {
5597                    if ((mProfileProc == r.app) && (mProfileFd != null)) {
5598                        try {
5599                            mProfileFd.close();
5600                        } catch (IOException e) {
5601                        }
5602                        clearProfilerLocked();
5603                    }
5604                }
5605            }
5606        }
5607        Binder.restoreCallingIdentity(origId);
5608    }
5609
5610    void postEnableScreenAfterBootLocked() {
5611        mHandler.sendEmptyMessage(ENABLE_SCREEN_AFTER_BOOT_MSG);
5612    }
5613
5614    void enableScreenAfterBoot() {
5615        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
5616                SystemClock.uptimeMillis());
5617        mWindowManager.enableScreenAfterBoot();
5618
5619        synchronized (this) {
5620            updateEventDispatchingLocked();
5621        }
5622    }
5623
5624    @Override
5625    public void showBootMessage(final CharSequence msg, final boolean always) {
5626        enforceNotIsolatedCaller("showBootMessage");
5627        mWindowManager.showBootMessage(msg, always);
5628    }
5629
5630    @Override
5631    public void dismissKeyguardOnNextActivity() {
5632        enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
5633        final long token = Binder.clearCallingIdentity();
5634        try {
5635            synchronized (this) {
5636                if (DEBUG_LOCKSCREEN) logLockScreen("");
5637                if (mLockScreenShown) {
5638                    mLockScreenShown = false;
5639                    comeOutOfSleepIfNeededLocked();
5640                }
5641                mStackSupervisor.setDismissKeyguard(true);
5642            }
5643        } finally {
5644            Binder.restoreCallingIdentity(token);
5645        }
5646    }
5647
5648    final void finishBooting() {
5649        // Register receivers to handle package update events
5650        mPackageMonitor.register(mContext, Looper.getMainLooper(), false);
5651
5652        synchronized (this) {
5653            // Ensure that any processes we had put on hold are now started
5654            // up.
5655            final int NP = mProcessesOnHold.size();
5656            if (NP > 0) {
5657                ArrayList<ProcessRecord> procs =
5658                    new ArrayList<ProcessRecord>(mProcessesOnHold);
5659                for (int ip=0; ip<NP; ip++) {
5660                    if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
5661                            + procs.get(ip));
5662                    startProcessLocked(procs.get(ip), "on-hold", null);
5663                }
5664            }
5665
5666            if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
5667                // Start looking for apps that are abusing wake locks.
5668                Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
5669                mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
5670                // Tell anyone interested that we are done booting!
5671                SystemProperties.set("sys.boot_completed", "1");
5672                SystemProperties.set("dev.bootcomplete", "1");
5673                for (int i=0; i<mStartedUsers.size(); i++) {
5674                    UserStartedState uss = mStartedUsers.valueAt(i);
5675                    if (uss.mState == UserStartedState.STATE_BOOTING) {
5676                        uss.mState = UserStartedState.STATE_RUNNING;
5677                        final int userId = mStartedUsers.keyAt(i);
5678                        Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
5679                        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
5680                        intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
5681                        broadcastIntentLocked(null, null, intent, null,
5682                                new IIntentReceiver.Stub() {
5683                                    @Override
5684                                    public void performReceive(Intent intent, int resultCode,
5685                                            String data, Bundle extras, boolean ordered,
5686                                            boolean sticky, int sendingUser) {
5687                                        synchronized (ActivityManagerService.this) {
5688                                            requestPssAllProcsLocked(SystemClock.uptimeMillis(),
5689                                                    true, false);
5690                                        }
5691                                    }
5692                                },
5693                                0, null, null,
5694                                android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
5695                                AppOpsManager.OP_NONE, true, false, MY_PID, Process.SYSTEM_UID,
5696                                userId);
5697                    }
5698                }
5699                scheduleStartProfilesLocked();
5700            }
5701        }
5702    }
5703
5704    final void ensureBootCompleted() {
5705        boolean booting;
5706        boolean enableScreen;
5707        synchronized (this) {
5708            booting = mBooting;
5709            mBooting = false;
5710            enableScreen = !mBooted;
5711            mBooted = true;
5712        }
5713
5714        if (booting) {
5715            finishBooting();
5716        }
5717
5718        if (enableScreen) {
5719            enableScreenAfterBoot();
5720        }
5721    }
5722
5723    @Override
5724    public final void activityResumed(IBinder token) {
5725        final long origId = Binder.clearCallingIdentity();
5726        synchronized(this) {
5727            ActivityStack stack = ActivityRecord.getStackLocked(token);
5728            if (stack != null) {
5729                ActivityRecord.activityResumedLocked(token);
5730            }
5731        }
5732        Binder.restoreCallingIdentity(origId);
5733    }
5734
5735    @Override
5736    public final void activityPaused(IBinder token, PersistableBundle persistentState) {
5737        final long origId = Binder.clearCallingIdentity();
5738        synchronized(this) {
5739            ActivityStack stack = ActivityRecord.getStackLocked(token);
5740            if (stack != null) {
5741                stack.activityPausedLocked(token, false, persistentState);
5742            }
5743        }
5744        Binder.restoreCallingIdentity(origId);
5745    }
5746
5747    @Override
5748    public final void activityStopped(IBinder token, Bundle icicle,
5749            PersistableBundle persistentState, CharSequence description) {
5750        if (localLOGV) Slog.v(TAG, "Activity stopped: token=" + token);
5751
5752        // Refuse possible leaked file descriptors
5753        if (icicle != null && icicle.hasFileDescriptors()) {
5754            throw new IllegalArgumentException("File descriptors passed in Bundle");
5755        }
5756
5757        final long origId = Binder.clearCallingIdentity();
5758
5759        synchronized (this) {
5760            ActivityRecord r = ActivityRecord.isInStackLocked(token);
5761            if (r != null) {
5762                r.task.stack.activityStoppedLocked(r, icicle, persistentState, description);
5763            }
5764        }
5765
5766        trimApplications();
5767
5768        Binder.restoreCallingIdentity(origId);
5769    }
5770
5771    @Override
5772    public final void activityDestroyed(IBinder token) {
5773        if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
5774        synchronized (this) {
5775            ActivityStack stack = ActivityRecord.getStackLocked(token);
5776            if (stack != null) {
5777                stack.activityDestroyedLocked(token);
5778            }
5779        }
5780    }
5781
5782    @Override
5783    public final void mediaResourcesReleased(IBinder token) {
5784        final long origId = Binder.clearCallingIdentity();
5785        try {
5786            synchronized (this) {
5787                ActivityStack stack = ActivityRecord.getStackLocked(token);
5788                if (stack != null) {
5789                    stack.mediaResourcesReleased(token);
5790                }
5791            }
5792        } finally {
5793            Binder.restoreCallingIdentity(origId);
5794        }
5795    }
5796
5797    @Override
5798    public final void notifyLaunchTaskBehindComplete(IBinder token) {
5799        mStackSupervisor.scheduleLaunchTaskBehindComplete(token);
5800    }
5801
5802    @Override
5803    public final void notifyEnterAnimationComplete(IBinder token) {
5804        mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token));
5805    }
5806
5807    @Override
5808    public String getCallingPackage(IBinder token) {
5809        synchronized (this) {
5810            ActivityRecord r = getCallingRecordLocked(token);
5811            return r != null ? r.info.packageName : null;
5812        }
5813    }
5814
5815    @Override
5816    public ComponentName getCallingActivity(IBinder token) {
5817        synchronized (this) {
5818            ActivityRecord r = getCallingRecordLocked(token);
5819            return r != null ? r.intent.getComponent() : null;
5820        }
5821    }
5822
5823    private ActivityRecord getCallingRecordLocked(IBinder token) {
5824        ActivityRecord r = ActivityRecord.isInStackLocked(token);
5825        if (r == null) {
5826            return null;
5827        }
5828        return r.resultTo;
5829    }
5830
5831    @Override
5832    public ComponentName getActivityClassForToken(IBinder token) {
5833        synchronized(this) {
5834            ActivityRecord r = ActivityRecord.isInStackLocked(token);
5835            if (r == null) {
5836                return null;
5837            }
5838            return r.intent.getComponent();
5839        }
5840    }
5841
5842    @Override
5843    public String getPackageForToken(IBinder token) {
5844        synchronized(this) {
5845            ActivityRecord r = ActivityRecord.isInStackLocked(token);
5846            if (r == null) {
5847                return null;
5848            }
5849            return r.packageName;
5850        }
5851    }
5852
5853    @Override
5854    public IIntentSender getIntentSender(int type,
5855            String packageName, IBinder token, String resultWho,
5856            int requestCode, Intent[] intents, String[] resolvedTypes,
5857            int flags, Bundle options, int userId) {
5858        enforceNotIsolatedCaller("getIntentSender");
5859        // Refuse possible leaked file descriptors
5860        if (intents != null) {
5861            if (intents.length < 1) {
5862                throw new IllegalArgumentException("Intents array length must be >= 1");
5863            }
5864            for (int i=0; i<intents.length; i++) {
5865                Intent intent = intents[i];
5866                if (intent != null) {
5867                    if (intent.hasFileDescriptors()) {
5868                        throw new IllegalArgumentException("File descriptors passed in Intent");
5869                    }
5870                    if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
5871                            (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
5872                        throw new IllegalArgumentException(
5873                                "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
5874                    }
5875                    intents[i] = new Intent(intent);
5876                }
5877            }
5878            if (resolvedTypes != null && resolvedTypes.length != intents.length) {
5879                throw new IllegalArgumentException(
5880                        "Intent array length does not match resolvedTypes length");
5881            }
5882        }
5883        if (options != null) {
5884            if (options.hasFileDescriptors()) {
5885                throw new IllegalArgumentException("File descriptors passed in options");
5886            }
5887        }
5888
5889        synchronized(this) {
5890            int callingUid = Binder.getCallingUid();
5891            int origUserId = userId;
5892            userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
5893                    type == ActivityManager.INTENT_SENDER_BROADCAST,
5894                    ALLOW_NON_FULL, "getIntentSender", null);
5895            if (origUserId == UserHandle.USER_CURRENT) {
5896                // We don't want to evaluate this until the pending intent is
5897                // actually executed.  However, we do want to always do the
5898                // security checking for it above.
5899                userId = UserHandle.USER_CURRENT;
5900            }
5901            try {
5902                if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
5903                    int uid = AppGlobals.getPackageManager()
5904                            .getPackageUid(packageName, UserHandle.getUserId(callingUid));
5905                    if (!UserHandle.isSameApp(callingUid, uid)) {
5906                        String msg = "Permission Denial: getIntentSender() from pid="
5907                            + Binder.getCallingPid()
5908                            + ", uid=" + Binder.getCallingUid()
5909                            + ", (need uid=" + uid + ")"
5910                            + " is not allowed to send as package " + packageName;
5911                        Slog.w(TAG, msg);
5912                        throw new SecurityException(msg);
5913                    }
5914                }
5915
5916                return getIntentSenderLocked(type, packageName, callingUid, userId,
5917                        token, resultWho, requestCode, intents, resolvedTypes, flags, options);
5918
5919            } catch (RemoteException e) {
5920                throw new SecurityException(e);
5921            }
5922        }
5923    }
5924
5925    IIntentSender getIntentSenderLocked(int type, String packageName,
5926            int callingUid, int userId, IBinder token, String resultWho,
5927            int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
5928            Bundle options) {
5929        if (DEBUG_MU)
5930            Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
5931        ActivityRecord activity = null;
5932        if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5933            activity = ActivityRecord.isInStackLocked(token);
5934            if (activity == null) {
5935                return null;
5936            }
5937            if (activity.finishing) {
5938                return null;
5939            }
5940        }
5941
5942        final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
5943        final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
5944        final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
5945        flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
5946                |PendingIntent.FLAG_UPDATE_CURRENT);
5947
5948        PendingIntentRecord.Key key = new PendingIntentRecord.Key(
5949                type, packageName, activity, resultWho,
5950                requestCode, intents, resolvedTypes, flags, options, userId);
5951        WeakReference<PendingIntentRecord> ref;
5952        ref = mIntentSenderRecords.get(key);
5953        PendingIntentRecord rec = ref != null ? ref.get() : null;
5954        if (rec != null) {
5955            if (!cancelCurrent) {
5956                if (updateCurrent) {
5957                    if (rec.key.requestIntent != null) {
5958                        rec.key.requestIntent.replaceExtras(intents != null ?
5959                                intents[intents.length - 1] : null);
5960                    }
5961                    if (intents != null) {
5962                        intents[intents.length-1] = rec.key.requestIntent;
5963                        rec.key.allIntents = intents;
5964                        rec.key.allResolvedTypes = resolvedTypes;
5965                    } else {
5966                        rec.key.allIntents = null;
5967                        rec.key.allResolvedTypes = null;
5968                    }
5969                }
5970                return rec;
5971            }
5972            rec.canceled = true;
5973            mIntentSenderRecords.remove(key);
5974        }
5975        if (noCreate) {
5976            return rec;
5977        }
5978        rec = new PendingIntentRecord(this, key, callingUid);
5979        mIntentSenderRecords.put(key, rec.ref);
5980        if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
5981            if (activity.pendingResults == null) {
5982                activity.pendingResults
5983                        = new HashSet<WeakReference<PendingIntentRecord>>();
5984            }
5985            activity.pendingResults.add(rec.ref);
5986        }
5987        return rec;
5988    }
5989
5990    @Override
5991    public void cancelIntentSender(IIntentSender sender) {
5992        if (!(sender instanceof PendingIntentRecord)) {
5993            return;
5994        }
5995        synchronized(this) {
5996            PendingIntentRecord rec = (PendingIntentRecord)sender;
5997            try {
5998                int uid = AppGlobals.getPackageManager()
5999                        .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
6000                if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
6001                    String msg = "Permission Denial: cancelIntentSender() from pid="
6002                        + Binder.getCallingPid()
6003                        + ", uid=" + Binder.getCallingUid()
6004                        + " is not allowed to cancel packges "
6005                        + rec.key.packageName;
6006                    Slog.w(TAG, msg);
6007                    throw new SecurityException(msg);
6008                }
6009            } catch (RemoteException e) {
6010                throw new SecurityException(e);
6011            }
6012            cancelIntentSenderLocked(rec, true);
6013        }
6014    }
6015
6016    void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
6017        rec.canceled = true;
6018        mIntentSenderRecords.remove(rec.key);
6019        if (cleanActivity && rec.key.activity != null) {
6020            rec.key.activity.pendingResults.remove(rec.ref);
6021        }
6022    }
6023
6024    @Override
6025    public String getPackageForIntentSender(IIntentSender pendingResult) {
6026        if (!(pendingResult instanceof PendingIntentRecord)) {
6027            return null;
6028        }
6029        try {
6030            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6031            return res.key.packageName;
6032        } catch (ClassCastException e) {
6033        }
6034        return null;
6035    }
6036
6037    @Override
6038    public int getUidForIntentSender(IIntentSender sender) {
6039        if (sender instanceof PendingIntentRecord) {
6040            try {
6041                PendingIntentRecord res = (PendingIntentRecord)sender;
6042                return res.uid;
6043            } catch (ClassCastException e) {
6044            }
6045        }
6046        return -1;
6047    }
6048
6049    @Override
6050    public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
6051        if (!(pendingResult instanceof PendingIntentRecord)) {
6052            return false;
6053        }
6054        try {
6055            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6056            if (res.key.allIntents == null) {
6057                return false;
6058            }
6059            for (int i=0; i<res.key.allIntents.length; i++) {
6060                Intent intent = res.key.allIntents[i];
6061                if (intent.getPackage() != null && intent.getComponent() != null) {
6062                    return false;
6063                }
6064            }
6065            return true;
6066        } catch (ClassCastException e) {
6067        }
6068        return false;
6069    }
6070
6071    @Override
6072    public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
6073        if (!(pendingResult instanceof PendingIntentRecord)) {
6074            return false;
6075        }
6076        try {
6077            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6078            if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
6079                return true;
6080            }
6081            return false;
6082        } catch (ClassCastException e) {
6083        }
6084        return false;
6085    }
6086
6087    @Override
6088    public Intent getIntentForIntentSender(IIntentSender pendingResult) {
6089        if (!(pendingResult instanceof PendingIntentRecord)) {
6090            return null;
6091        }
6092        try {
6093            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6094            return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
6095        } catch (ClassCastException e) {
6096        }
6097        return null;
6098    }
6099
6100    @Override
6101    public String getTagForIntentSender(IIntentSender pendingResult, String prefix) {
6102        if (!(pendingResult instanceof PendingIntentRecord)) {
6103            return null;
6104        }
6105        try {
6106            PendingIntentRecord res = (PendingIntentRecord)pendingResult;
6107            Intent intent = res.key.requestIntent;
6108            if (intent != null) {
6109                if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null
6110                        || res.lastTagPrefix.equals(prefix))) {
6111                    return res.lastTag;
6112                }
6113                res.lastTagPrefix = prefix;
6114                StringBuilder sb = new StringBuilder(128);
6115                if (prefix != null) {
6116                    sb.append(prefix);
6117                }
6118                if (intent.getAction() != null) {
6119                    sb.append(intent.getAction());
6120                } else if (intent.getComponent() != null) {
6121                    intent.getComponent().appendShortString(sb);
6122                } else {
6123                    sb.append("?");
6124                }
6125                return res.lastTag = sb.toString();
6126            }
6127        } catch (ClassCastException e) {
6128        }
6129        return null;
6130    }
6131
6132    @Override
6133    public void setProcessLimit(int max) {
6134        enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
6135                "setProcessLimit()");
6136        synchronized (this) {
6137            mProcessLimit = max < 0 ? ProcessList.MAX_CACHED_APPS : max;
6138            mProcessLimitOverride = max;
6139        }
6140        trimApplications();
6141    }
6142
6143    @Override
6144    public int getProcessLimit() {
6145        synchronized (this) {
6146            return mProcessLimitOverride;
6147        }
6148    }
6149
6150    void foregroundTokenDied(ForegroundToken token) {
6151        synchronized (ActivityManagerService.this) {
6152            synchronized (mPidsSelfLocked) {
6153                ForegroundToken cur
6154                    = mForegroundProcesses.get(token.pid);
6155                if (cur != token) {
6156                    return;
6157                }
6158                mForegroundProcesses.remove(token.pid);
6159                ProcessRecord pr = mPidsSelfLocked.get(token.pid);
6160                if (pr == null) {
6161                    return;
6162                }
6163                pr.forcingToForeground = null;
6164                updateProcessForegroundLocked(pr, false, false);
6165            }
6166            updateOomAdjLocked();
6167        }
6168    }
6169
6170    @Override
6171    public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
6172        enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
6173                "setProcessForeground()");
6174        synchronized(this) {
6175            boolean changed = false;
6176
6177            synchronized (mPidsSelfLocked) {
6178                ProcessRecord pr = mPidsSelfLocked.get(pid);
6179                if (pr == null && isForeground) {
6180                    Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
6181                    return;
6182                }
6183                ForegroundToken oldToken = mForegroundProcesses.get(pid);
6184                if (oldToken != null) {
6185                    oldToken.token.unlinkToDeath(oldToken, 0);
6186                    mForegroundProcesses.remove(pid);
6187                    if (pr != null) {
6188                        pr.forcingToForeground = null;
6189                    }
6190                    changed = true;
6191                }
6192                if (isForeground && token != null) {
6193                    ForegroundToken newToken = new ForegroundToken() {
6194                        @Override
6195                        public void binderDied() {
6196                            foregroundTokenDied(this);
6197                        }
6198                    };
6199                    newToken.pid = pid;
6200                    newToken.token = token;
6201                    try {
6202                        token.linkToDeath(newToken, 0);
6203                        mForegroundProcesses.put(pid, newToken);
6204                        pr.forcingToForeground = token;
6205                        changed = true;
6206                    } catch (RemoteException e) {
6207                        // If the process died while doing this, we will later
6208                        // do the cleanup with the process death link.
6209                    }
6210                }
6211            }
6212
6213            if (changed) {
6214                updateOomAdjLocked();
6215            }
6216        }
6217    }
6218
6219    // =========================================================
6220    // PERMISSIONS
6221    // =========================================================
6222
6223    static class PermissionController extends IPermissionController.Stub {
6224        ActivityManagerService mActivityManagerService;
6225        PermissionController(ActivityManagerService activityManagerService) {
6226            mActivityManagerService = activityManagerService;
6227        }
6228
6229        @Override
6230        public boolean checkPermission(String permission, int pid, int uid) {
6231            return mActivityManagerService.checkPermission(permission, pid,
6232                    uid) == PackageManager.PERMISSION_GRANTED;
6233        }
6234    }
6235
6236    class IntentFirewallInterface implements IntentFirewall.AMSInterface {
6237        @Override
6238        public int checkComponentPermission(String permission, int pid, int uid,
6239                int owningUid, boolean exported) {
6240            return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
6241                    owningUid, exported);
6242        }
6243
6244        @Override
6245        public Object getAMSLock() {
6246            return ActivityManagerService.this;
6247        }
6248    }
6249
6250    /**
6251     * This can be called with or without the global lock held.
6252     */
6253    int checkComponentPermission(String permission, int pid, int uid,
6254            int owningUid, boolean exported) {
6255        // We might be performing an operation on behalf of an indirect binder
6256        // invocation, e.g. via {@link #openContentUri}.  Check and adjust the
6257        // client identity accordingly before proceeding.
6258        Identity tlsIdentity = sCallerIdentity.get();
6259        if (tlsIdentity != null) {
6260            Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
6261                    + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
6262            uid = tlsIdentity.uid;
6263            pid = tlsIdentity.pid;
6264        }
6265
6266        if (pid == MY_PID) {
6267            return PackageManager.PERMISSION_GRANTED;
6268        }
6269
6270        return ActivityManager.checkComponentPermission(permission, uid,
6271                owningUid, exported);
6272    }
6273
6274    /**
6275     * As the only public entry point for permissions checking, this method
6276     * can enforce the semantic that requesting a check on a null global
6277     * permission is automatically denied.  (Internally a null permission
6278     * string is used when calling {@link #checkComponentPermission} in cases
6279     * when only uid-based security is needed.)
6280     *
6281     * This can be called with or without the global lock held.
6282     */
6283    @Override
6284    public int checkPermission(String permission, int pid, int uid) {
6285        if (permission == null) {
6286            return PackageManager.PERMISSION_DENIED;
6287        }
6288        return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
6289    }
6290
6291    /**
6292     * Binder IPC calls go through the public entry point.
6293     * This can be called with or without the global lock held.
6294     */
6295    int checkCallingPermission(String permission) {
6296        return checkPermission(permission,
6297                Binder.getCallingPid(),
6298                UserHandle.getAppId(Binder.getCallingUid()));
6299    }
6300
6301    /**
6302     * This can be called with or without the global lock held.
6303     */
6304    void enforceCallingPermission(String permission, String func) {
6305        if (checkCallingPermission(permission)
6306                == PackageManager.PERMISSION_GRANTED) {
6307            return;
6308        }
6309
6310        String msg = "Permission Denial: " + func + " from pid="
6311                + Binder.getCallingPid()
6312                + ", uid=" + Binder.getCallingUid()
6313                + " requires " + permission;
6314        Slog.w(TAG, msg);
6315        throw new SecurityException(msg);
6316    }
6317
6318    /**
6319     * Determine if UID is holding permissions required to access {@link Uri} in
6320     * the given {@link ProviderInfo}. Final permission checking is always done
6321     * in {@link ContentProvider}.
6322     */
6323    private final boolean checkHoldingPermissionsLocked(
6324            IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) {
6325        if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6326                "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid);
6327        if (UserHandle.getUserId(uid) != grantUri.sourceUserId) {
6328            if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true)
6329                    != PERMISSION_GRANTED) {
6330                return false;
6331            }
6332        }
6333        return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true);
6334    }
6335
6336    private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi,
6337            GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) {
6338        if (pi.applicationInfo.uid == uid) {
6339            return true;
6340        } else if (!pi.exported) {
6341            return false;
6342        }
6343
6344        boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
6345        boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
6346        try {
6347            // check if target holds top-level <provider> permissions
6348            if (!readMet && pi.readPermission != null && considerUidPermissions
6349                    && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
6350                readMet = true;
6351            }
6352            if (!writeMet && pi.writePermission != null && considerUidPermissions
6353                    && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
6354                writeMet = true;
6355            }
6356
6357            // track if unprotected read/write is allowed; any denied
6358            // <path-permission> below removes this ability
6359            boolean allowDefaultRead = pi.readPermission == null;
6360            boolean allowDefaultWrite = pi.writePermission == null;
6361
6362            // check if target holds any <path-permission> that match uri
6363            final PathPermission[] pps = pi.pathPermissions;
6364            if (pps != null) {
6365                final String path = grantUri.uri.getPath();
6366                int i = pps.length;
6367                while (i > 0 && (!readMet || !writeMet)) {
6368                    i--;
6369                    PathPermission pp = pps[i];
6370                    if (pp.match(path)) {
6371                        if (!readMet) {
6372                            final String pprperm = pp.getReadPermission();
6373                            if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
6374                                    + pprperm + " for " + pp.getPath()
6375                                    + ": match=" + pp.match(path)
6376                                    + " check=" + pm.checkUidPermission(pprperm, uid));
6377                            if (pprperm != null) {
6378                                if (considerUidPermissions && pm.checkUidPermission(pprperm, uid)
6379                                        == PERMISSION_GRANTED) {
6380                                    readMet = true;
6381                                } else {
6382                                    allowDefaultRead = false;
6383                                }
6384                            }
6385                        }
6386                        if (!writeMet) {
6387                            final String ppwperm = pp.getWritePermission();
6388                            if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
6389                                    + ppwperm + " for " + pp.getPath()
6390                                    + ": match=" + pp.match(path)
6391                                    + " check=" + pm.checkUidPermission(ppwperm, uid));
6392                            if (ppwperm != null) {
6393                                if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid)
6394                                        == PERMISSION_GRANTED) {
6395                                    writeMet = true;
6396                                } else {
6397                                    allowDefaultWrite = false;
6398                                }
6399                            }
6400                        }
6401                    }
6402                }
6403            }
6404
6405            // grant unprotected <provider> read/write, if not blocked by
6406            // <path-permission> above
6407            if (allowDefaultRead) readMet = true;
6408            if (allowDefaultWrite) writeMet = true;
6409
6410        } catch (RemoteException e) {
6411            return false;
6412        }
6413
6414        return readMet && writeMet;
6415    }
6416
6417    private ProviderInfo getProviderInfoLocked(String authority, int userHandle) {
6418        ProviderInfo pi = null;
6419        ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle);
6420        if (cpr != null) {
6421            pi = cpr.info;
6422        } else {
6423            try {
6424                pi = AppGlobals.getPackageManager().resolveContentProvider(
6425                        authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle);
6426            } catch (RemoteException ex) {
6427            }
6428        }
6429        return pi;
6430    }
6431
6432    private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) {
6433        final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
6434        if (targetUris != null) {
6435            return targetUris.get(grantUri);
6436        }
6437        return null;
6438    }
6439
6440    private UriPermission findOrCreateUriPermissionLocked(String sourcePkg,
6441            String targetPkg, int targetUid, GrantUri grantUri) {
6442        ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid);
6443        if (targetUris == null) {
6444            targetUris = Maps.newArrayMap();
6445            mGrantedUriPermissions.put(targetUid, targetUris);
6446        }
6447
6448        UriPermission perm = targetUris.get(grantUri);
6449        if (perm == null) {
6450            perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri);
6451            targetUris.put(grantUri, perm);
6452        }
6453
6454        return perm;
6455    }
6456
6457    private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid,
6458            final int modeFlags) {
6459        final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0;
6460        final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE
6461                : UriPermission.STRENGTH_OWNED;
6462
6463        // Root gets to do everything.
6464        if (uid == 0) {
6465            return true;
6466        }
6467
6468        final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
6469        if (perms == null) return false;
6470
6471        // First look for exact match
6472        final UriPermission exactPerm = perms.get(grantUri);
6473        if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) {
6474            return true;
6475        }
6476
6477        // No exact match, look for prefixes
6478        final int N = perms.size();
6479        for (int i = 0; i < N; i++) {
6480            final UriPermission perm = perms.valueAt(i);
6481            if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri)
6482                    && perm.getStrength(modeFlags) >= minStrength) {
6483                return true;
6484            }
6485        }
6486
6487        return false;
6488    }
6489
6490    @Override
6491    public int checkUriPermission(Uri uri, int pid, int uid,
6492            final int modeFlags, int userId) {
6493        enforceNotIsolatedCaller("checkUriPermission");
6494
6495        // Another redirected-binder-call permissions check as in
6496        // {@link checkComponentPermission}.
6497        Identity tlsIdentity = sCallerIdentity.get();
6498        if (tlsIdentity != null) {
6499            uid = tlsIdentity.uid;
6500            pid = tlsIdentity.pid;
6501        }
6502
6503        // Our own process gets to do everything.
6504        if (pid == MY_PID) {
6505            return PackageManager.PERMISSION_GRANTED;
6506        }
6507        synchronized (this) {
6508            return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags)
6509                    ? PackageManager.PERMISSION_GRANTED
6510                    : PackageManager.PERMISSION_DENIED;
6511        }
6512    }
6513
6514    /**
6515     * Check if the targetPkg can be granted permission to access uri by
6516     * the callingUid using the given modeFlags.  Throws a security exception
6517     * if callingUid is not allowed to do this.  Returns the uid of the target
6518     * if the URI permission grant should be performed; returns -1 if it is not
6519     * needed (for example targetPkg already has permission to access the URI).
6520     * If you already know the uid of the target, you can supply it in
6521     * lastTargetUid else set that to -1.
6522     */
6523    int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
6524            final int modeFlags, int lastTargetUid) {
6525        if (!Intent.isAccessUriMode(modeFlags)) {
6526            return -1;
6527        }
6528
6529        if (targetPkg != null) {
6530            if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6531                    "Checking grant " + targetPkg + " permission to " + grantUri);
6532        }
6533
6534        final IPackageManager pm = AppGlobals.getPackageManager();
6535
6536        // If this is not a content: uri, we can't do anything with it.
6537        if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) {
6538            if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6539                    "Can't grant URI permission for non-content URI: " + grantUri);
6540            return -1;
6541        }
6542
6543        final String authority = grantUri.uri.getAuthority();
6544        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
6545        if (pi == null) {
6546            Slog.w(TAG, "No content provider found for permission check: " +
6547                    grantUri.uri.toSafeString());
6548            return -1;
6549        }
6550
6551        int targetUid = lastTargetUid;
6552        if (targetUid < 0 && targetPkg != null) {
6553            try {
6554                targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
6555                if (targetUid < 0) {
6556                    if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6557                            "Can't grant URI permission no uid for: " + targetPkg);
6558                    return -1;
6559                }
6560            } catch (RemoteException ex) {
6561                return -1;
6562            }
6563        }
6564
6565        if (targetUid >= 0) {
6566            // First...  does the target actually need this permission?
6567            if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) {
6568                // No need to grant the target this permission.
6569                if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6570                        "Target " + targetPkg + " already has full permission to " + grantUri);
6571                return -1;
6572            }
6573        } else {
6574            // First...  there is no target package, so can anyone access it?
6575            boolean allowed = pi.exported;
6576            if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
6577                if (pi.readPermission != null) {
6578                    allowed = false;
6579                }
6580            }
6581            if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
6582                if (pi.writePermission != null) {
6583                    allowed = false;
6584                }
6585            }
6586            if (allowed) {
6587                return -1;
6588            }
6589        }
6590
6591        /* There is a special cross user grant if:
6592         * - The target is on another user.
6593         * - Apps on the current user can access the uri without any uid permissions.
6594         * In this case, we grant a uri permission, even if the ContentProvider does not normally
6595         * grant uri permissions.
6596         */
6597        boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId
6598                && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid,
6599                modeFlags, false /*without considering the uid permissions*/);
6600
6601        // Second...  is the provider allowing granting of URI permissions?
6602        if (!specialCrossUserGrant) {
6603            if (!pi.grantUriPermissions) {
6604                throw new SecurityException("Provider " + pi.packageName
6605                        + "/" + pi.name
6606                        + " does not allow granting of Uri permissions (uri "
6607                        + grantUri + ")");
6608            }
6609            if (pi.uriPermissionPatterns != null) {
6610                final int N = pi.uriPermissionPatterns.length;
6611                boolean allowed = false;
6612                for (int i=0; i<N; i++) {
6613                    if (pi.uriPermissionPatterns[i] != null
6614                            && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) {
6615                        allowed = true;
6616                        break;
6617                    }
6618                }
6619                if (!allowed) {
6620                    throw new SecurityException("Provider " + pi.packageName
6621                            + "/" + pi.name
6622                            + " does not allow granting of permission to path of Uri "
6623                            + grantUri);
6624                }
6625            }
6626        }
6627
6628        // Third...  does the caller itself have permission to access
6629        // this uri?
6630        if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
6631            if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
6632                // Require they hold a strong enough Uri permission
6633                if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) {
6634                    throw new SecurityException("Uid " + callingUid
6635                            + " does not have permission to uri " + grantUri);
6636                }
6637            }
6638        }
6639        return targetUid;
6640    }
6641
6642    @Override
6643    public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri,
6644            final int modeFlags, int userId) {
6645        enforceNotIsolatedCaller("checkGrantUriPermission");
6646        synchronized(this) {
6647            return checkGrantUriPermissionLocked(callingUid, targetPkg,
6648                    new GrantUri(userId, uri, false), modeFlags, -1);
6649        }
6650    }
6651
6652    void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri,
6653            final int modeFlags, UriPermissionOwner owner) {
6654        if (!Intent.isAccessUriMode(modeFlags)) {
6655            return;
6656        }
6657
6658        // So here we are: the caller has the assumed permission
6659        // to the uri, and the target doesn't.  Let's now give this to
6660        // the target.
6661
6662        if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6663                "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri);
6664
6665        final String authority = grantUri.uri.getAuthority();
6666        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
6667        if (pi == null) {
6668            Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString());
6669            return;
6670        }
6671
6672        if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
6673            grantUri.prefix = true;
6674        }
6675        final UriPermission perm = findOrCreateUriPermissionLocked(
6676                pi.packageName, targetPkg, targetUid, grantUri);
6677        perm.grantModes(modeFlags, owner);
6678    }
6679
6680    void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri,
6681            final int modeFlags, UriPermissionOwner owner, int targetUserId) {
6682        if (targetPkg == null) {
6683            throw new NullPointerException("targetPkg");
6684        }
6685        int targetUid;
6686        final IPackageManager pm = AppGlobals.getPackageManager();
6687        try {
6688            targetUid = pm.getPackageUid(targetPkg, targetUserId);
6689        } catch (RemoteException ex) {
6690            return;
6691        }
6692
6693        targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags,
6694                targetUid);
6695        if (targetUid < 0) {
6696            return;
6697        }
6698
6699        grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags,
6700                owner);
6701    }
6702
6703    static class NeededUriGrants extends ArrayList<GrantUri> {
6704        final String targetPkg;
6705        final int targetUid;
6706        final int flags;
6707
6708        NeededUriGrants(String targetPkg, int targetUid, int flags) {
6709            this.targetPkg = targetPkg;
6710            this.targetUid = targetUid;
6711            this.flags = flags;
6712        }
6713    }
6714
6715    /**
6716     * Like checkGrantUriPermissionLocked, but takes an Intent.
6717     */
6718    NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
6719            String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) {
6720        if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6721                "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
6722                + " clip=" + (intent != null ? intent.getClipData() : null)
6723                + " from " + intent + "; flags=0x"
6724                + Integer.toHexString(intent != null ? intent.getFlags() : 0));
6725
6726        if (targetPkg == null) {
6727            throw new NullPointerException("targetPkg");
6728        }
6729
6730        if (intent == null) {
6731            return null;
6732        }
6733        Uri data = intent.getData();
6734        ClipData clip = intent.getClipData();
6735        if (data == null && clip == null) {
6736            return null;
6737        }
6738        // Default userId for uris in the intent (if they don't specify it themselves)
6739        int contentUserHint = intent.getContentUserHint();
6740        if (contentUserHint == UserHandle.USER_CURRENT) {
6741            contentUserHint = UserHandle.getUserId(callingUid);
6742        }
6743        final IPackageManager pm = AppGlobals.getPackageManager();
6744        int targetUid;
6745        if (needed != null) {
6746            targetUid = needed.targetUid;
6747        } else {
6748            try {
6749                targetUid = pm.getPackageUid(targetPkg, targetUserId);
6750            } catch (RemoteException ex) {
6751                return null;
6752            }
6753            if (targetUid < 0) {
6754                if (DEBUG_URI_PERMISSION) {
6755                    Slog.v(TAG, "Can't grant URI permission no uid for: " + targetPkg
6756                            + " on user " + targetUserId);
6757                }
6758                return null;
6759            }
6760        }
6761        if (data != null) {
6762            GrantUri grantUri = GrantUri.resolve(contentUserHint, data);
6763            targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
6764                    targetUid);
6765            if (targetUid > 0) {
6766                if (needed == null) {
6767                    needed = new NeededUriGrants(targetPkg, targetUid, mode);
6768                }
6769                needed.add(grantUri);
6770            }
6771        }
6772        if (clip != null) {
6773            for (int i=0; i<clip.getItemCount(); i++) {
6774                Uri uri = clip.getItemAt(i).getUri();
6775                if (uri != null) {
6776                    GrantUri grantUri = GrantUri.resolve(contentUserHint, uri);
6777                    targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode,
6778                            targetUid);
6779                    if (targetUid > 0) {
6780                        if (needed == null) {
6781                            needed = new NeededUriGrants(targetPkg, targetUid, mode);
6782                        }
6783                        needed.add(grantUri);
6784                    }
6785                } else {
6786                    Intent clipIntent = clip.getItemAt(i).getIntent();
6787                    if (clipIntent != null) {
6788                        NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
6789                                callingUid, targetPkg, clipIntent, mode, needed, targetUserId);
6790                        if (newNeeded != null) {
6791                            needed = newNeeded;
6792                        }
6793                    }
6794                }
6795            }
6796        }
6797
6798        return needed;
6799    }
6800
6801    /**
6802     * Like grantUriPermissionUncheckedLocked, but takes an Intent.
6803     */
6804    void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
6805            UriPermissionOwner owner) {
6806        if (needed != null) {
6807            for (int i=0; i<needed.size(); i++) {
6808                GrantUri grantUri = needed.get(i);
6809                grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
6810                        grantUri, needed.flags, owner);
6811            }
6812        }
6813    }
6814
6815    void grantUriPermissionFromIntentLocked(int callingUid,
6816            String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) {
6817        NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
6818                intent, intent != null ? intent.getFlags() : 0, null, targetUserId);
6819        if (needed == null) {
6820            return;
6821        }
6822
6823        grantUriPermissionUncheckedFromIntentLocked(needed, owner);
6824    }
6825
6826    @Override
6827    public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri,
6828            final int modeFlags, int userId) {
6829        enforceNotIsolatedCaller("grantUriPermission");
6830        GrantUri grantUri = new GrantUri(userId, uri, false);
6831        synchronized(this) {
6832            final ProcessRecord r = getRecordForAppLocked(caller);
6833            if (r == null) {
6834                throw new SecurityException("Unable to find app for caller "
6835                        + caller
6836                        + " when granting permission to uri " + grantUri);
6837            }
6838            if (targetPkg == null) {
6839                throw new IllegalArgumentException("null target");
6840            }
6841            if (grantUri == null) {
6842                throw new IllegalArgumentException("null uri");
6843            }
6844
6845            Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION
6846                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
6847                    | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
6848                    | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
6849
6850            grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null,
6851                    UserHandle.getUserId(r.uid));
6852        }
6853    }
6854
6855    void removeUriPermissionIfNeededLocked(UriPermission perm) {
6856        if (perm.modeFlags == 0) {
6857            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
6858                    perm.targetUid);
6859            if (perms != null) {
6860                if (DEBUG_URI_PERMISSION) Slog.v(TAG,
6861                        "Removing " + perm.targetUid + " permission to " + perm.uri);
6862
6863                perms.remove(perm.uri);
6864                if (perms.isEmpty()) {
6865                    mGrantedUriPermissions.remove(perm.targetUid);
6866                }
6867            }
6868        }
6869    }
6870
6871    private void revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags) {
6872        if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Revoking all granted permissions to " + grantUri);
6873
6874        final IPackageManager pm = AppGlobals.getPackageManager();
6875        final String authority = grantUri.uri.getAuthority();
6876        final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId);
6877        if (pi == null) {
6878            Slog.w(TAG, "No content provider found for permission revoke: "
6879                    + grantUri.toSafeString());
6880            return;
6881        }
6882
6883        // Does the caller have this permission on the URI?
6884        if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) {
6885            // Right now, if you are not the original owner of the permission,
6886            // you are not allowed to revoke it.
6887            //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
6888                throw new SecurityException("Uid " + callingUid
6889                        + " does not have permission to uri " + grantUri);
6890            //}
6891        }
6892
6893        boolean persistChanged = false;
6894
6895        // Go through all of the permissions and remove any that match.
6896        int N = mGrantedUriPermissions.size();
6897        for (int i = 0; i < N; i++) {
6898            final int targetUid = mGrantedUriPermissions.keyAt(i);
6899            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
6900
6901            for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
6902                final UriPermission perm = it.next();
6903                if (perm.uri.sourceUserId == grantUri.sourceUserId
6904                        && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) {
6905                    if (DEBUG_URI_PERMISSION)
6906                        Slog.v(TAG,
6907                                "Revoking " + perm.targetUid + " permission to " + perm.uri);
6908                    persistChanged |= perm.revokeModes(
6909                            modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
6910                    if (perm.modeFlags == 0) {
6911                        it.remove();
6912                    }
6913                }
6914            }
6915
6916            if (perms.isEmpty()) {
6917                mGrantedUriPermissions.remove(targetUid);
6918                N--;
6919                i--;
6920            }
6921        }
6922
6923        if (persistChanged) {
6924            schedulePersistUriGrants();
6925        }
6926    }
6927
6928    @Override
6929    public void revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags,
6930            int userId) {
6931        enforceNotIsolatedCaller("revokeUriPermission");
6932        synchronized(this) {
6933            final ProcessRecord r = getRecordForAppLocked(caller);
6934            if (r == null) {
6935                throw new SecurityException("Unable to find app for caller "
6936                        + caller
6937                        + " when revoking permission to uri " + uri);
6938            }
6939            if (uri == null) {
6940                Slog.w(TAG, "revokeUriPermission: null uri");
6941                return;
6942            }
6943
6944            if (!Intent.isAccessUriMode(modeFlags)) {
6945                return;
6946            }
6947
6948            final IPackageManager pm = AppGlobals.getPackageManager();
6949            final String authority = uri.getAuthority();
6950            final ProviderInfo pi = getProviderInfoLocked(authority, userId);
6951            if (pi == null) {
6952                Slog.w(TAG, "No content provider found for permission revoke: "
6953                        + uri.toSafeString());
6954                return;
6955            }
6956
6957            revokeUriPermissionLocked(r.uid, new GrantUri(userId, uri, false), modeFlags);
6958        }
6959    }
6960
6961    /**
6962     * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the
6963     * given package.
6964     *
6965     * @param packageName Package name to match, or {@code null} to apply to all
6966     *            packages.
6967     * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply
6968     *            to all users.
6969     * @param persistable If persistable grants should be removed.
6970     */
6971    private void removeUriPermissionsForPackageLocked(
6972            String packageName, int userHandle, boolean persistable) {
6973        if (userHandle == UserHandle.USER_ALL && packageName == null) {
6974            throw new IllegalArgumentException("Must narrow by either package or user");
6975        }
6976
6977        boolean persistChanged = false;
6978
6979        int N = mGrantedUriPermissions.size();
6980        for (int i = 0; i < N; i++) {
6981            final int targetUid = mGrantedUriPermissions.keyAt(i);
6982            final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
6983
6984            // Only inspect grants matching user
6985            if (userHandle == UserHandle.USER_ALL
6986                    || userHandle == UserHandle.getUserId(targetUid)) {
6987                for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) {
6988                    final UriPermission perm = it.next();
6989
6990                    // Only inspect grants matching package
6991                    if (packageName == null || perm.sourcePkg.equals(packageName)
6992                            || perm.targetPkg.equals(packageName)) {
6993                        persistChanged |= perm.revokeModes(
6994                                persistable ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
6995
6996                        // Only remove when no modes remain; any persisted grants
6997                        // will keep this alive.
6998                        if (perm.modeFlags == 0) {
6999                            it.remove();
7000                        }
7001                    }
7002                }
7003
7004                if (perms.isEmpty()) {
7005                    mGrantedUriPermissions.remove(targetUid);
7006                    N--;
7007                    i--;
7008                }
7009            }
7010        }
7011
7012        if (persistChanged) {
7013            schedulePersistUriGrants();
7014        }
7015    }
7016
7017    @Override
7018    public IBinder newUriPermissionOwner(String name) {
7019        enforceNotIsolatedCaller("newUriPermissionOwner");
7020        synchronized(this) {
7021            UriPermissionOwner owner = new UriPermissionOwner(this, name);
7022            return owner.getExternalTokenLocked();
7023        }
7024    }
7025
7026    @Override
7027    public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri,
7028            final int modeFlags, int sourceUserId, int targetUserId) {
7029        synchronized(this) {
7030            UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
7031            if (owner == null) {
7032                throw new IllegalArgumentException("Unknown owner: " + token);
7033            }
7034            if (fromUid != Binder.getCallingUid()) {
7035                if (Binder.getCallingUid() != Process.myUid()) {
7036                    // Only system code can grant URI permissions on behalf
7037                    // of other users.
7038                    throw new SecurityException("nice try");
7039                }
7040            }
7041            if (targetPkg == null) {
7042                throw new IllegalArgumentException("null target");
7043            }
7044            if (uri == null) {
7045                throw new IllegalArgumentException("null uri");
7046            }
7047
7048            grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false),
7049                    modeFlags, owner, targetUserId);
7050        }
7051    }
7052
7053    @Override
7054    public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) {
7055        synchronized(this) {
7056            UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
7057            if (owner == null) {
7058                throw new IllegalArgumentException("Unknown owner: " + token);
7059            }
7060
7061            if (uri == null) {
7062                owner.removeUriPermissionsLocked(mode);
7063            } else {
7064                owner.removeUriPermissionLocked(new GrantUri(userId, uri, false), mode);
7065            }
7066        }
7067    }
7068
7069    private void schedulePersistUriGrants() {
7070        if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) {
7071            mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG),
7072                    10 * DateUtils.SECOND_IN_MILLIS);
7073        }
7074    }
7075
7076    private void writeGrantedUriPermissions() {
7077        if (DEBUG_URI_PERMISSION) Slog.v(TAG, "writeGrantedUriPermissions()");
7078
7079        // Snapshot permissions so we can persist without lock
7080        ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList();
7081        synchronized (this) {
7082            final int size = mGrantedUriPermissions.size();
7083            for (int i = 0; i < size; i++) {
7084                final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
7085                for (UriPermission perm : perms.values()) {
7086                    if (perm.persistedModeFlags != 0) {
7087                        persist.add(perm.snapshot());
7088                    }
7089                }
7090            }
7091        }
7092
7093        FileOutputStream fos = null;
7094        try {
7095            fos = mGrantFile.startWrite();
7096
7097            XmlSerializer out = new FastXmlSerializer();
7098            out.setOutput(fos, "utf-8");
7099            out.startDocument(null, true);
7100            out.startTag(null, TAG_URI_GRANTS);
7101            for (UriPermission.Snapshot perm : persist) {
7102                out.startTag(null, TAG_URI_GRANT);
7103                writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId);
7104                writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId);
7105                out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg);
7106                out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg);
7107                out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri));
7108                writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix);
7109                writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags);
7110                writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime);
7111                out.endTag(null, TAG_URI_GRANT);
7112            }
7113            out.endTag(null, TAG_URI_GRANTS);
7114            out.endDocument();
7115
7116            mGrantFile.finishWrite(fos);
7117        } catch (IOException e) {
7118            if (fos != null) {
7119                mGrantFile.failWrite(fos);
7120            }
7121        }
7122    }
7123
7124    private void readGrantedUriPermissionsLocked() {
7125        if (DEBUG_URI_PERMISSION) Slog.v(TAG, "readGrantedUriPermissions()");
7126
7127        final long now = System.currentTimeMillis();
7128
7129        FileInputStream fis = null;
7130        try {
7131            fis = mGrantFile.openRead();
7132            final XmlPullParser in = Xml.newPullParser();
7133            in.setInput(fis, null);
7134
7135            int type;
7136            while ((type = in.next()) != END_DOCUMENT) {
7137                final String tag = in.getName();
7138                if (type == START_TAG) {
7139                    if (TAG_URI_GRANT.equals(tag)) {
7140                        final int sourceUserId;
7141                        final int targetUserId;
7142                        final int userHandle = readIntAttribute(in,
7143                                ATTR_USER_HANDLE, UserHandle.USER_NULL);
7144                        if (userHandle != UserHandle.USER_NULL) {
7145                            // For backwards compatibility.
7146                            sourceUserId = userHandle;
7147                            targetUserId = userHandle;
7148                        } else {
7149                            sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID);
7150                            targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID);
7151                        }
7152                        final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG);
7153                        final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG);
7154                        final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI));
7155                        final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX);
7156                        final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS);
7157                        final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now);
7158
7159                        // Sanity check that provider still belongs to source package
7160                        final ProviderInfo pi = getProviderInfoLocked(
7161                                uri.getAuthority(), sourceUserId);
7162                        if (pi != null && sourcePkg.equals(pi.packageName)) {
7163                            int targetUid = -1;
7164                            try {
7165                                targetUid = AppGlobals.getPackageManager()
7166                                        .getPackageUid(targetPkg, targetUserId);
7167                            } catch (RemoteException e) {
7168                            }
7169                            if (targetUid != -1) {
7170                                final UriPermission perm = findOrCreateUriPermissionLocked(
7171                                        sourcePkg, targetPkg, targetUid,
7172                                        new GrantUri(sourceUserId, uri, prefix));
7173                                perm.initPersistedModes(modeFlags, createdTime);
7174                            }
7175                        } else {
7176                            Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg
7177                                    + " but instead found " + pi);
7178                        }
7179                    }
7180                }
7181            }
7182        } catch (FileNotFoundException e) {
7183            // Missing grants is okay
7184        } catch (IOException e) {
7185            Log.wtf(TAG, "Failed reading Uri grants", e);
7186        } catch (XmlPullParserException e) {
7187            Log.wtf(TAG, "Failed reading Uri grants", e);
7188        } finally {
7189            IoUtils.closeQuietly(fis);
7190        }
7191    }
7192
7193    @Override
7194    public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
7195        enforceNotIsolatedCaller("takePersistableUriPermission");
7196
7197        Preconditions.checkFlagsArgument(modeFlags,
7198                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
7199
7200        synchronized (this) {
7201            final int callingUid = Binder.getCallingUid();
7202            boolean persistChanged = false;
7203            GrantUri grantUri = new GrantUri(userId, uri, false);
7204
7205            UriPermission exactPerm = findUriPermissionLocked(callingUid,
7206                    new GrantUri(userId, uri, false));
7207            UriPermission prefixPerm = findUriPermissionLocked(callingUid,
7208                    new GrantUri(userId, uri, true));
7209
7210            final boolean exactValid = (exactPerm != null)
7211                    && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags);
7212            final boolean prefixValid = (prefixPerm != null)
7213                    && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags);
7214
7215            if (!(exactValid || prefixValid)) {
7216                throw new SecurityException("No persistable permission grants found for UID "
7217                        + callingUid + " and Uri " + grantUri.toSafeString());
7218            }
7219
7220            if (exactValid) {
7221                persistChanged |= exactPerm.takePersistableModes(modeFlags);
7222            }
7223            if (prefixValid) {
7224                persistChanged |= prefixPerm.takePersistableModes(modeFlags);
7225            }
7226
7227            persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid);
7228
7229            if (persistChanged) {
7230                schedulePersistUriGrants();
7231            }
7232        }
7233    }
7234
7235    @Override
7236    public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) {
7237        enforceNotIsolatedCaller("releasePersistableUriPermission");
7238
7239        Preconditions.checkFlagsArgument(modeFlags,
7240                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
7241
7242        synchronized (this) {
7243            final int callingUid = Binder.getCallingUid();
7244            boolean persistChanged = false;
7245
7246            UriPermission exactPerm = findUriPermissionLocked(callingUid,
7247                    new GrantUri(userId, uri, false));
7248            UriPermission prefixPerm = findUriPermissionLocked(callingUid,
7249                    new GrantUri(userId, uri, true));
7250            if (exactPerm == null && prefixPerm == null) {
7251                throw new SecurityException("No permission grants found for UID " + callingUid
7252                        + " and Uri " + uri.toSafeString());
7253            }
7254
7255            if (exactPerm != null) {
7256                persistChanged |= exactPerm.releasePersistableModes(modeFlags);
7257                removeUriPermissionIfNeededLocked(exactPerm);
7258            }
7259            if (prefixPerm != null) {
7260                persistChanged |= prefixPerm.releasePersistableModes(modeFlags);
7261                removeUriPermissionIfNeededLocked(prefixPerm);
7262            }
7263
7264            if (persistChanged) {
7265                schedulePersistUriGrants();
7266            }
7267        }
7268    }
7269
7270    /**
7271     * Prune any older {@link UriPermission} for the given UID until outstanding
7272     * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}.
7273     *
7274     * @return if any mutations occured that require persisting.
7275     */
7276    private boolean maybePrunePersistedUriGrantsLocked(int uid) {
7277        final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid);
7278        if (perms == null) return false;
7279        if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false;
7280
7281        final ArrayList<UriPermission> persisted = Lists.newArrayList();
7282        for (UriPermission perm : perms.values()) {
7283            if (perm.persistedModeFlags != 0) {
7284                persisted.add(perm);
7285            }
7286        }
7287
7288        final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS;
7289        if (trimCount <= 0) return false;
7290
7291        Collections.sort(persisted, new UriPermission.PersistedTimeComparator());
7292        for (int i = 0; i < trimCount; i++) {
7293            final UriPermission perm = persisted.get(i);
7294
7295            if (DEBUG_URI_PERMISSION) {
7296                Slog.v(TAG, "Trimming grant created at " + perm.persistedCreateTime);
7297            }
7298
7299            perm.releasePersistableModes(~0);
7300            removeUriPermissionIfNeededLocked(perm);
7301        }
7302
7303        return true;
7304    }
7305
7306    @Override
7307    public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions(
7308            String packageName, boolean incoming) {
7309        enforceNotIsolatedCaller("getPersistedUriPermissions");
7310        Preconditions.checkNotNull(packageName, "packageName");
7311
7312        final int callingUid = Binder.getCallingUid();
7313        final IPackageManager pm = AppGlobals.getPackageManager();
7314        try {
7315            final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid));
7316            if (packageUid != callingUid) {
7317                throw new SecurityException(
7318                        "Package " + packageName + " does not belong to calling UID " + callingUid);
7319            }
7320        } catch (RemoteException e) {
7321            throw new SecurityException("Failed to verify package name ownership");
7322        }
7323
7324        final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
7325        synchronized (this) {
7326            if (incoming) {
7327                final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(
7328                        callingUid);
7329                if (perms == null) {
7330                    Slog.w(TAG, "No permission grants found for " + packageName);
7331                } else {
7332                    for (UriPermission perm : perms.values()) {
7333                        if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) {
7334                            result.add(perm.buildPersistedPublicApiObject());
7335                        }
7336                    }
7337                }
7338            } else {
7339                final int size = mGrantedUriPermissions.size();
7340                for (int i = 0; i < size; i++) {
7341                    final ArrayMap<GrantUri, UriPermission> perms =
7342                            mGrantedUriPermissions.valueAt(i);
7343                    for (UriPermission perm : perms.values()) {
7344                        if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) {
7345                            result.add(perm.buildPersistedPublicApiObject());
7346                        }
7347                    }
7348                }
7349            }
7350        }
7351        return new ParceledListSlice<android.content.UriPermission>(result);
7352    }
7353
7354    @Override
7355    public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
7356        synchronized (this) {
7357            ProcessRecord app =
7358                who != null ? getRecordForAppLocked(who) : null;
7359            if (app == null) return;
7360
7361            Message msg = Message.obtain();
7362            msg.what = WAIT_FOR_DEBUGGER_MSG;
7363            msg.obj = app;
7364            msg.arg1 = waiting ? 1 : 0;
7365            mHandler.sendMessage(msg);
7366        }
7367    }
7368
7369    @Override
7370    public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
7371        final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
7372        final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ);
7373        outInfo.availMem = Process.getFreeMemory();
7374        outInfo.totalMem = Process.getTotalMemory();
7375        outInfo.threshold = homeAppMem;
7376        outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2));
7377        outInfo.hiddenAppThreshold = cachedAppMem;
7378        outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
7379                ProcessList.SERVICE_ADJ);
7380        outInfo.visibleAppThreshold = mProcessList.getMemLevel(
7381                ProcessList.VISIBLE_APP_ADJ);
7382        outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
7383                ProcessList.FOREGROUND_APP_ADJ);
7384    }
7385
7386    // =========================================================
7387    // TASK MANAGEMENT
7388    // =========================================================
7389
7390    @Override
7391    public List<IAppTask> getAppTasks() {
7392        final PackageManager pm = mContext.getPackageManager();
7393        int callingUid = Binder.getCallingUid();
7394        long ident = Binder.clearCallingIdentity();
7395
7396        // Compose the list of packages for this id to test against
7397        HashSet<String> packages = new HashSet<String>();
7398        String[] uidPackages = pm.getPackagesForUid(callingUid);
7399        for (int i = 0; i < uidPackages.length; i++) {
7400            packages.add(uidPackages[i]);
7401        }
7402
7403        synchronized(this) {
7404            ArrayList<IAppTask> list = new ArrayList<IAppTask>();
7405            try {
7406                if (localLOGV) Slog.v(TAG, "getAppTasks");
7407
7408                final int N = mRecentTasks.size();
7409                for (int i = 0; i < N; i++) {
7410                    TaskRecord tr = mRecentTasks.get(i);
7411                    // Skip tasks that are not created by the caller
7412                    if (packages.contains(tr.getBaseIntent().getComponent().getPackageName())) {
7413                        ActivityManager.RecentTaskInfo taskInfo =
7414                                createRecentTaskInfoFromTaskRecord(tr);
7415                        AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid);
7416                        list.add(taskImpl);
7417                    }
7418                }
7419            } finally {
7420                Binder.restoreCallingIdentity(ident);
7421            }
7422            return list;
7423        }
7424    }
7425
7426    @Override
7427    public List<RunningTaskInfo> getTasks(int maxNum, int flags) {
7428        final int callingUid = Binder.getCallingUid();
7429        ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>();
7430
7431        synchronized(this) {
7432            if (localLOGV) Slog.v(
7433                TAG, "getTasks: max=" + maxNum + ", flags=" + flags);
7434
7435            final boolean allowed = checkCallingPermission(
7436                    android.Manifest.permission.GET_TASKS)
7437                    == PackageManager.PERMISSION_GRANTED;
7438            if (!allowed) {
7439                Slog.w(TAG, "getTasks: caller " + callingUid
7440                        + " does not hold GET_TASKS; limiting output");
7441            }
7442
7443            // TODO: Improve with MRU list from all ActivityStacks.
7444            mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed);
7445        }
7446
7447        return list;
7448    }
7449
7450    TaskRecord getMostRecentTask() {
7451        return mRecentTasks.get(0);
7452    }
7453
7454    /**
7455     * Creates a new RecentTaskInfo from a TaskRecord.
7456     */
7457    private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) {
7458        // Update the task description to reflect any changes in the task stack
7459        tr.updateTaskDescription();
7460
7461        // Compose the recent task info
7462        ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo();
7463        rti.id = tr.getTopActivity() == null ? -1 : tr.taskId;
7464        rti.persistentId = tr.taskId;
7465        rti.baseIntent = new Intent(tr.getBaseIntent());
7466        rti.origActivity = tr.origActivity;
7467        rti.description = tr.lastDescription;
7468        rti.stackId = tr.stack != null ? tr.stack.mStackId : -1;
7469        rti.userId = tr.userId;
7470        rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription);
7471        rti.firstActiveTime = tr.firstActiveTime;
7472        rti.lastActiveTime = tr.lastActiveTime;
7473        rti.affiliatedTaskId = tr.mAffiliatedTaskId;
7474        return rti;
7475    }
7476
7477    @Override
7478    public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) {
7479        final int callingUid = Binder.getCallingUid();
7480        userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
7481                false, ALLOW_FULL_ONLY, "getRecentTasks", null);
7482
7483        final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0;
7484        final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0;
7485        synchronized (this) {
7486            final boolean allowed = checkCallingPermission(android.Manifest.permission.GET_TASKS)
7487                    == PackageManager.PERMISSION_GRANTED;
7488            if (!allowed) {
7489                Slog.w(TAG, "getRecentTasks: caller " + callingUid
7490                        + " does not hold GET_TASKS; limiting output");
7491            }
7492            final boolean detailed = checkCallingPermission(
7493                    android.Manifest.permission.GET_DETAILED_TASKS)
7494                    == PackageManager.PERMISSION_GRANTED;
7495
7496            IPackageManager pm = AppGlobals.getPackageManager();
7497
7498            final int N = mRecentTasks.size();
7499            ArrayList<ActivityManager.RecentTaskInfo> res
7500                    = new ArrayList<ActivityManager.RecentTaskInfo>(
7501                            maxNum < N ? maxNum : N);
7502
7503            final Set<Integer> includedUsers;
7504            if (includeProfiles) {
7505                includedUsers = getProfileIdsLocked(userId);
7506            } else {
7507                includedUsers = new HashSet<Integer>();
7508            }
7509            includedUsers.add(Integer.valueOf(userId));
7510
7511            // Regroup affiliated tasks together.
7512            for (int i = 0; i < N; ) {
7513                TaskRecord task = mRecentTasks.remove(i);
7514                if (mTmpRecents.contains(task)) {
7515                    continue;
7516                }
7517                int affiliatedTaskId = task.mAffiliatedTaskId;
7518                while (true) {
7519                    TaskRecord next = task.mNextAffiliate;
7520                    if (next == null) {
7521                        break;
7522                    }
7523                    if (next.mAffiliatedTaskId != affiliatedTaskId) {
7524                        Slog.e(TAG, "Error in Recents: next.affiliatedTaskId=" +
7525                                next.mAffiliatedTaskId + " affiliatedTaskId=" + affiliatedTaskId);
7526                        task.setNextAffiliate(null);
7527                        if (next.mPrevAffiliate == task) {
7528                            next.setPrevAffiliate(null);
7529                        }
7530                        break;
7531                    }
7532                    if (next.mPrevAffiliate != task) {
7533                        Slog.e(TAG, "Error in Recents chain prev.mNextAffiliate=" +
7534                                next.mPrevAffiliate + " task=" + task);
7535                        next.setPrevAffiliate(null);
7536                        break;
7537                    }
7538                    if (!mRecentTasks.contains(next)) {
7539                        Slog.e(TAG, "Error in Recents: next=" + next + " not in mRecentTasks");
7540                        task.setNextAffiliate(null);
7541                        if (next.mPrevAffiliate == task) {
7542                            next.setPrevAffiliate(null);
7543                        }
7544                        break;
7545                    }
7546                    task = next;
7547                }
7548                // task is now the end of the list
7549                do {
7550                    mRecentTasks.remove(task);
7551                    mRecentTasks.add(i++, task);
7552                    mTmpRecents.add(task);
7553                } while ((task = task.mPrevAffiliate) != null);
7554            }
7555            mTmpRecents.clear();
7556            // mRecentTasks is now in sorted, affiliated order.
7557
7558            for (int i=0; i<N && maxNum > 0; i++) {
7559                TaskRecord tr = mRecentTasks.get(i);
7560                // Only add calling user or related users recent tasks
7561                if (!includedUsers.contains(Integer.valueOf(tr.userId))) continue;
7562
7563                // Return the entry if desired by the caller.  We always return
7564                // the first entry, because callers always expect this to be the
7565                // foreground app.  We may filter others if the caller has
7566                // not supplied RECENT_WITH_EXCLUDED and there is some reason
7567                // we should exclude the entry.
7568
7569                if (i == 0
7570                        || withExcluded
7571                        || (tr.intent == null)
7572                        || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
7573                                == 0)) {
7574                    if (!allowed) {
7575                        // If the caller doesn't have the GET_TASKS permission, then only
7576                        // allow them to see a small subset of tasks -- their own and home.
7577                        if (!tr.isHomeTask() && tr.creatorUid != callingUid) {
7578                            continue;
7579                        }
7580                    }
7581                    if (tr.autoRemoveRecents && tr.getTopActivity() == null) {
7582                        // Don't include auto remove tasks that are finished or finishing.
7583                        continue;
7584                    }
7585
7586                    ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr);
7587                    if (!detailed) {
7588                        rti.baseIntent.replaceExtras((Bundle)null);
7589                    }
7590
7591                    if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
7592                        // Check whether this activity is currently available.
7593                        try {
7594                            if (rti.origActivity != null) {
7595                                if (pm.getActivityInfo(rti.origActivity, 0, userId)
7596                                        == null) {
7597                                    continue;
7598                                }
7599                            } else if (rti.baseIntent != null) {
7600                                if (pm.queryIntentActivities(rti.baseIntent,
7601                                        null, 0, userId) == null) {
7602                                    continue;
7603                                }
7604                            }
7605                        } catch (RemoteException e) {
7606                            // Will never happen.
7607                        }
7608                    }
7609
7610                    res.add(rti);
7611                    maxNum--;
7612                }
7613            }
7614            return res;
7615        }
7616    }
7617
7618    private TaskRecord recentTaskForIdLocked(int id) {
7619        final int N = mRecentTasks.size();
7620            for (int i=0; i<N; i++) {
7621                TaskRecord tr = mRecentTasks.get(i);
7622                if (tr.taskId == id) {
7623                    return tr;
7624                }
7625            }
7626            return null;
7627    }
7628
7629    @Override
7630    public ActivityManager.TaskThumbnail getTaskThumbnail(int id) {
7631        synchronized (this) {
7632            enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
7633                    "getTaskThumbnail()");
7634            TaskRecord tr = recentTaskForIdLocked(id);
7635            if (tr != null) {
7636                return tr.getTaskThumbnailLocked();
7637            }
7638        }
7639        return null;
7640    }
7641
7642    @Override
7643    public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) {
7644        synchronized (this) {
7645            ActivityRecord r = ActivityRecord.isInStackLocked(token);
7646            if (r != null) {
7647                r.taskDescription = td;
7648                r.task.updateTaskDescription();
7649            }
7650        }
7651    }
7652
7653    private void killUnneededProcessLocked(ProcessRecord pr, String reason) {
7654        if (!pr.killedByAm) {
7655            Slog.i(TAG, "Killing " + pr.toShortString() + " (adj " + pr.setAdj + "): " + reason);
7656            EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
7657                    pr.processName, pr.setAdj, reason);
7658            pr.killedByAm = true;
7659            Process.killProcessQuiet(pr.pid);
7660            Process.killProcessGroup(pr.info.uid, pr.pid);
7661        }
7662    }
7663
7664    private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
7665        tr.disposeThumbnail();
7666        mRecentTasks.remove(tr);
7667        tr.closeRecentsChain();
7668        final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
7669        Intent baseIntent = new Intent(
7670                tr.intent != null ? tr.intent : tr.affinityIntent);
7671        ComponentName component = baseIntent.getComponent();
7672        if (component == null) {
7673            Slog.w(TAG, "Now component for base intent of task: " + tr);
7674            return;
7675        }
7676
7677        // Find any running services associated with this app.
7678        mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
7679
7680        if (killProcesses) {
7681            // Find any running processes associated with this app.
7682            final String pkg = component.getPackageName();
7683            ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
7684            ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
7685            for (int i=0; i<pmap.size(); i++) {
7686                SparseArray<ProcessRecord> uids = pmap.valueAt(i);
7687                for (int j=0; j<uids.size(); j++) {
7688                    ProcessRecord proc = uids.valueAt(j);
7689                    if (proc.userId != tr.userId) {
7690                        continue;
7691                    }
7692                    if (!proc.pkgList.containsKey(pkg)) {
7693                        continue;
7694                    }
7695                    procs.add(proc);
7696                }
7697            }
7698
7699            // Kill the running processes.
7700            for (int i=0; i<procs.size(); i++) {
7701                ProcessRecord pr = procs.get(i);
7702                if (pr == mHomeProcess) {
7703                    // Don't kill the home process along with tasks from the same package.
7704                    continue;
7705                }
7706                if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
7707                    killUnneededProcessLocked(pr, "remove task");
7708                } else {
7709                    pr.waitingToKill = "remove task";
7710                }
7711            }
7712        }
7713    }
7714
7715    /**
7716     * Removes the task with the specified task id.
7717     *
7718     * @param taskId Identifier of the task to be removed.
7719     * @param flags Additional operational flags.  May be 0 or
7720     * {@link ActivityManager#REMOVE_TASK_KILL_PROCESS}.
7721     * @return Returns true if the given task was found and removed.
7722     */
7723    private boolean removeTaskByIdLocked(int taskId, int flags) {
7724        TaskRecord tr = recentTaskForIdLocked(taskId);
7725        if (tr != null) {
7726            tr.removeTaskActivitiesLocked();
7727            cleanUpRemovedTaskLocked(tr, flags);
7728            if (tr.isPersistable) {
7729                notifyTaskPersisterLocked(null, true);
7730            }
7731            return true;
7732        }
7733        return false;
7734    }
7735
7736    @Override
7737    public boolean removeTask(int taskId, int flags) {
7738        synchronized (this) {
7739            enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
7740                    "removeTask()");
7741            long ident = Binder.clearCallingIdentity();
7742            try {
7743                return removeTaskByIdLocked(taskId, flags);
7744            } finally {
7745                Binder.restoreCallingIdentity(ident);
7746            }
7747        }
7748    }
7749
7750    /**
7751     * TODO: Add mController hook
7752     */
7753    @Override
7754    public void moveTaskToFront(int taskId, int flags, Bundle options) {
7755        enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7756                "moveTaskToFront()");
7757
7758        if (DEBUG_STACK) Slog.d(TAG, "moveTaskToFront: moving taskId=" + taskId);
7759        synchronized(this) {
7760            if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7761                    Binder.getCallingUid(), "Task to front")) {
7762                ActivityOptions.abort(options);
7763                return;
7764            }
7765            final long origId = Binder.clearCallingIdentity();
7766            try {
7767                final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId);
7768                if (task == null) {
7769                    return;
7770                }
7771                if (mStackSupervisor.isLockTaskModeViolation(task)) {
7772                    mStackSupervisor.showLockTaskToast();
7773                    Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode");
7774                    return;
7775                }
7776                final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked();
7777                if (prev != null && prev.isRecentsActivity()) {
7778                    task.setTaskToReturnTo(ActivityRecord.RECENTS_ACTIVITY_TYPE);
7779                }
7780                mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options);
7781            } finally {
7782                Binder.restoreCallingIdentity(origId);
7783            }
7784            ActivityOptions.abort(options);
7785        }
7786    }
7787
7788    @Override
7789    public void moveTaskToBack(int taskId) {
7790        enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7791                "moveTaskToBack()");
7792
7793        synchronized(this) {
7794            TaskRecord tr = recentTaskForIdLocked(taskId);
7795            if (tr != null) {
7796                if (DEBUG_STACK) Slog.d(TAG, "moveTaskToBack: moving task=" + tr);
7797                ActivityStack stack = tr.stack;
7798                if (stack.mResumedActivity != null && stack.mResumedActivity.task == tr) {
7799                    if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7800                            Binder.getCallingUid(), "Task to back")) {
7801                        return;
7802                    }
7803                }
7804                final long origId = Binder.clearCallingIdentity();
7805                try {
7806                    stack.moveTaskToBackLocked(taskId, null);
7807                } finally {
7808                    Binder.restoreCallingIdentity(origId);
7809                }
7810            }
7811        }
7812    }
7813
7814    /**
7815     * Moves an activity, and all of the other activities within the same task, to the bottom
7816     * of the history stack.  The activity's order within the task is unchanged.
7817     *
7818     * @param token A reference to the activity we wish to move
7819     * @param nonRoot If false then this only works if the activity is the root
7820     *                of a task; if true it will work for any activity in a task.
7821     * @return Returns true if the move completed, false if not.
7822     */
7823    @Override
7824    public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
7825        enforceNotIsolatedCaller("moveActivityTaskToBack");
7826        synchronized(this) {
7827            final long origId = Binder.clearCallingIdentity();
7828            int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot);
7829            if (taskId >= 0) {
7830                return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId, null);
7831            }
7832            Binder.restoreCallingIdentity(origId);
7833        }
7834        return false;
7835    }
7836
7837    @Override
7838    public void moveTaskBackwards(int task) {
7839        enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
7840                "moveTaskBackwards()");
7841
7842        synchronized(this) {
7843            if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
7844                    Binder.getCallingUid(), "Task backwards")) {
7845                return;
7846            }
7847            final long origId = Binder.clearCallingIdentity();
7848            moveTaskBackwardsLocked(task);
7849            Binder.restoreCallingIdentity(origId);
7850        }
7851    }
7852
7853    private final void moveTaskBackwardsLocked(int task) {
7854        Slog.e(TAG, "moveTaskBackwards not yet implemented!");
7855    }
7856
7857    @Override
7858    public IBinder getHomeActivityToken() throws RemoteException {
7859        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7860                "getHomeActivityToken()");
7861        synchronized (this) {
7862            return mStackSupervisor.getHomeActivityToken();
7863        }
7864    }
7865
7866    @Override
7867    public IActivityContainer createActivityContainer(IBinder parentActivityToken,
7868            IActivityContainerCallback callback) throws RemoteException {
7869        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7870                "createActivityContainer()");
7871        synchronized (this) {
7872            if (parentActivityToken == null) {
7873                throw new IllegalArgumentException("parent token must not be null");
7874            }
7875            ActivityRecord r = ActivityRecord.forToken(parentActivityToken);
7876            if (r == null) {
7877                return null;
7878            }
7879            if (callback == null) {
7880                throw new IllegalArgumentException("callback must not be null");
7881            }
7882            return mStackSupervisor.createActivityContainer(r, callback);
7883        }
7884    }
7885
7886    @Override
7887    public void deleteActivityContainer(IActivityContainer container) throws RemoteException {
7888        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7889                "deleteActivityContainer()");
7890        synchronized (this) {
7891            mStackSupervisor.deleteActivityContainer(container);
7892        }
7893    }
7894
7895    @Override
7896    public IActivityContainer getEnclosingActivityContainer(IBinder activityToken)
7897            throws RemoteException {
7898        synchronized (this) {
7899            ActivityStack stack = ActivityRecord.getStackLocked(activityToken);
7900            if (stack != null) {
7901                return stack.mActivityContainer;
7902            }
7903            return null;
7904        }
7905    }
7906
7907    @Override
7908    public void moveTaskToStack(int taskId, int stackId, boolean toTop) {
7909        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7910                "moveTaskToStack()");
7911        if (stackId == HOME_STACK_ID) {
7912            Slog.e(TAG, "moveTaskToStack: Attempt to move task " + taskId + " to home stack",
7913                    new RuntimeException("here").fillInStackTrace());
7914        }
7915        synchronized (this) {
7916            long ident = Binder.clearCallingIdentity();
7917            try {
7918                if (DEBUG_STACK) Slog.d(TAG, "moveTaskToStack: moving task=" + taskId + " to stackId="
7919                        + stackId + " toTop=" + toTop);
7920                mStackSupervisor.moveTaskToStack(taskId, stackId, toTop);
7921            } finally {
7922                Binder.restoreCallingIdentity(ident);
7923            }
7924        }
7925    }
7926
7927    @Override
7928    public void resizeStack(int stackBoxId, Rect bounds) {
7929        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7930                "resizeStackBox()");
7931        long ident = Binder.clearCallingIdentity();
7932        try {
7933            mWindowManager.resizeStack(stackBoxId, bounds);
7934        } finally {
7935            Binder.restoreCallingIdentity(ident);
7936        }
7937    }
7938
7939    @Override
7940    public List<StackInfo> getAllStackInfos() {
7941        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7942                "getAllStackInfos()");
7943        long ident = Binder.clearCallingIdentity();
7944        try {
7945            synchronized (this) {
7946                return mStackSupervisor.getAllStackInfosLocked();
7947            }
7948        } finally {
7949            Binder.restoreCallingIdentity(ident);
7950        }
7951    }
7952
7953    @Override
7954    public StackInfo getStackInfo(int stackId) {
7955        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7956                "getStackInfo()");
7957        long ident = Binder.clearCallingIdentity();
7958        try {
7959            synchronized (this) {
7960                return mStackSupervisor.getStackInfoLocked(stackId);
7961            }
7962        } finally {
7963            Binder.restoreCallingIdentity(ident);
7964        }
7965    }
7966
7967    @Override
7968    public boolean isInHomeStack(int taskId) {
7969        enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
7970                "getStackInfo()");
7971        long ident = Binder.clearCallingIdentity();
7972        try {
7973            synchronized (this) {
7974                TaskRecord tr = recentTaskForIdLocked(taskId);
7975                return tr != null && tr.stack != null && tr.stack.isHomeStack();
7976            }
7977        } finally {
7978            Binder.restoreCallingIdentity(ident);
7979        }
7980    }
7981
7982    @Override
7983    public int getTaskForActivity(IBinder token, boolean onlyRoot) {
7984        synchronized(this) {
7985            return ActivityRecord.getTaskForActivityLocked(token, onlyRoot);
7986        }
7987    }
7988
7989    private boolean isLockTaskAuthorized(String pkg) {
7990        final DevicePolicyManager dpm = (DevicePolicyManager)
7991                mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
7992        try {
7993            int uid = mContext.getPackageManager().getPackageUid(pkg,
7994                    Binder.getCallingUserHandle().getIdentifier());
7995            return (uid == Binder.getCallingUid()) && dpm != null && dpm.isLockTaskPermitted(pkg);
7996        } catch (NameNotFoundException e) {
7997            return false;
7998        }
7999    }
8000
8001    void startLockTaskMode(TaskRecord task) {
8002        final String pkg;
8003        synchronized (this) {
8004            pkg = task.intent.getComponent().getPackageName();
8005        }
8006        boolean isSystemInitiated = Binder.getCallingUid() == Process.SYSTEM_UID;
8007        if (!isSystemInitiated && !isLockTaskAuthorized(pkg)) {
8008            final TaskRecord taskRecord = task;
8009            mHandler.post(new Runnable() {
8010                @Override
8011                public void run() {
8012                    mLockToAppRequest.showLockTaskPrompt(taskRecord);
8013                }
8014            });
8015            return;
8016        }
8017        long ident = Binder.clearCallingIdentity();
8018        try {
8019            synchronized (this) {
8020                // Since we lost lock on task, make sure it is still there.
8021                task = mStackSupervisor.anyTaskForIdLocked(task.taskId);
8022                if (task != null) {
8023                    if (!isSystemInitiated
8024                            && ((mFocusedActivity == null) || (task != mFocusedActivity.task))) {
8025                        throw new IllegalArgumentException("Invalid task, not in foreground");
8026                    }
8027                    mStackSupervisor.setLockTaskModeLocked(task, !isSystemInitiated);
8028                }
8029            }
8030        } finally {
8031            Binder.restoreCallingIdentity(ident);
8032        }
8033    }
8034
8035    @Override
8036    public void startLockTaskMode(int taskId) {
8037        final TaskRecord task;
8038        long ident = Binder.clearCallingIdentity();
8039        try {
8040            synchronized (this) {
8041                task = mStackSupervisor.anyTaskForIdLocked(taskId);
8042            }
8043        } finally {
8044            Binder.restoreCallingIdentity(ident);
8045        }
8046        if (task != null) {
8047            startLockTaskMode(task);
8048        }
8049    }
8050
8051    @Override
8052    public void startLockTaskMode(IBinder token) {
8053        final TaskRecord task;
8054        long ident = Binder.clearCallingIdentity();
8055        try {
8056            synchronized (this) {
8057                final ActivityRecord r = ActivityRecord.forToken(token);
8058                if (r == null) {
8059                    return;
8060                }
8061                task = r.task;
8062            }
8063        } finally {
8064            Binder.restoreCallingIdentity(ident);
8065        }
8066        if (task != null) {
8067            startLockTaskMode(task);
8068        }
8069    }
8070
8071    @Override
8072    public void startLockTaskModeOnCurrent() throws RemoteException {
8073        checkCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS);
8074        ActivityRecord r = null;
8075        synchronized (this) {
8076            r = mStackSupervisor.topRunningActivityLocked();
8077        }
8078        startLockTaskMode(r.task);
8079    }
8080
8081    @Override
8082    public void stopLockTaskMode() {
8083        // Verify that the user matches the package of the intent for the TaskRecord
8084        // we are locked to or systtem.  This will ensure the same caller for startLockTaskMode
8085        // and stopLockTaskMode.
8086        final int callingUid = Binder.getCallingUid();
8087        if (callingUid != Process.SYSTEM_UID) {
8088            try {
8089                String pkg =
8090                        mStackSupervisor.mLockTaskModeTask.intent.getComponent().getPackageName();
8091                int uid = mContext.getPackageManager().getPackageUid(pkg,
8092                        Binder.getCallingUserHandle().getIdentifier());
8093                if (uid != callingUid) {
8094                    throw new SecurityException("Invalid uid, expected " + uid);
8095                }
8096            } catch (NameNotFoundException e) {
8097                Log.d(TAG, "stopLockTaskMode " + e);
8098                return;
8099            }
8100        }
8101        long ident = Binder.clearCallingIdentity();
8102        try {
8103            Log.d(TAG, "stopLockTaskMode");
8104            // Stop lock task
8105            synchronized (this) {
8106                mStackSupervisor.setLockTaskModeLocked(null, false);
8107            }
8108        } finally {
8109            Binder.restoreCallingIdentity(ident);
8110        }
8111    }
8112
8113    @Override
8114    public void stopLockTaskModeOnCurrent() throws RemoteException {
8115        checkCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS);
8116        long ident = Binder.clearCallingIdentity();
8117        try {
8118            stopLockTaskMode();
8119        } finally {
8120            Binder.restoreCallingIdentity(ident);
8121        }
8122    }
8123
8124    @Override
8125    public boolean isInLockTaskMode() {
8126        synchronized (this) {
8127            return mStackSupervisor.isInLockTaskMode();
8128        }
8129    }
8130
8131    // =========================================================
8132    // CONTENT PROVIDERS
8133    // =========================================================
8134
8135    private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
8136        List<ProviderInfo> providers = null;
8137        try {
8138            providers = AppGlobals.getPackageManager().
8139                queryContentProviders(app.processName, app.uid,
8140                        STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
8141        } catch (RemoteException ex) {
8142        }
8143        if (DEBUG_MU)
8144            Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
8145        int userId = app.userId;
8146        if (providers != null) {
8147            int N = providers.size();
8148            app.pubProviders.ensureCapacity(N + app.pubProviders.size());
8149            for (int i=0; i<N; i++) {
8150                ProviderInfo cpi =
8151                    (ProviderInfo)providers.get(i);
8152                boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
8153                        cpi.name, cpi.flags);
8154                if (singleton && UserHandle.getUserId(app.uid) != 0) {
8155                    // This is a singleton provider, but a user besides the
8156                    // default user is asking to initialize a process it runs
8157                    // in...  well, no, it doesn't actually run in this process,
8158                    // it runs in the process of the default user.  Get rid of it.
8159                    providers.remove(i);
8160                    N--;
8161                    i--;
8162                    continue;
8163                }
8164
8165                ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
8166                ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
8167                if (cpr == null) {
8168                    cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
8169                    mProviderMap.putProviderByClass(comp, cpr);
8170                }
8171                if (DEBUG_MU)
8172                    Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
8173                app.pubProviders.put(cpi.name, cpr);
8174                if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
8175                    // Don't add this if it is a platform component that is marked
8176                    // to run in multiple processes, because this is actually
8177                    // part of the framework so doesn't make sense to track as a
8178                    // separate apk in the process.
8179                    app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode,
8180                            mProcessStats);
8181                }
8182                ensurePackageDexOpt(cpi.applicationInfo.packageName);
8183            }
8184        }
8185        return providers;
8186    }
8187
8188    /**
8189     * Check if {@link ProcessRecord} has a possible chance at accessing the
8190     * given {@link ProviderInfo}. Final permission checking is always done
8191     * in {@link ContentProvider}.
8192     */
8193    private final String checkContentProviderPermissionLocked(
8194            ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) {
8195        final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
8196        final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
8197        boolean checkedGrants = false;
8198        if (checkUser) {
8199            // Looking for cross-user grants before enforcing the typical cross-users permissions
8200            int tmpTargetUserId = unsafeConvertIncomingUser(userId);
8201            if (tmpTargetUserId != UserHandle.getUserId(callingUid)) {
8202                if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) {
8203                    return null;
8204                }
8205                checkedGrants = true;
8206            }
8207            userId = handleIncomingUser(callingPid, callingUid, userId,
8208                    false, ALLOW_NON_FULL,
8209                    "checkContentProviderPermissionLocked " + cpi.authority, null);
8210            if (userId != tmpTargetUserId) {
8211                // When we actually went to determine the final targer user ID, this ended
8212                // up different than our initial check for the authority.  This is because
8213                // they had asked for USER_CURRENT_OR_SELF and we ended up switching to
8214                // SELF.  So we need to re-check the grants again.
8215                checkedGrants = false;
8216            }
8217        }
8218        if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
8219                cpi.applicationInfo.uid, cpi.exported)
8220                == PackageManager.PERMISSION_GRANTED) {
8221            return null;
8222        }
8223        if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
8224                cpi.applicationInfo.uid, cpi.exported)
8225                == PackageManager.PERMISSION_GRANTED) {
8226            return null;
8227        }
8228
8229        PathPermission[] pps = cpi.pathPermissions;
8230        if (pps != null) {
8231            int i = pps.length;
8232            while (i > 0) {
8233                i--;
8234                PathPermission pp = pps[i];
8235                String pprperm = pp.getReadPermission();
8236                if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid,
8237                        cpi.applicationInfo.uid, cpi.exported)
8238                        == PackageManager.PERMISSION_GRANTED) {
8239                    return null;
8240                }
8241                String ppwperm = pp.getWritePermission();
8242                if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid,
8243                        cpi.applicationInfo.uid, cpi.exported)
8244                        == PackageManager.PERMISSION_GRANTED) {
8245                    return null;
8246                }
8247            }
8248        }
8249        if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) {
8250            return null;
8251        }
8252
8253        String msg;
8254        if (!cpi.exported) {
8255            msg = "Permission Denial: opening provider " + cpi.name
8256                    + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
8257                    + ", uid=" + callingUid + ") that is not exported from uid "
8258                    + cpi.applicationInfo.uid;
8259        } else {
8260            msg = "Permission Denial: opening provider " + cpi.name
8261                    + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
8262                    + ", uid=" + callingUid + ") requires "
8263                    + cpi.readPermission + " or " + cpi.writePermission;
8264        }
8265        Slog.w(TAG, msg);
8266        return msg;
8267    }
8268
8269    /**
8270     * Returns if the ContentProvider has granted a uri to callingUid
8271     */
8272    boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) {
8273        final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
8274        if (perms != null) {
8275            for (int i=perms.size()-1; i>=0; i--) {
8276                GrantUri grantUri = perms.keyAt(i);
8277                if (grantUri.sourceUserId == userId || !checkUser) {
8278                    if (matchesProvider(grantUri.uri, cpi)) {
8279                        return true;
8280                    }
8281                }
8282            }
8283        }
8284        return false;
8285    }
8286
8287    /**
8288     * Returns true if the uri authority is one of the authorities specified in the provider.
8289     */
8290    boolean matchesProvider(Uri uri, ProviderInfo cpi) {
8291        String uriAuth = uri.getAuthority();
8292        String cpiAuth = cpi.authority;
8293        if (cpiAuth.indexOf(';') == -1) {
8294            return cpiAuth.equals(uriAuth);
8295        }
8296        String[] cpiAuths = cpiAuth.split(";");
8297        int length = cpiAuths.length;
8298        for (int i = 0; i < length; i++) {
8299            if (cpiAuths[i].equals(uriAuth)) return true;
8300        }
8301        return false;
8302    }
8303
8304    ContentProviderConnection incProviderCountLocked(ProcessRecord r,
8305            final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
8306        if (r != null) {
8307            for (int i=0; i<r.conProviders.size(); i++) {
8308                ContentProviderConnection conn = r.conProviders.get(i);
8309                if (conn.provider == cpr) {
8310                    if (DEBUG_PROVIDER) Slog.v(TAG,
8311                            "Adding provider requested by "
8312                            + r.processName + " from process "
8313                            + cpr.info.processName + ": " + cpr.name.flattenToShortString()
8314                            + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
8315                    if (stable) {
8316                        conn.stableCount++;
8317                        conn.numStableIncs++;
8318                    } else {
8319                        conn.unstableCount++;
8320                        conn.numUnstableIncs++;
8321                    }
8322                    return conn;
8323                }
8324            }
8325            ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
8326            if (stable) {
8327                conn.stableCount = 1;
8328                conn.numStableIncs = 1;
8329            } else {
8330                conn.unstableCount = 1;
8331                conn.numUnstableIncs = 1;
8332            }
8333            cpr.connections.add(conn);
8334            r.conProviders.add(conn);
8335            return conn;
8336        }
8337        cpr.addExternalProcessHandleLocked(externalProcessToken);
8338        return null;
8339    }
8340
8341    boolean decProviderCountLocked(ContentProviderConnection conn,
8342            ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
8343        if (conn != null) {
8344            cpr = conn.provider;
8345            if (DEBUG_PROVIDER) Slog.v(TAG,
8346                    "Removing provider requested by "
8347                    + conn.client.processName + " from process "
8348                    + cpr.info.processName + ": " + cpr.name.flattenToShortString()
8349                    + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
8350            if (stable) {
8351                conn.stableCount--;
8352            } else {
8353                conn.unstableCount--;
8354            }
8355            if (conn.stableCount == 0 && conn.unstableCount == 0) {
8356                cpr.connections.remove(conn);
8357                conn.client.conProviders.remove(conn);
8358                return true;
8359            }
8360            return false;
8361        }
8362        cpr.removeExternalProcessHandleLocked(externalProcessToken);
8363        return false;
8364    }
8365
8366    private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
8367            String name, IBinder token, boolean stable, int userId) {
8368        ContentProviderRecord cpr;
8369        ContentProviderConnection conn = null;
8370        ProviderInfo cpi = null;
8371
8372        synchronized(this) {
8373            ProcessRecord r = null;
8374            if (caller != null) {
8375                r = getRecordForAppLocked(caller);
8376                if (r == null) {
8377                    throw new SecurityException(
8378                            "Unable to find app for caller " + caller
8379                          + " (pid=" + Binder.getCallingPid()
8380                          + ") when getting content provider " + name);
8381                }
8382            }
8383
8384            boolean checkCrossUser = true;
8385
8386            // First check if this content provider has been published...
8387            cpr = mProviderMap.getProviderByName(name, userId);
8388            // If that didn't work, check if it exists for user 0 and then
8389            // verify that it's a singleton provider before using it.
8390            if (cpr == null && userId != UserHandle.USER_OWNER) {
8391                cpr = mProviderMap.getProviderByName(name, UserHandle.USER_OWNER);
8392                if (cpr != null) {
8393                    cpi = cpr.info;
8394                    if (isSingleton(cpi.processName, cpi.applicationInfo,
8395                            cpi.name, cpi.flags)
8396                            && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) {
8397                        userId = UserHandle.USER_OWNER;
8398                        checkCrossUser = false;
8399                    } else {
8400                        cpr = null;
8401                        cpi = null;
8402                    }
8403                }
8404            }
8405
8406            boolean providerRunning = cpr != null;
8407            if (providerRunning) {
8408                cpi = cpr.info;
8409                String msg;
8410                if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser))
8411                        != null) {
8412                    throw new SecurityException(msg);
8413                }
8414
8415                if (r != null && cpr.canRunHere(r)) {
8416                    // This provider has been published or is in the process
8417                    // of being published...  but it is also allowed to run
8418                    // in the caller's process, so don't make a connection
8419                    // and just let the caller instantiate its own instance.
8420                    ContentProviderHolder holder = cpr.newHolder(null);
8421                    // don't give caller the provider object, it needs
8422                    // to make its own.
8423                    holder.provider = null;
8424                    return holder;
8425                }
8426
8427                final long origId = Binder.clearCallingIdentity();
8428
8429                // In this case the provider instance already exists, so we can
8430                // return it right away.
8431                conn = incProviderCountLocked(r, cpr, token, stable);
8432                if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
8433                    if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
8434                        // If this is a perceptible app accessing the provider,
8435                        // make sure to count it as being accessed and thus
8436                        // back up on the LRU list.  This is good because
8437                        // content providers are often expensive to start.
8438                        updateLruProcessLocked(cpr.proc, false, null);
8439                    }
8440                }
8441
8442                if (cpr.proc != null) {
8443                    if (false) {
8444                        if (cpr.name.flattenToShortString().equals(
8445                                "com.android.providers.calendar/.CalendarProvider2")) {
8446                            Slog.v(TAG, "****************** KILLING "
8447                                + cpr.name.flattenToShortString());
8448                            Process.killProcess(cpr.proc.pid);
8449                        }
8450                    }
8451                    boolean success = updateOomAdjLocked(cpr.proc);
8452                    if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
8453                    // NOTE: there is still a race here where a signal could be
8454                    // pending on the process even though we managed to update its
8455                    // adj level.  Not sure what to do about this, but at least
8456                    // the race is now smaller.
8457                    if (!success) {
8458                        // Uh oh...  it looks like the provider's process
8459                        // has been killed on us.  We need to wait for a new
8460                        // process to be started, and make sure its death
8461                        // doesn't kill our process.
8462                        Slog.i(TAG,
8463                                "Existing provider " + cpr.name.flattenToShortString()
8464                                + " is crashing; detaching " + r);
8465                        boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
8466                        appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
8467                        if (!lastRef) {
8468                            // This wasn't the last ref our process had on
8469                            // the provider...  we have now been killed, bail.
8470                            return null;
8471                        }
8472                        providerRunning = false;
8473                        conn = null;
8474                    }
8475                }
8476
8477                Binder.restoreCallingIdentity(origId);
8478            }
8479
8480            boolean singleton;
8481            if (!providerRunning) {
8482                try {
8483                    cpi = AppGlobals.getPackageManager().
8484                        resolveContentProvider(name,
8485                            STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
8486                } catch (RemoteException ex) {
8487                }
8488                if (cpi == null) {
8489                    return null;
8490                }
8491                // If the provider is a singleton AND
8492                // (it's a call within the same user || the provider is a
8493                // privileged app)
8494                // Then allow connecting to the singleton provider
8495                singleton = isSingleton(cpi.processName, cpi.applicationInfo,
8496                        cpi.name, cpi.flags)
8497                        && isValidSingletonCall(r.uid, cpi.applicationInfo.uid);
8498                if (singleton) {
8499                    userId = UserHandle.USER_OWNER;
8500                }
8501                cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
8502
8503                String msg;
8504                if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton))
8505                        != null) {
8506                    throw new SecurityException(msg);
8507                }
8508
8509                if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
8510                        && !cpi.processName.equals("system")) {
8511                    // If this content provider does not run in the system
8512                    // process, and the system is not yet ready to run other
8513                    // processes, then fail fast instead of hanging.
8514                    throw new IllegalArgumentException(
8515                            "Attempt to launch content provider before system ready");
8516                }
8517
8518                // Make sure that the user who owns this provider is started.  If not,
8519                // we don't want to allow it to run.
8520                if (mStartedUsers.get(userId) == null) {
8521                    Slog.w(TAG, "Unable to launch app "
8522                            + cpi.applicationInfo.packageName + "/"
8523                            + cpi.applicationInfo.uid + " for provider "
8524                            + name + ": user " + userId + " is stopped");
8525                    return null;
8526                }
8527
8528                ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
8529                cpr = mProviderMap.getProviderByClass(comp, userId);
8530                final boolean firstClass = cpr == null;
8531                if (firstClass) {
8532                    try {
8533                        ApplicationInfo ai =
8534                            AppGlobals.getPackageManager().
8535                                getApplicationInfo(
8536                                        cpi.applicationInfo.packageName,
8537                                        STOCK_PM_FLAGS, userId);
8538                        if (ai == null) {
8539                            Slog.w(TAG, "No package info for content provider "
8540                                    + cpi.name);
8541                            return null;
8542                        }
8543                        ai = getAppInfoForUser(ai, userId);
8544                        cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
8545                    } catch (RemoteException ex) {
8546                        // pm is in same process, this will never happen.
8547                    }
8548                }
8549
8550                if (r != null && cpr.canRunHere(r)) {
8551                    // If this is a multiprocess provider, then just return its
8552                    // info and allow the caller to instantiate it.  Only do
8553                    // this if the provider is the same user as the caller's
8554                    // process, or can run as root (so can be in any process).
8555                    return cpr.newHolder(null);
8556                }
8557
8558                if (DEBUG_PROVIDER) {
8559                    RuntimeException e = new RuntimeException("here");
8560                    Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + (r != null ? r.uid : null)
8561                          + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
8562                }
8563
8564                // This is single process, and our app is now connecting to it.
8565                // See if we are already in the process of launching this
8566                // provider.
8567                final int N = mLaunchingProviders.size();
8568                int i;
8569                for (i=0; i<N; i++) {
8570                    if (mLaunchingProviders.get(i) == cpr) {
8571                        break;
8572                    }
8573                }
8574
8575                // If the provider is not already being launched, then get it
8576                // started.
8577                if (i >= N) {
8578                    final long origId = Binder.clearCallingIdentity();
8579
8580                    try {
8581                        // Content provider is now in use, its package can't be stopped.
8582                        try {
8583                            AppGlobals.getPackageManager().setPackageStoppedState(
8584                                    cpr.appInfo.packageName, false, userId);
8585                        } catch (RemoteException e) {
8586                        } catch (IllegalArgumentException e) {
8587                            Slog.w(TAG, "Failed trying to unstop package "
8588                                    + cpr.appInfo.packageName + ": " + e);
8589                        }
8590
8591                        // Use existing process if already started
8592                        ProcessRecord proc = getProcessRecordLocked(
8593                                cpi.processName, cpr.appInfo.uid, false);
8594                        if (proc != null && proc.thread != null) {
8595                            if (DEBUG_PROVIDER) {
8596                                Slog.d(TAG, "Installing in existing process " + proc);
8597                            }
8598                            proc.pubProviders.put(cpi.name, cpr);
8599                            try {
8600                                proc.thread.scheduleInstallProvider(cpi);
8601                            } catch (RemoteException e) {
8602                            }
8603                        } else {
8604                            proc = startProcessLocked(cpi.processName,
8605                                    cpr.appInfo, false, 0, "content provider",
8606                                    new ComponentName(cpi.applicationInfo.packageName,
8607                                            cpi.name), false, false, false);
8608                            if (proc == null) {
8609                                Slog.w(TAG, "Unable to launch app "
8610                                        + cpi.applicationInfo.packageName + "/"
8611                                        + cpi.applicationInfo.uid + " for provider "
8612                                        + name + ": process is bad");
8613                                return null;
8614                            }
8615                        }
8616                        cpr.launchingApp = proc;
8617                        mLaunchingProviders.add(cpr);
8618                    } finally {
8619                        Binder.restoreCallingIdentity(origId);
8620                    }
8621                }
8622
8623                // Make sure the provider is published (the same provider class
8624                // may be published under multiple names).
8625                if (firstClass) {
8626                    mProviderMap.putProviderByClass(comp, cpr);
8627                }
8628
8629                mProviderMap.putProviderByName(name, cpr);
8630                conn = incProviderCountLocked(r, cpr, token, stable);
8631                if (conn != null) {
8632                    conn.waiting = true;
8633                }
8634            }
8635        }
8636
8637        // Wait for the provider to be published...
8638        synchronized (cpr) {
8639            while (cpr.provider == null) {
8640                if (cpr.launchingApp == null) {
8641                    Slog.w(TAG, "Unable to launch app "
8642                            + cpi.applicationInfo.packageName + "/"
8643                            + cpi.applicationInfo.uid + " for provider "
8644                            + name + ": launching app became null");
8645                    EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
8646                            UserHandle.getUserId(cpi.applicationInfo.uid),
8647                            cpi.applicationInfo.packageName,
8648                            cpi.applicationInfo.uid, name);
8649                    return null;
8650                }
8651                try {
8652                    if (DEBUG_MU) {
8653                        Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
8654                                + cpr.launchingApp);
8655                    }
8656                    if (conn != null) {
8657                        conn.waiting = true;
8658                    }
8659                    cpr.wait();
8660                } catch (InterruptedException ex) {
8661                } finally {
8662                    if (conn != null) {
8663                        conn.waiting = false;
8664                    }
8665                }
8666            }
8667        }
8668        return cpr != null ? cpr.newHolder(conn) : null;
8669    }
8670
8671    @Override
8672    public final ContentProviderHolder getContentProvider(
8673            IApplicationThread caller, String name, int userId, boolean stable) {
8674        enforceNotIsolatedCaller("getContentProvider");
8675        if (caller == null) {
8676            String msg = "null IApplicationThread when getting content provider "
8677                    + name;
8678            Slog.w(TAG, msg);
8679            throw new SecurityException(msg);
8680        }
8681        // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal
8682        // with cross-user grant.
8683        return getContentProviderImpl(caller, name, null, stable, userId);
8684    }
8685
8686    public ContentProviderHolder getContentProviderExternal(
8687            String name, int userId, IBinder token) {
8688        enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
8689            "Do not have permission in call getContentProviderExternal()");
8690        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
8691                false, ALLOW_FULL_ONLY, "getContentProvider", null);
8692        return getContentProviderExternalUnchecked(name, token, userId);
8693    }
8694
8695    private ContentProviderHolder getContentProviderExternalUnchecked(String name,
8696            IBinder token, int userId) {
8697        return getContentProviderImpl(null, name, token, true, userId);
8698    }
8699
8700    /**
8701     * Drop a content provider from a ProcessRecord's bookkeeping
8702     */
8703    public void removeContentProvider(IBinder connection, boolean stable) {
8704        enforceNotIsolatedCaller("removeContentProvider");
8705        long ident = Binder.clearCallingIdentity();
8706        try {
8707            synchronized (this) {
8708                ContentProviderConnection conn;
8709                try {
8710                    conn = (ContentProviderConnection)connection;
8711                } catch (ClassCastException e) {
8712                    String msg ="removeContentProvider: " + connection
8713                            + " not a ContentProviderConnection";
8714                    Slog.w(TAG, msg);
8715                    throw new IllegalArgumentException(msg);
8716                }
8717                if (conn == null) {
8718                    throw new NullPointerException("connection is null");
8719                }
8720                if (decProviderCountLocked(conn, null, null, stable)) {
8721                    updateOomAdjLocked();
8722                }
8723            }
8724        } finally {
8725            Binder.restoreCallingIdentity(ident);
8726        }
8727    }
8728
8729    public void removeContentProviderExternal(String name, IBinder token) {
8730        enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
8731            "Do not have permission in call removeContentProviderExternal()");
8732        removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
8733    }
8734
8735    private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
8736        synchronized (this) {
8737            ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
8738            if(cpr == null) {
8739                //remove from mProvidersByClass
8740                if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
8741                return;
8742            }
8743
8744            //update content provider record entry info
8745            ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
8746            ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
8747            if (localCpr.hasExternalProcessHandles()) {
8748                if (localCpr.removeExternalProcessHandleLocked(token)) {
8749                    updateOomAdjLocked();
8750                } else {
8751                    Slog.e(TAG, "Attmpt to remove content provider " + localCpr
8752                            + " with no external reference for token: "
8753                            + token + ".");
8754                }
8755            } else {
8756                Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
8757                        + " with no external references.");
8758            }
8759        }
8760    }
8761
8762    public final void publishContentProviders(IApplicationThread caller,
8763            List<ContentProviderHolder> providers) {
8764        if (providers == null) {
8765            return;
8766        }
8767
8768        enforceNotIsolatedCaller("publishContentProviders");
8769        synchronized (this) {
8770            final ProcessRecord r = getRecordForAppLocked(caller);
8771            if (DEBUG_MU)
8772                Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
8773            if (r == null) {
8774                throw new SecurityException(
8775                        "Unable to find app for caller " + caller
8776                      + " (pid=" + Binder.getCallingPid()
8777                      + ") when publishing content providers");
8778            }
8779
8780            final long origId = Binder.clearCallingIdentity();
8781
8782            final int N = providers.size();
8783            for (int i=0; i<N; i++) {
8784                ContentProviderHolder src = providers.get(i);
8785                if (src == null || src.info == null || src.provider == null) {
8786                    continue;
8787                }
8788                ContentProviderRecord dst = r.pubProviders.get(src.info.name);
8789                if (DEBUG_MU)
8790                    Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
8791                if (dst != null) {
8792                    ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
8793                    mProviderMap.putProviderByClass(comp, dst);
8794                    String names[] = dst.info.authority.split(";");
8795                    for (int j = 0; j < names.length; j++) {
8796                        mProviderMap.putProviderByName(names[j], dst);
8797                    }
8798
8799                    int NL = mLaunchingProviders.size();
8800                    int j;
8801                    for (j=0; j<NL; j++) {
8802                        if (mLaunchingProviders.get(j) == dst) {
8803                            mLaunchingProviders.remove(j);
8804                            j--;
8805                            NL--;
8806                        }
8807                    }
8808                    synchronized (dst) {
8809                        dst.provider = src.provider;
8810                        dst.proc = r;
8811                        dst.notifyAll();
8812                    }
8813                    updateOomAdjLocked(r);
8814                }
8815            }
8816
8817            Binder.restoreCallingIdentity(origId);
8818        }
8819    }
8820
8821    public boolean refContentProvider(IBinder connection, int stable, int unstable) {
8822        ContentProviderConnection conn;
8823        try {
8824            conn = (ContentProviderConnection)connection;
8825        } catch (ClassCastException e) {
8826            String msg ="refContentProvider: " + connection
8827                    + " not a ContentProviderConnection";
8828            Slog.w(TAG, msg);
8829            throw new IllegalArgumentException(msg);
8830        }
8831        if (conn == null) {
8832            throw new NullPointerException("connection is null");
8833        }
8834
8835        synchronized (this) {
8836            if (stable > 0) {
8837                conn.numStableIncs += stable;
8838            }
8839            stable = conn.stableCount + stable;
8840            if (stable < 0) {
8841                throw new IllegalStateException("stableCount < 0: " + stable);
8842            }
8843
8844            if (unstable > 0) {
8845                conn.numUnstableIncs += unstable;
8846            }
8847            unstable = conn.unstableCount + unstable;
8848            if (unstable < 0) {
8849                throw new IllegalStateException("unstableCount < 0: " + unstable);
8850            }
8851
8852            if ((stable+unstable) <= 0) {
8853                throw new IllegalStateException("ref counts can't go to zero here: stable="
8854                        + stable + " unstable=" + unstable);
8855            }
8856            conn.stableCount = stable;
8857            conn.unstableCount = unstable;
8858            return !conn.dead;
8859        }
8860    }
8861
8862    public void unstableProviderDied(IBinder connection) {
8863        ContentProviderConnection conn;
8864        try {
8865            conn = (ContentProviderConnection)connection;
8866        } catch (ClassCastException e) {
8867            String msg ="refContentProvider: " + connection
8868                    + " not a ContentProviderConnection";
8869            Slog.w(TAG, msg);
8870            throw new IllegalArgumentException(msg);
8871        }
8872        if (conn == null) {
8873            throw new NullPointerException("connection is null");
8874        }
8875
8876        // Safely retrieve the content provider associated with the connection.
8877        IContentProvider provider;
8878        synchronized (this) {
8879            provider = conn.provider.provider;
8880        }
8881
8882        if (provider == null) {
8883            // Um, yeah, we're way ahead of you.
8884            return;
8885        }
8886
8887        // Make sure the caller is being honest with us.
8888        if (provider.asBinder().pingBinder()) {
8889            // Er, no, still looks good to us.
8890            synchronized (this) {
8891                Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
8892                        + " says " + conn + " died, but we don't agree");
8893                return;
8894            }
8895        }
8896
8897        // Well look at that!  It's dead!
8898        synchronized (this) {
8899            if (conn.provider.provider != provider) {
8900                // But something changed...  good enough.
8901                return;
8902            }
8903
8904            ProcessRecord proc = conn.provider.proc;
8905            if (proc == null || proc.thread == null) {
8906                // Seems like the process is already cleaned up.
8907                return;
8908            }
8909
8910            // As far as we're concerned, this is just like receiving a
8911            // death notification...  just a bit prematurely.
8912            Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
8913                    + ") early provider death");
8914            final long ident = Binder.clearCallingIdentity();
8915            try {
8916                appDiedLocked(proc, proc.pid, proc.thread);
8917            } finally {
8918                Binder.restoreCallingIdentity(ident);
8919            }
8920        }
8921    }
8922
8923    @Override
8924    public void appNotRespondingViaProvider(IBinder connection) {
8925        enforceCallingPermission(
8926                android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()");
8927
8928        final ContentProviderConnection conn = (ContentProviderConnection) connection;
8929        if (conn == null) {
8930            Slog.w(TAG, "ContentProviderConnection is null");
8931            return;
8932        }
8933
8934        final ProcessRecord host = conn.provider.proc;
8935        if (host == null) {
8936            Slog.w(TAG, "Failed to find hosting ProcessRecord");
8937            return;
8938        }
8939
8940        final long token = Binder.clearCallingIdentity();
8941        try {
8942            appNotResponding(host, null, null, false, "ContentProvider not responding");
8943        } finally {
8944            Binder.restoreCallingIdentity(token);
8945        }
8946    }
8947
8948    public final void installSystemProviders() {
8949        List<ProviderInfo> providers;
8950        synchronized (this) {
8951            ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID);
8952            providers = generateApplicationProvidersLocked(app);
8953            if (providers != null) {
8954                for (int i=providers.size()-1; i>=0; i--) {
8955                    ProviderInfo pi = (ProviderInfo)providers.get(i);
8956                    if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8957                        Slog.w(TAG, "Not installing system proc provider " + pi.name
8958                                + ": not system .apk");
8959                        providers.remove(i);
8960                    }
8961                }
8962            }
8963        }
8964        if (providers != null) {
8965            mSystemThread.installSystemProviders(providers);
8966        }
8967
8968        mCoreSettingsObserver = new CoreSettingsObserver(this);
8969
8970        //mUsageStatsService.monitorPackages();
8971    }
8972
8973    /**
8974     * Allows app to retrieve the MIME type of a URI without having permission
8975     * to access its content provider.
8976     *
8977     * CTS tests for this functionality can be run with "runtest cts-appsecurity".
8978     *
8979     * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
8980     *     src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
8981     */
8982    public String getProviderMimeType(Uri uri, int userId) {
8983        enforceNotIsolatedCaller("getProviderMimeType");
8984        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
8985                userId, false, ALLOW_NON_FULL_IN_PROFILE, "getProviderMimeType", null);
8986        final String name = uri.getAuthority();
8987        final long ident = Binder.clearCallingIdentity();
8988        ContentProviderHolder holder = null;
8989
8990        try {
8991            holder = getContentProviderExternalUnchecked(name, null, userId);
8992            if (holder != null) {
8993                return holder.provider.getType(uri);
8994            }
8995        } catch (RemoteException e) {
8996            Log.w(TAG, "Content provider dead retrieving " + uri, e);
8997            return null;
8998        } finally {
8999            if (holder != null) {
9000                removeContentProviderExternalUnchecked(name, null, userId);
9001            }
9002            Binder.restoreCallingIdentity(ident);
9003        }
9004
9005        return null;
9006    }
9007
9008    // =========================================================
9009    // GLOBAL MANAGEMENT
9010    // =========================================================
9011
9012    final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess,
9013            boolean isolated, int isolatedUid) {
9014        String proc = customProcess != null ? customProcess : info.processName;
9015        BatteryStatsImpl.Uid.Proc ps = null;
9016        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9017        int uid = info.uid;
9018        if (isolated) {
9019            if (isolatedUid == 0) {
9020                int userId = UserHandle.getUserId(uid);
9021                int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
9022                while (true) {
9023                    if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
9024                            || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
9025                        mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
9026                    }
9027                    uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
9028                    mNextIsolatedProcessUid++;
9029                    if (mIsolatedProcesses.indexOfKey(uid) < 0) {
9030                        // No process for this uid, use it.
9031                        break;
9032                    }
9033                    stepsLeft--;
9034                    if (stepsLeft <= 0) {
9035                        return null;
9036                    }
9037                }
9038            } else {
9039                // Special case for startIsolatedProcess (internal only), where
9040                // the uid of the isolated process is specified by the caller.
9041                uid = isolatedUid;
9042            }
9043        }
9044        return new ProcessRecord(stats, info, proc, uid);
9045    }
9046
9047    final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated,
9048            String abiOverride) {
9049        ProcessRecord app;
9050        if (!isolated) {
9051            app = getProcessRecordLocked(info.processName, info.uid, true);
9052        } else {
9053            app = null;
9054        }
9055
9056        if (app == null) {
9057            app = newProcessRecordLocked(info, null, isolated, 0);
9058            mProcessNames.put(info.processName, app.uid, app);
9059            if (isolated) {
9060                mIsolatedProcesses.put(app.uid, app);
9061            }
9062            updateLruProcessLocked(app, false, null);
9063            updateOomAdjLocked();
9064        }
9065
9066        // This package really, really can not be stopped.
9067        try {
9068            AppGlobals.getPackageManager().setPackageStoppedState(
9069                    info.packageName, false, UserHandle.getUserId(app.uid));
9070        } catch (RemoteException e) {
9071        } catch (IllegalArgumentException e) {
9072            Slog.w(TAG, "Failed trying to unstop package "
9073                    + info.packageName + ": " + e);
9074        }
9075
9076        if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
9077                == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
9078            app.persistent = true;
9079            app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
9080        }
9081        if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
9082            mPersistentStartingProcesses.add(app);
9083            startProcessLocked(app, "added application", app.processName, abiOverride,
9084                    null /* entryPoint */, null /* entryPointArgs */);
9085        }
9086
9087        return app;
9088    }
9089
9090    public void unhandledBack() {
9091        enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
9092                "unhandledBack()");
9093
9094        synchronized(this) {
9095            final long origId = Binder.clearCallingIdentity();
9096            try {
9097                getFocusedStack().unhandledBackLocked();
9098            } finally {
9099                Binder.restoreCallingIdentity(origId);
9100            }
9101        }
9102    }
9103
9104    public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
9105        enforceNotIsolatedCaller("openContentUri");
9106        final int userId = UserHandle.getCallingUserId();
9107        String name = uri.getAuthority();
9108        ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
9109        ParcelFileDescriptor pfd = null;
9110        if (cph != null) {
9111            // We record the binder invoker's uid in thread-local storage before
9112            // going to the content provider to open the file.  Later, in the code
9113            // that handles all permissions checks, we look for this uid and use
9114            // that rather than the Activity Manager's own uid.  The effect is that
9115            // we do the check against the caller's permissions even though it looks
9116            // to the content provider like the Activity Manager itself is making
9117            // the request.
9118            sCallerIdentity.set(new Identity(
9119                    Binder.getCallingPid(), Binder.getCallingUid()));
9120            try {
9121                pfd = cph.provider.openFile(null, uri, "r", null);
9122            } catch (FileNotFoundException e) {
9123                // do nothing; pfd will be returned null
9124            } finally {
9125                // Ensure that whatever happens, we clean up the identity state
9126                sCallerIdentity.remove();
9127            }
9128
9129            // We've got the fd now, so we're done with the provider.
9130            removeContentProviderExternalUnchecked(name, null, userId);
9131        } else {
9132            Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
9133        }
9134        return pfd;
9135    }
9136
9137    // Actually is sleeping or shutting down or whatever else in the future
9138    // is an inactive state.
9139    public boolean isSleepingOrShuttingDown() {
9140        return mSleeping || mShuttingDown;
9141    }
9142
9143    public boolean isSleeping() {
9144        return mSleeping;
9145    }
9146
9147    void goingToSleep() {
9148        synchronized(this) {
9149            mWentToSleep = true;
9150            updateEventDispatchingLocked();
9151            goToSleepIfNeededLocked();
9152        }
9153    }
9154
9155    void finishRunningVoiceLocked() {
9156        if (mRunningVoice) {
9157            mRunningVoice = false;
9158            goToSleepIfNeededLocked();
9159        }
9160    }
9161
9162    void goToSleepIfNeededLocked() {
9163        if (mWentToSleep && !mRunningVoice) {
9164            if (!mSleeping) {
9165                mSleeping = true;
9166                mStackSupervisor.goingToSleepLocked();
9167
9168                // Initialize the wake times of all processes.
9169                checkExcessivePowerUsageLocked(false);
9170                mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
9171                Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
9172                mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
9173            }
9174        }
9175    }
9176
9177    void notifyTaskPersisterLocked(TaskRecord task, boolean flush) {
9178        if (task != null && task.stack != null && task.stack.isHomeStack()) {
9179            // Never persist the home stack.
9180            return;
9181        }
9182        mTaskPersister.wakeup(task, flush);
9183    }
9184
9185    @Override
9186    public boolean shutdown(int timeout) {
9187        if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
9188                != PackageManager.PERMISSION_GRANTED) {
9189            throw new SecurityException("Requires permission "
9190                    + android.Manifest.permission.SHUTDOWN);
9191        }
9192
9193        boolean timedout = false;
9194
9195        synchronized(this) {
9196            mShuttingDown = true;
9197            updateEventDispatchingLocked();
9198            timedout = mStackSupervisor.shutdownLocked(timeout);
9199        }
9200
9201        mAppOpsService.shutdown();
9202        if (mUsageStatsService != null) {
9203            mUsageStatsService.prepareShutdown();
9204        }
9205        mBatteryStatsService.shutdown();
9206        synchronized (this) {
9207            mProcessStats.shutdownLocked();
9208        }
9209        notifyTaskPersisterLocked(null, true);
9210
9211        return timedout;
9212    }
9213
9214    public final void activitySlept(IBinder token) {
9215        if (localLOGV) Slog.v(TAG, "Activity slept: token=" + token);
9216
9217        final long origId = Binder.clearCallingIdentity();
9218
9219        synchronized (this) {
9220            final ActivityRecord r = ActivityRecord.isInStackLocked(token);
9221            if (r != null) {
9222                mStackSupervisor.activitySleptLocked(r);
9223            }
9224        }
9225
9226        Binder.restoreCallingIdentity(origId);
9227    }
9228
9229    void logLockScreen(String msg) {
9230        if (DEBUG_LOCKSCREEN) Slog.d(TAG, Debug.getCallers(2) + ":" + msg +
9231                " mLockScreenShown=" + mLockScreenShown + " mWentToSleep=" +
9232                mWentToSleep + " mSleeping=" + mSleeping + " mDismissKeyguardOnNextActivity=" +
9233                mStackSupervisor.mDismissKeyguardOnNextActivity);
9234    }
9235
9236    private void comeOutOfSleepIfNeededLocked() {
9237        if ((!mWentToSleep && !mLockScreenShown) || mRunningVoice) {
9238            if (mSleeping) {
9239                mSleeping = false;
9240                mStackSupervisor.comeOutOfSleepIfNeededLocked();
9241            }
9242        }
9243    }
9244
9245    void wakingUp() {
9246        synchronized(this) {
9247            mWentToSleep = false;
9248            updateEventDispatchingLocked();
9249            comeOutOfSleepIfNeededLocked();
9250        }
9251    }
9252
9253    void startRunningVoiceLocked() {
9254        if (!mRunningVoice) {
9255            mRunningVoice = true;
9256            comeOutOfSleepIfNeededLocked();
9257        }
9258    }
9259
9260    private void updateEventDispatchingLocked() {
9261        mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
9262    }
9263
9264    public void setLockScreenShown(boolean shown) {
9265        if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
9266                != PackageManager.PERMISSION_GRANTED) {
9267            throw new SecurityException("Requires permission "
9268                    + android.Manifest.permission.DEVICE_POWER);
9269        }
9270
9271        synchronized(this) {
9272            long ident = Binder.clearCallingIdentity();
9273            try {
9274                if (DEBUG_LOCKSCREEN) logLockScreen(" shown=" + shown);
9275                mLockScreenShown = shown;
9276                comeOutOfSleepIfNeededLocked();
9277            } finally {
9278                Binder.restoreCallingIdentity(ident);
9279            }
9280        }
9281    }
9282
9283    @Override
9284    public void stopAppSwitches() {
9285        if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
9286                != PackageManager.PERMISSION_GRANTED) {
9287            throw new SecurityException("Requires permission "
9288                    + android.Manifest.permission.STOP_APP_SWITCHES);
9289        }
9290
9291        synchronized(this) {
9292            mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
9293                    + APP_SWITCH_DELAY_TIME;
9294            mDidAppSwitch = false;
9295            mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
9296            Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
9297            mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
9298        }
9299    }
9300
9301    public void resumeAppSwitches() {
9302        if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
9303                != PackageManager.PERMISSION_GRANTED) {
9304            throw new SecurityException("Requires permission "
9305                    + android.Manifest.permission.STOP_APP_SWITCHES);
9306        }
9307
9308        synchronized(this) {
9309            // Note that we don't execute any pending app switches... we will
9310            // let those wait until either the timeout, or the next start
9311            // activity request.
9312            mAppSwitchesAllowedTime = 0;
9313        }
9314    }
9315
9316    boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
9317            String name) {
9318        if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
9319            return true;
9320        }
9321
9322        final int perm = checkComponentPermission(
9323                android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
9324                callingUid, -1, true);
9325        if (perm == PackageManager.PERMISSION_GRANTED) {
9326            return true;
9327        }
9328
9329        Slog.w(TAG, name + " request from " + callingUid + " stopped");
9330        return false;
9331    }
9332
9333    public void setDebugApp(String packageName, boolean waitForDebugger,
9334            boolean persistent) {
9335        enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
9336                "setDebugApp()");
9337
9338        long ident = Binder.clearCallingIdentity();
9339        try {
9340            // Note that this is not really thread safe if there are multiple
9341            // callers into it at the same time, but that's not a situation we
9342            // care about.
9343            if (persistent) {
9344                final ContentResolver resolver = mContext.getContentResolver();
9345                Settings.Global.putString(
9346                    resolver, Settings.Global.DEBUG_APP,
9347                    packageName);
9348                Settings.Global.putInt(
9349                    resolver, Settings.Global.WAIT_FOR_DEBUGGER,
9350                    waitForDebugger ? 1 : 0);
9351            }
9352
9353            synchronized (this) {
9354                if (!persistent) {
9355                    mOrigDebugApp = mDebugApp;
9356                    mOrigWaitForDebugger = mWaitForDebugger;
9357                }
9358                mDebugApp = packageName;
9359                mWaitForDebugger = waitForDebugger;
9360                mDebugTransient = !persistent;
9361                if (packageName != null) {
9362                    forceStopPackageLocked(packageName, -1, false, false, true, true,
9363                            false, UserHandle.USER_ALL, "set debug app");
9364                }
9365            }
9366        } finally {
9367            Binder.restoreCallingIdentity(ident);
9368        }
9369    }
9370
9371    void setOpenGlTraceApp(ApplicationInfo app, String processName) {
9372        synchronized (this) {
9373            boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
9374            if (!isDebuggable) {
9375                if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
9376                    throw new SecurityException("Process not debuggable: " + app.packageName);
9377                }
9378            }
9379
9380            mOpenGlTraceApp = processName;
9381        }
9382    }
9383
9384    void setProfileApp(ApplicationInfo app, String processName, String profileFile,
9385            ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
9386        synchronized (this) {
9387            boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
9388            if (!isDebuggable) {
9389                if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
9390                    throw new SecurityException("Process not debuggable: " + app.packageName);
9391                }
9392            }
9393            mProfileApp = processName;
9394            mProfileFile = profileFile;
9395            if (mProfileFd != null) {
9396                try {
9397                    mProfileFd.close();
9398                } catch (IOException e) {
9399                }
9400                mProfileFd = null;
9401            }
9402            mProfileFd = profileFd;
9403            mProfileType = 0;
9404            mAutoStopProfiler = autoStopProfiler;
9405        }
9406    }
9407
9408    @Override
9409    public void setAlwaysFinish(boolean enabled) {
9410        enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
9411                "setAlwaysFinish()");
9412
9413        Settings.Global.putInt(
9414                mContext.getContentResolver(),
9415                Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
9416
9417        synchronized (this) {
9418            mAlwaysFinishActivities = enabled;
9419        }
9420    }
9421
9422    @Override
9423    public void setActivityController(IActivityController controller) {
9424        enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
9425                "setActivityController()");
9426        synchronized (this) {
9427            mController = controller;
9428            Watchdog.getInstance().setActivityController(controller);
9429        }
9430    }
9431
9432    @Override
9433    public void setUserIsMonkey(boolean userIsMonkey) {
9434        synchronized (this) {
9435            synchronized (mPidsSelfLocked) {
9436                final int callingPid = Binder.getCallingPid();
9437                ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid);
9438                if (precessRecord == null) {
9439                    throw new SecurityException("Unknown process: " + callingPid);
9440                }
9441                if (precessRecord.instrumentationUiAutomationConnection  == null) {
9442                    throw new SecurityException("Only an instrumentation process "
9443                            + "with a UiAutomation can call setUserIsMonkey");
9444                }
9445            }
9446            mUserIsMonkey = userIsMonkey;
9447        }
9448    }
9449
9450    @Override
9451    public boolean isUserAMonkey() {
9452        synchronized (this) {
9453            // If there is a controller also implies the user is a monkey.
9454            return (mUserIsMonkey || mController != null);
9455        }
9456    }
9457
9458    public void requestBugReport() {
9459        enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
9460        SystemProperties.set("ctl.start", "bugreport");
9461    }
9462
9463    public static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
9464        return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT;
9465    }
9466
9467    public static long getInputDispatchingTimeoutLocked(ProcessRecord r) {
9468        if (r != null && (r.instrumentationClass != null || r.usingWrapper)) {
9469            return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
9470        }
9471        return KEY_DISPATCHING_TIMEOUT;
9472    }
9473
9474    @Override
9475    public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) {
9476        if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
9477                != PackageManager.PERMISSION_GRANTED) {
9478            throw new SecurityException("Requires permission "
9479                    + android.Manifest.permission.FILTER_EVENTS);
9480        }
9481        ProcessRecord proc;
9482        long timeout;
9483        synchronized (this) {
9484            synchronized (mPidsSelfLocked) {
9485                proc = mPidsSelfLocked.get(pid);
9486            }
9487            timeout = getInputDispatchingTimeoutLocked(proc);
9488        }
9489
9490        if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) {
9491            return -1;
9492        }
9493
9494        return timeout;
9495    }
9496
9497    /**
9498     * Handle input dispatching timeouts.
9499     * Returns whether input dispatching should be aborted or not.
9500     */
9501    public boolean inputDispatchingTimedOut(final ProcessRecord proc,
9502            final ActivityRecord activity, final ActivityRecord parent,
9503            final boolean aboveSystem, String reason) {
9504        if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
9505                != PackageManager.PERMISSION_GRANTED) {
9506            throw new SecurityException("Requires permission "
9507                    + android.Manifest.permission.FILTER_EVENTS);
9508        }
9509
9510        final String annotation;
9511        if (reason == null) {
9512            annotation = "Input dispatching timed out";
9513        } else {
9514            annotation = "Input dispatching timed out (" + reason + ")";
9515        }
9516
9517        if (proc != null) {
9518            synchronized (this) {
9519                if (proc.debugging) {
9520                    return false;
9521                }
9522
9523                if (mDidDexOpt) {
9524                    // Give more time since we were dexopting.
9525                    mDidDexOpt = false;
9526                    return false;
9527                }
9528
9529                if (proc.instrumentationClass != null) {
9530                    Bundle info = new Bundle();
9531                    info.putString("shortMsg", "keyDispatchingTimedOut");
9532                    info.putString("longMsg", annotation);
9533                    finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
9534                    return true;
9535                }
9536            }
9537            mHandler.post(new Runnable() {
9538                @Override
9539                public void run() {
9540                    appNotResponding(proc, activity, parent, aboveSystem, annotation);
9541                }
9542            });
9543        }
9544
9545        return true;
9546    }
9547
9548    public Bundle getAssistContextExtras(int requestType) {
9549        enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
9550                "getAssistContextExtras()");
9551        PendingAssistExtras pae;
9552        Bundle extras = new Bundle();
9553        synchronized (this) {
9554            ActivityRecord activity = getFocusedStack().mResumedActivity;
9555            if (activity == null) {
9556                Slog.w(TAG, "getAssistContextExtras failed: no resumed activity");
9557                return null;
9558            }
9559            extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
9560            if (activity.app == null || activity.app.thread == null) {
9561                Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
9562                return extras;
9563            }
9564            if (activity.app.pid == Binder.getCallingPid()) {
9565                Slog.w(TAG, "getAssistContextExtras failed: request process same as " + activity);
9566                return extras;
9567            }
9568            pae = new PendingAssistExtras(activity);
9569            try {
9570                activity.app.thread.requestAssistContextExtras(activity.appToken, pae,
9571                        requestType);
9572                mPendingAssistExtras.add(pae);
9573                mHandler.postDelayed(pae, PENDING_ASSIST_EXTRAS_TIMEOUT);
9574            } catch (RemoteException e) {
9575                Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity);
9576                return extras;
9577            }
9578        }
9579        synchronized (pae) {
9580            while (!pae.haveResult) {
9581                try {
9582                    pae.wait();
9583                } catch (InterruptedException e) {
9584                }
9585            }
9586            if (pae.result != null) {
9587                extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
9588            }
9589        }
9590        synchronized (this) {
9591            mPendingAssistExtras.remove(pae);
9592            mHandler.removeCallbacks(pae);
9593        }
9594        return extras;
9595    }
9596
9597    public void reportAssistContextExtras(IBinder token, Bundle extras) {
9598        PendingAssistExtras pae = (PendingAssistExtras)token;
9599        synchronized (pae) {
9600            pae.result = extras;
9601            pae.haveResult = true;
9602            pae.notifyAll();
9603        }
9604    }
9605
9606    public void registerProcessObserver(IProcessObserver observer) {
9607        enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
9608                "registerProcessObserver()");
9609        synchronized (this) {
9610            mProcessObservers.register(observer);
9611        }
9612    }
9613
9614    @Override
9615    public void unregisterProcessObserver(IProcessObserver observer) {
9616        synchronized (this) {
9617            mProcessObservers.unregister(observer);
9618        }
9619    }
9620
9621    @Override
9622    public boolean convertFromTranslucent(IBinder token) {
9623        final long origId = Binder.clearCallingIdentity();
9624        try {
9625            synchronized (this) {
9626                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
9627                if (r == null) {
9628                    return false;
9629                }
9630                if (r.changeWindowTranslucency(true)) {
9631                    mWindowManager.setAppFullscreen(token, true);
9632                    r.task.stack.releaseMediaResources();
9633                    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
9634                    return true;
9635                }
9636                return false;
9637            }
9638        } finally {
9639            Binder.restoreCallingIdentity(origId);
9640        }
9641    }
9642
9643    @Override
9644    public boolean convertToTranslucent(IBinder token, ActivityOptions options) {
9645        final long origId = Binder.clearCallingIdentity();
9646        try {
9647            synchronized (this) {
9648                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
9649                if (r == null) {
9650                    return false;
9651                }
9652                int index = r.task.mActivities.lastIndexOf(r);
9653                if (index > 0) {
9654                    ActivityRecord under = r.task.mActivities.get(index - 1);
9655                    under.returningOptions = options;
9656                }
9657                if (r.changeWindowTranslucency(false)) {
9658                    r.task.stack.convertToTranslucent(r);
9659                    mWindowManager.setAppFullscreen(token, false);
9660                    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
9661                    return true;
9662                } else {
9663                    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0);
9664                    return false;
9665                }
9666            }
9667        } finally {
9668            Binder.restoreCallingIdentity(origId);
9669        }
9670    }
9671
9672    @Override
9673    public boolean setMediaPlaying(IBinder token, boolean playing) {
9674        final long origId = Binder.clearCallingIdentity();
9675        try {
9676            synchronized (this) {
9677                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
9678                if (r != null) {
9679                    return mStackSupervisor.setMediaPlayingLocked(r, playing);
9680                }
9681            }
9682            return false;
9683        } finally {
9684            Binder.restoreCallingIdentity(origId);
9685        }
9686    }
9687
9688    @Override
9689    public boolean isBackgroundMediaPlaying(IBinder token) {
9690        final long origId = Binder.clearCallingIdentity();
9691        try {
9692            synchronized (this) {
9693                final ActivityStack stack = ActivityRecord.getStackLocked(token);
9694                final boolean playing = stack == null ? false : stack.isMediaPlaying();
9695                if (ActivityStackSupervisor.DEBUG_MEDIA_VISIBILITY) Slog.d(TAG,
9696                        "isBackgroundMediaPlaying: stack=" + stack + " playing=" + playing);
9697                return playing;
9698            }
9699        } finally {
9700            Binder.restoreCallingIdentity(origId);
9701        }
9702    }
9703
9704    @Override
9705    public ActivityOptions getActivityOptions(IBinder token) {
9706        final long origId = Binder.clearCallingIdentity();
9707        try {
9708            synchronized (this) {
9709                final ActivityRecord r = ActivityRecord.isInStackLocked(token);
9710                if (r != null) {
9711                    final ActivityOptions activityOptions = r.pendingOptions;
9712                    r.pendingOptions = null;
9713                    return activityOptions;
9714                }
9715                return null;
9716            }
9717        } finally {
9718            Binder.restoreCallingIdentity(origId);
9719        }
9720    }
9721
9722    @Override
9723    public void setImmersive(IBinder token, boolean immersive) {
9724        synchronized(this) {
9725            final ActivityRecord r = ActivityRecord.isInStackLocked(token);
9726            if (r == null) {
9727                throw new IllegalArgumentException();
9728            }
9729            r.immersive = immersive;
9730
9731            // update associated state if we're frontmost
9732            if (r == mFocusedActivity) {
9733                if (DEBUG_IMMERSIVE) {
9734                    Slog.d(TAG, "Frontmost changed immersion: "+ r);
9735                }
9736                applyUpdateLockStateLocked(r);
9737            }
9738        }
9739    }
9740
9741    @Override
9742    public boolean isImmersive(IBinder token) {
9743        synchronized (this) {
9744            ActivityRecord r = ActivityRecord.isInStackLocked(token);
9745            if (r == null) {
9746                throw new IllegalArgumentException();
9747            }
9748            return r.immersive;
9749        }
9750    }
9751
9752    public boolean isTopActivityImmersive() {
9753        enforceNotIsolatedCaller("startActivity");
9754        synchronized (this) {
9755            ActivityRecord r = getFocusedStack().topRunningActivityLocked(null);
9756            return (r != null) ? r.immersive : false;
9757        }
9758    }
9759
9760    @Override
9761    public boolean isTopOfTask(IBinder token) {
9762        synchronized (this) {
9763            ActivityRecord r = ActivityRecord.isInStackLocked(token);
9764            if (r == null) {
9765                throw new IllegalArgumentException();
9766            }
9767            return r.task.getTopActivity() == r;
9768        }
9769    }
9770
9771    public final void enterSafeMode() {
9772        synchronized(this) {
9773            // It only makes sense to do this before the system is ready
9774            // and started launching other packages.
9775            if (!mSystemReady) {
9776                try {
9777                    AppGlobals.getPackageManager().enterSafeMode();
9778                } catch (RemoteException e) {
9779                }
9780            }
9781
9782            mSafeMode = true;
9783        }
9784    }
9785
9786    public final void showSafeModeOverlay() {
9787        View v = LayoutInflater.from(mContext).inflate(
9788                com.android.internal.R.layout.safe_mode, null);
9789        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
9790        lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
9791        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
9792        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
9793        lp.gravity = Gravity.BOTTOM | Gravity.START;
9794        lp.format = v.getBackground().getOpacity();
9795        lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
9796                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
9797        lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
9798        ((WindowManager)mContext.getSystemService(
9799                Context.WINDOW_SERVICE)).addView(v, lp);
9800    }
9801
9802    public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg) {
9803        if (!(sender instanceof PendingIntentRecord)) {
9804            return;
9805        }
9806        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
9807        synchronized (stats) {
9808            if (mBatteryStatsService.isOnBattery()) {
9809                mBatteryStatsService.enforceCallingPermission();
9810                PendingIntentRecord rec = (PendingIntentRecord)sender;
9811                int MY_UID = Binder.getCallingUid();
9812                int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
9813                BatteryStatsImpl.Uid.Pkg pkg =
9814                    stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid,
9815                            sourcePkg != null ? sourcePkg : rec.key.packageName);
9816                pkg.incWakeupsLocked();
9817            }
9818        }
9819    }
9820
9821    public boolean killPids(int[] pids, String pReason, boolean secure) {
9822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9823            throw new SecurityException("killPids only available to the system");
9824        }
9825        String reason = (pReason == null) ? "Unknown" : pReason;
9826        // XXX Note: don't acquire main activity lock here, because the window
9827        // manager calls in with its locks held.
9828
9829        boolean killed = false;
9830        synchronized (mPidsSelfLocked) {
9831            int[] types = new int[pids.length];
9832            int worstType = 0;
9833            for (int i=0; i<pids.length; i++) {
9834                ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
9835                if (proc != null) {
9836                    int type = proc.setAdj;
9837                    types[i] = type;
9838                    if (type > worstType) {
9839                        worstType = type;
9840                    }
9841                }
9842            }
9843
9844            // If the worst oom_adj is somewhere in the cached proc LRU range,
9845            // then constrain it so we will kill all cached procs.
9846            if (worstType < ProcessList.CACHED_APP_MAX_ADJ
9847                    && worstType > ProcessList.CACHED_APP_MIN_ADJ) {
9848                worstType = ProcessList.CACHED_APP_MIN_ADJ;
9849            }
9850
9851            // If this is not a secure call, don't let it kill processes that
9852            // are important.
9853            if (!secure && worstType < ProcessList.SERVICE_ADJ) {
9854                worstType = ProcessList.SERVICE_ADJ;
9855            }
9856
9857            Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
9858            for (int i=0; i<pids.length; i++) {
9859                ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
9860                if (proc == null) {
9861                    continue;
9862                }
9863                int adj = proc.setAdj;
9864                if (adj >= worstType && !proc.killedByAm) {
9865                    killUnneededProcessLocked(proc, reason);
9866                    killed = true;
9867                }
9868            }
9869        }
9870        return killed;
9871    }
9872
9873    @Override
9874    public void killUid(int uid, String reason) {
9875        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9876            throw new SecurityException("killUid only available to the system");
9877        }
9878        synchronized (this) {
9879            killPackageProcessesLocked(null, UserHandle.getAppId(uid), UserHandle.getUserId(uid),
9880                    ProcessList.FOREGROUND_APP_ADJ-1, false, true, true, false,
9881                    reason != null ? reason : "kill uid");
9882        }
9883    }
9884
9885    @Override
9886    public boolean killProcessesBelowForeground(String reason) {
9887        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9888            throw new SecurityException("killProcessesBelowForeground() only available to system");
9889        }
9890
9891        return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
9892    }
9893
9894    private boolean killProcessesBelowAdj(int belowAdj, String reason) {
9895        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9896            throw new SecurityException("killProcessesBelowAdj() only available to system");
9897        }
9898
9899        boolean killed = false;
9900        synchronized (mPidsSelfLocked) {
9901            final int size = mPidsSelfLocked.size();
9902            for (int i = 0; i < size; i++) {
9903                final int pid = mPidsSelfLocked.keyAt(i);
9904                final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
9905                if (proc == null) continue;
9906
9907                final int adj = proc.setAdj;
9908                if (adj > belowAdj && !proc.killedByAm) {
9909                    killUnneededProcessLocked(proc, reason);
9910                    killed = true;
9911                }
9912            }
9913        }
9914        return killed;
9915    }
9916
9917    @Override
9918    public void hang(final IBinder who, boolean allowRestart) {
9919        if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9920                != PackageManager.PERMISSION_GRANTED) {
9921            throw new SecurityException("Requires permission "
9922                    + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9923        }
9924
9925        final IBinder.DeathRecipient death = new DeathRecipient() {
9926            @Override
9927            public void binderDied() {
9928                synchronized (this) {
9929                    notifyAll();
9930                }
9931            }
9932        };
9933
9934        try {
9935            who.linkToDeath(death, 0);
9936        } catch (RemoteException e) {
9937            Slog.w(TAG, "hang: given caller IBinder is already dead.");
9938            return;
9939        }
9940
9941        synchronized (this) {
9942            Watchdog.getInstance().setAllowRestart(allowRestart);
9943            Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
9944            synchronized (death) {
9945                while (who.isBinderAlive()) {
9946                    try {
9947                        death.wait();
9948                    } catch (InterruptedException e) {
9949                    }
9950                }
9951            }
9952            Watchdog.getInstance().setAllowRestart(true);
9953        }
9954    }
9955
9956    @Override
9957    public void restart() {
9958        if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9959                != PackageManager.PERMISSION_GRANTED) {
9960            throw new SecurityException("Requires permission "
9961                    + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9962        }
9963
9964        Log.i(TAG, "Sending shutdown broadcast...");
9965
9966        BroadcastReceiver br = new BroadcastReceiver() {
9967            @Override public void onReceive(Context context, Intent intent) {
9968                // Now the broadcast is done, finish up the low-level shutdown.
9969                Log.i(TAG, "Shutting down activity manager...");
9970                shutdown(10000);
9971                Log.i(TAG, "Shutdown complete, restarting!");
9972                Process.killProcess(Process.myPid());
9973                System.exit(10);
9974            }
9975        };
9976
9977        // First send the high-level shut down broadcast.
9978        Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
9979        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9980        intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
9981        /* For now we are not doing a clean shutdown, because things seem to get unhappy.
9982        mContext.sendOrderedBroadcastAsUser(intent,
9983                UserHandle.ALL, null, br, mHandler, 0, null, null);
9984        */
9985        br.onReceive(mContext, intent);
9986    }
9987
9988    private long getLowRamTimeSinceIdle(long now) {
9989        return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0);
9990    }
9991
9992    @Override
9993    public void performIdleMaintenance() {
9994        if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
9995                != PackageManager.PERMISSION_GRANTED) {
9996            throw new SecurityException("Requires permission "
9997                    + android.Manifest.permission.SET_ACTIVITY_WATCHER);
9998        }
9999
10000        synchronized (this) {
10001            final long now = SystemClock.uptimeMillis();
10002            final long timeSinceLastIdle = now - mLastIdleTime;
10003            final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now);
10004            mLastIdleTime = now;
10005            mLowRamTimeSinceLastIdle = 0;
10006            if (mLowRamStartTime != 0) {
10007                mLowRamStartTime = now;
10008            }
10009
10010            StringBuilder sb = new StringBuilder(128);
10011            sb.append("Idle maintenance over ");
10012            TimeUtils.formatDuration(timeSinceLastIdle, sb);
10013            sb.append(" low RAM for ");
10014            TimeUtils.formatDuration(lowRamSinceLastIdle, sb);
10015            Slog.i(TAG, sb.toString());
10016
10017            // If at least 1/3 of our time since the last idle period has been spent
10018            // with RAM low, then we want to kill processes.
10019            boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3);
10020
10021            for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
10022                ProcessRecord proc = mLruProcesses.get(i);
10023                if (proc.notCachedSinceIdle) {
10024                    if (proc.setProcState > ActivityManager.PROCESS_STATE_TOP
10025                            && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) {
10026                        if (doKilling && proc.initialIdlePss != 0
10027                                && proc.lastPss > ((proc.initialIdlePss*3)/2)) {
10028                            killUnneededProcessLocked(proc, "idle maint (pss " + proc.lastPss
10029                                    + " from " + proc.initialIdlePss + ")");
10030                        }
10031                    }
10032                } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME) {
10033                    proc.notCachedSinceIdle = true;
10034                    proc.initialIdlePss = 0;
10035                    proc.nextPssTime = ProcessList.computeNextPssTime(proc.curProcState, true,
10036                            isSleeping(), now);
10037                }
10038            }
10039
10040            mHandler.removeMessages(REQUEST_ALL_PSS_MSG);
10041            mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000);
10042        }
10043    }
10044
10045    private void retrieveSettings() {
10046        final ContentResolver resolver = mContext.getContentResolver();
10047        String debugApp = Settings.Global.getString(
10048            resolver, Settings.Global.DEBUG_APP);
10049        boolean waitForDebugger = Settings.Global.getInt(
10050            resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
10051        boolean alwaysFinishActivities = Settings.Global.getInt(
10052            resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
10053        boolean forceRtl = Settings.Global.getInt(
10054                resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0;
10055        // Transfer any global setting for forcing RTL layout, into a System Property
10056        SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0");
10057
10058        Configuration configuration = new Configuration();
10059        Settings.System.getConfiguration(resolver, configuration);
10060        if (forceRtl) {
10061            // This will take care of setting the correct layout direction flags
10062            configuration.setLayoutDirection(configuration.locale);
10063        }
10064
10065        synchronized (this) {
10066            mDebugApp = mOrigDebugApp = debugApp;
10067            mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
10068            mAlwaysFinishActivities = alwaysFinishActivities;
10069            // This happens before any activities are started, so we can
10070            // change mConfiguration in-place.
10071            updateConfigurationLocked(configuration, null, false, true);
10072            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
10073        }
10074    }
10075
10076    public boolean testIsSystemReady() {
10077        // no need to synchronize(this) just to read & return the value
10078        return mSystemReady;
10079    }
10080
10081    private static File getCalledPreBootReceiversFile() {
10082        File dataDir = Environment.getDataDirectory();
10083        File systemDir = new File(dataDir, "system");
10084        File fname = new File(systemDir, CALLED_PRE_BOOTS_FILENAME);
10085        return fname;
10086    }
10087
10088    private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
10089        ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
10090        File file = getCalledPreBootReceiversFile();
10091        FileInputStream fis = null;
10092        try {
10093            fis = new FileInputStream(file);
10094            DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
10095            int fvers = dis.readInt();
10096            if (fvers == LAST_PREBOOT_DELIVERED_FILE_VERSION) {
10097                String vers = dis.readUTF();
10098                String codename = dis.readUTF();
10099                String build = dis.readUTF();
10100                if (android.os.Build.VERSION.RELEASE.equals(vers)
10101                        && android.os.Build.VERSION.CODENAME.equals(codename)
10102                        && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
10103                    int num = dis.readInt();
10104                    while (num > 0) {
10105                        num--;
10106                        String pkg = dis.readUTF();
10107                        String cls = dis.readUTF();
10108                        lastDoneReceivers.add(new ComponentName(pkg, cls));
10109                    }
10110                }
10111            }
10112        } catch (FileNotFoundException e) {
10113        } catch (IOException e) {
10114            Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
10115        } finally {
10116            if (fis != null) {
10117                try {
10118                    fis.close();
10119                } catch (IOException e) {
10120                }
10121            }
10122        }
10123        return lastDoneReceivers;
10124    }
10125
10126    private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
10127        File file = getCalledPreBootReceiversFile();
10128        FileOutputStream fos = null;
10129        DataOutputStream dos = null;
10130        try {
10131            fos = new FileOutputStream(file);
10132            dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
10133            dos.writeInt(LAST_PREBOOT_DELIVERED_FILE_VERSION);
10134            dos.writeUTF(android.os.Build.VERSION.RELEASE);
10135            dos.writeUTF(android.os.Build.VERSION.CODENAME);
10136            dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
10137            dos.writeInt(list.size());
10138            for (int i=0; i<list.size(); i++) {
10139                dos.writeUTF(list.get(i).getPackageName());
10140                dos.writeUTF(list.get(i).getClassName());
10141            }
10142        } catch (IOException e) {
10143            Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
10144            file.delete();
10145        } finally {
10146            FileUtils.sync(fos);
10147            if (dos != null) {
10148                try {
10149                    dos.close();
10150                } catch (IOException e) {
10151                    // TODO Auto-generated catch block
10152                    e.printStackTrace();
10153                }
10154            }
10155        }
10156    }
10157
10158    private boolean deliverPreBootCompleted(final Runnable onFinishCallback,
10159            ArrayList<ComponentName> doneReceivers, int userId) {
10160        boolean waitingUpdate = false;
10161        Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
10162        List<ResolveInfo> ris = null;
10163        try {
10164            ris = AppGlobals.getPackageManager().queryIntentReceivers(
10165                    intent, null, 0, userId);
10166        } catch (RemoteException e) {
10167        }
10168        if (ris != null) {
10169            for (int i=ris.size()-1; i>=0; i--) {
10170                if ((ris.get(i).activityInfo.applicationInfo.flags
10171                        &ApplicationInfo.FLAG_SYSTEM) == 0) {
10172                    ris.remove(i);
10173                }
10174            }
10175            intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
10176
10177            // For User 0, load the version number. When delivering to a new user, deliver
10178            // to all receivers.
10179            if (userId == UserHandle.USER_OWNER) {
10180                ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
10181                for (int i=0; i<ris.size(); i++) {
10182                    ActivityInfo ai = ris.get(i).activityInfo;
10183                    ComponentName comp = new ComponentName(ai.packageName, ai.name);
10184                    if (lastDoneReceivers.contains(comp)) {
10185                        // We already did the pre boot receiver for this app with the current
10186                        // platform version, so don't do it again...
10187                        ris.remove(i);
10188                        i--;
10189                        // ...however, do keep it as one that has been done, so we don't
10190                        // forget about it when rewriting the file of last done receivers.
10191                        doneReceivers.add(comp);
10192                    }
10193                }
10194            }
10195
10196            // If primary user, send broadcast to all available users, else just to userId
10197            final int[] users = userId == UserHandle.USER_OWNER ? getUsersLocked()
10198                    : new int[] { userId };
10199            for (int i = 0; i < ris.size(); i++) {
10200                ActivityInfo ai = ris.get(i).activityInfo;
10201                ComponentName comp = new ComponentName(ai.packageName, ai.name);
10202                doneReceivers.add(comp);
10203                intent.setComponent(comp);
10204                for (int j=0; j<users.length; j++) {
10205                    IIntentReceiver finisher = null;
10206                    // On last receiver and user, set up a completion callback
10207                    if (i == ris.size() - 1 && j == users.length - 1 && onFinishCallback != null) {
10208                        finisher = new IIntentReceiver.Stub() {
10209                            public void performReceive(Intent intent, int resultCode,
10210                                    String data, Bundle extras, boolean ordered,
10211                                    boolean sticky, int sendingUser) {
10212                                // The raw IIntentReceiver interface is called
10213                                // with the AM lock held, so redispatch to
10214                                // execute our code without the lock.
10215                                mHandler.post(onFinishCallback);
10216                            }
10217                        };
10218                    }
10219                    Slog.i(TAG, "Sending system update to " + intent.getComponent()
10220                            + " for user " + users[j]);
10221                    broadcastIntentLocked(null, null, intent, null, finisher,
10222                            0, null, null, null, AppOpsManager.OP_NONE,
10223                            true, false, MY_PID, Process.SYSTEM_UID,
10224                            users[j]);
10225                    if (finisher != null) {
10226                        waitingUpdate = true;
10227                    }
10228                }
10229            }
10230        }
10231
10232        return waitingUpdate;
10233    }
10234
10235    public void systemReady(final Runnable goingCallback) {
10236        synchronized(this) {
10237            if (mSystemReady) {
10238                // If we're done calling all the receivers, run the next "boot phase" passed in
10239                // by the SystemServer
10240                if (goingCallback != null) {
10241                    goingCallback.run();
10242                }
10243                return;
10244            }
10245
10246            // Make sure we have the current profile info, since it is needed for
10247            // security checks.
10248            updateCurrentProfileIdsLocked();
10249
10250            if (mRecentTasks == null) {
10251                mRecentTasks = mTaskPersister.restoreTasksLocked();
10252                if (!mRecentTasks.isEmpty()) {
10253                    mStackSupervisor.createStackForRestoredTaskHistory(mRecentTasks);
10254                }
10255                mTaskPersister.startPersisting();
10256            }
10257
10258            // Check to see if there are any update receivers to run.
10259            if (!mDidUpdate) {
10260                if (mWaitingUpdate) {
10261                    return;
10262                }
10263                final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
10264                mWaitingUpdate = deliverPreBootCompleted(new Runnable() {
10265                    public void run() {
10266                        synchronized (ActivityManagerService.this) {
10267                            mDidUpdate = true;
10268                        }
10269                        writeLastDonePreBootReceivers(doneReceivers);
10270                        showBootMessage(mContext.getText(
10271                                R.string.android_upgrading_complete),
10272                                false);
10273                        systemReady(goingCallback);
10274                    }
10275                }, doneReceivers, UserHandle.USER_OWNER);
10276
10277                if (mWaitingUpdate) {
10278                    return;
10279                }
10280                mDidUpdate = true;
10281            }
10282
10283            mAppOpsService.systemReady();
10284            mSystemReady = true;
10285        }
10286
10287        ArrayList<ProcessRecord> procsToKill = null;
10288        synchronized(mPidsSelfLocked) {
10289            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
10290                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
10291                if (!isAllowedWhileBooting(proc.info)){
10292                    if (procsToKill == null) {
10293                        procsToKill = new ArrayList<ProcessRecord>();
10294                    }
10295                    procsToKill.add(proc);
10296                }
10297            }
10298        }
10299
10300        synchronized(this) {
10301            if (procsToKill != null) {
10302                for (int i=procsToKill.size()-1; i>=0; i--) {
10303                    ProcessRecord proc = procsToKill.get(i);
10304                    Slog.i(TAG, "Removing system update proc: " + proc);
10305                    removeProcessLocked(proc, true, false, "system update done");
10306                }
10307            }
10308
10309            // Now that we have cleaned up any update processes, we
10310            // are ready to start launching real processes and know that
10311            // we won't trample on them any more.
10312            mProcessesReady = true;
10313        }
10314
10315        Slog.i(TAG, "System now ready");
10316        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
10317            SystemClock.uptimeMillis());
10318
10319        synchronized(this) {
10320            // Make sure we have no pre-ready processes sitting around.
10321
10322            if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
10323                ResolveInfo ri = mContext.getPackageManager()
10324                        .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
10325                                STOCK_PM_FLAGS);
10326                CharSequence errorMsg = null;
10327                if (ri != null) {
10328                    ActivityInfo ai = ri.activityInfo;
10329                    ApplicationInfo app = ai.applicationInfo;
10330                    if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
10331                        mTopAction = Intent.ACTION_FACTORY_TEST;
10332                        mTopData = null;
10333                        mTopComponent = new ComponentName(app.packageName,
10334                                ai.name);
10335                    } else {
10336                        errorMsg = mContext.getResources().getText(
10337                                com.android.internal.R.string.factorytest_not_system);
10338                    }
10339                } else {
10340                    errorMsg = mContext.getResources().getText(
10341                            com.android.internal.R.string.factorytest_no_action);
10342                }
10343                if (errorMsg != null) {
10344                    mTopAction = null;
10345                    mTopData = null;
10346                    mTopComponent = null;
10347                    Message msg = Message.obtain();
10348                    msg.what = SHOW_FACTORY_ERROR_MSG;
10349                    msg.getData().putCharSequence("msg", errorMsg);
10350                    mHandler.sendMessage(msg);
10351                }
10352            }
10353        }
10354
10355        retrieveSettings();
10356
10357        synchronized (this) {
10358            readGrantedUriPermissionsLocked();
10359        }
10360
10361        if (goingCallback != null) goingCallback.run();
10362
10363        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
10364                Integer.toString(mCurrentUserId), mCurrentUserId);
10365        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
10366                Integer.toString(mCurrentUserId), mCurrentUserId);
10367        mSystemServiceManager.startUser(mCurrentUserId);
10368
10369        synchronized (this) {
10370            if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
10371                try {
10372                    List apps = AppGlobals.getPackageManager().
10373                        getPersistentApplications(STOCK_PM_FLAGS);
10374                    if (apps != null) {
10375                        int N = apps.size();
10376                        int i;
10377                        for (i=0; i<N; i++) {
10378                            ApplicationInfo info
10379                                = (ApplicationInfo)apps.get(i);
10380                            if (info != null &&
10381                                    !info.packageName.equals("android")) {
10382                                addAppLocked(info, false, null /* ABI override */);
10383                            }
10384                        }
10385                    }
10386                } catch (RemoteException ex) {
10387                    // pm is in same process, this will never happen.
10388                }
10389            }
10390
10391            // Start up initial activity.
10392            mBooting = true;
10393
10394            try {
10395                if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
10396                    Message msg = Message.obtain();
10397                    msg.what = SHOW_UID_ERROR_MSG;
10398                    mHandler.sendMessage(msg);
10399                }
10400            } catch (RemoteException e) {
10401            }
10402
10403            long ident = Binder.clearCallingIdentity();
10404            try {
10405                Intent intent = new Intent(Intent.ACTION_USER_STARTED);
10406                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
10407                        | Intent.FLAG_RECEIVER_FOREGROUND);
10408                intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
10409                broadcastIntentLocked(null, null, intent,
10410                        null, null, 0, null, null, null, AppOpsManager.OP_NONE,
10411                        false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
10412                intent = new Intent(Intent.ACTION_USER_STARTING);
10413                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
10414                intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
10415                broadcastIntentLocked(null, null, intent,
10416                        null, new IIntentReceiver.Stub() {
10417                            @Override
10418                            public void performReceive(Intent intent, int resultCode, String data,
10419                                    Bundle extras, boolean ordered, boolean sticky, int sendingUser)
10420                                    throws RemoteException {
10421                            }
10422                        }, 0, null, null,
10423                        INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
10424                        true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
10425            } catch (Throwable t) {
10426                Slog.wtf(TAG, "Failed sending first user broadcasts", t);
10427            } finally {
10428                Binder.restoreCallingIdentity(ident);
10429            }
10430            mStackSupervisor.resumeTopActivitiesLocked();
10431            sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
10432        }
10433    }
10434
10435    private boolean makeAppCrashingLocked(ProcessRecord app,
10436            String shortMsg, String longMsg, String stackTrace) {
10437        app.crashing = true;
10438        app.crashingReport = generateProcessError(app,
10439                ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
10440        startAppProblemLocked(app);
10441        app.stopFreezingAllLocked();
10442        return handleAppCrashLocked(app, shortMsg, longMsg, stackTrace);
10443    }
10444
10445    private void makeAppNotRespondingLocked(ProcessRecord app,
10446            String activity, String shortMsg, String longMsg) {
10447        app.notResponding = true;
10448        app.notRespondingReport = generateProcessError(app,
10449                ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
10450                activity, shortMsg, longMsg, null);
10451        startAppProblemLocked(app);
10452        app.stopFreezingAllLocked();
10453    }
10454
10455    /**
10456     * Generate a process error record, suitable for attachment to a ProcessRecord.
10457     *
10458     * @param app The ProcessRecord in which the error occurred.
10459     * @param condition Crashing, Application Not Responding, etc.  Values are defined in
10460     *                      ActivityManager.AppErrorStateInfo
10461     * @param activity The activity associated with the crash, if known.
10462     * @param shortMsg Short message describing the crash.
10463     * @param longMsg Long message describing the crash.
10464     * @param stackTrace Full crash stack trace, may be null.
10465     *
10466     * @return Returns a fully-formed AppErrorStateInfo record.
10467     */
10468    private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
10469            int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
10470        ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
10471
10472        report.condition = condition;
10473        report.processName = app.processName;
10474        report.pid = app.pid;
10475        report.uid = app.info.uid;
10476        report.tag = activity;
10477        report.shortMsg = shortMsg;
10478        report.longMsg = longMsg;
10479        report.stackTrace = stackTrace;
10480
10481        return report;
10482    }
10483
10484    void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
10485        synchronized (this) {
10486            app.crashing = false;
10487            app.crashingReport = null;
10488            app.notResponding = false;
10489            app.notRespondingReport = null;
10490            if (app.anrDialog == fromDialog) {
10491                app.anrDialog = null;
10492            }
10493            if (app.waitDialog == fromDialog) {
10494                app.waitDialog = null;
10495            }
10496            if (app.pid > 0 && app.pid != MY_PID) {
10497                handleAppCrashLocked(app, null, null, null);
10498                killUnneededProcessLocked(app, "user request after error");
10499            }
10500        }
10501    }
10502
10503    private boolean handleAppCrashLocked(ProcessRecord app, String shortMsg, String longMsg,
10504            String stackTrace) {
10505        long now = SystemClock.uptimeMillis();
10506
10507        Long crashTime;
10508        if (!app.isolated) {
10509            crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
10510        } else {
10511            crashTime = null;
10512        }
10513        if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
10514            // This process loses!
10515            Slog.w(TAG, "Process " + app.info.processName
10516                    + " has crashed too many times: killing!");
10517            EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
10518                    app.userId, app.info.processName, app.uid);
10519            mStackSupervisor.handleAppCrashLocked(app);
10520            if (!app.persistent) {
10521                // We don't want to start this process again until the user
10522                // explicitly does so...  but for persistent process, we really
10523                // need to keep it running.  If a persistent process is actually
10524                // repeatedly crashing, then badness for everyone.
10525                EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
10526                        app.info.processName);
10527                if (!app.isolated) {
10528                    // XXX We don't have a way to mark isolated processes
10529                    // as bad, since they don't have a peristent identity.
10530                    mBadProcesses.put(app.info.processName, app.uid,
10531                            new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
10532                    mProcessCrashTimes.remove(app.info.processName, app.uid);
10533                }
10534                app.bad = true;
10535                app.removed = true;
10536                // Don't let services in this process be restarted and potentially
10537                // annoy the user repeatedly.  Unless it is persistent, since those
10538                // processes run critical code.
10539                removeProcessLocked(app, false, false, "crash");
10540                mStackSupervisor.resumeTopActivitiesLocked();
10541                return false;
10542            }
10543            mStackSupervisor.resumeTopActivitiesLocked();
10544        } else {
10545            mStackSupervisor.finishTopRunningActivityLocked(app);
10546        }
10547
10548        // Bump up the crash count of any services currently running in the proc.
10549        for (int i=app.services.size()-1; i>=0; i--) {
10550            // Any services running in the application need to be placed
10551            // back in the pending list.
10552            ServiceRecord sr = app.services.valueAt(i);
10553            sr.crashCount++;
10554        }
10555
10556        // If the crashing process is what we consider to be the "home process" and it has been
10557        // replaced by a third-party app, clear the package preferred activities from packages
10558        // with a home activity running in the process to prevent a repeatedly crashing app
10559        // from blocking the user to manually clear the list.
10560        final ArrayList<ActivityRecord> activities = app.activities;
10561        if (app == mHomeProcess && activities.size() > 0
10562                    && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
10563            for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
10564                final ActivityRecord r = activities.get(activityNdx);
10565                if (r.isHomeActivity()) {
10566                    Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
10567                    try {
10568                        ActivityThread.getPackageManager()
10569                                .clearPackagePreferredActivities(r.packageName);
10570                    } catch (RemoteException c) {
10571                        // pm is in same process, this will never happen.
10572                    }
10573                }
10574            }
10575        }
10576
10577        if (!app.isolated) {
10578            // XXX Can't keep track of crash times for isolated processes,
10579            // because they don't have a perisistent identity.
10580            mProcessCrashTimes.put(app.info.processName, app.uid, now);
10581        }
10582
10583        if (app.crashHandler != null) mHandler.post(app.crashHandler);
10584        return true;
10585    }
10586
10587    void startAppProblemLocked(ProcessRecord app) {
10588        if (app.userId == mCurrentUserId) {
10589            app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
10590                    mContext, app.info.packageName, app.info.flags);
10591        } else {
10592            // If this app is not running under the current user, then we
10593            // can't give it a report button because that would require
10594            // launching the report UI under a different user.
10595            app.errorReportReceiver = null;
10596        }
10597        skipCurrentReceiverLocked(app);
10598    }
10599
10600    void skipCurrentReceiverLocked(ProcessRecord app) {
10601        for (BroadcastQueue queue : mBroadcastQueues) {
10602            queue.skipCurrentReceiverLocked(app);
10603        }
10604    }
10605
10606    /**
10607     * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
10608     * The application process will exit immediately after this call returns.
10609     * @param app object of the crashing app, null for the system server
10610     * @param crashInfo describing the exception
10611     */
10612    public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
10613        ProcessRecord r = findAppProcess(app, "Crash");
10614        final String processName = app == null ? "system_server"
10615                : (r == null ? "unknown" : r.processName);
10616
10617        handleApplicationCrashInner("crash", r, processName, crashInfo);
10618    }
10619
10620    /* Native crash reporting uses this inner version because it needs to be somewhat
10621     * decoupled from the AM-managed cleanup lifecycle
10622     */
10623    void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
10624            ApplicationErrorReport.CrashInfo crashInfo) {
10625        EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
10626                UserHandle.getUserId(Binder.getCallingUid()), processName,
10627                r == null ? -1 : r.info.flags,
10628                crashInfo.exceptionClassName,
10629                crashInfo.exceptionMessage,
10630                crashInfo.throwFileName,
10631                crashInfo.throwLineNumber);
10632
10633        addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo);
10634
10635        crashApplication(r, crashInfo);
10636    }
10637
10638    public void handleApplicationStrictModeViolation(
10639            IBinder app,
10640            int violationMask,
10641            StrictMode.ViolationInfo info) {
10642        ProcessRecord r = findAppProcess(app, "StrictMode");
10643        if (r == null) {
10644            return;
10645        }
10646
10647        if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
10648            Integer stackFingerprint = info.hashCode();
10649            boolean logIt = true;
10650            synchronized (mAlreadyLoggedViolatedStacks) {
10651                if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
10652                    logIt = false;
10653                    // TODO: sub-sample into EventLog for these, with
10654                    // the info.durationMillis?  Then we'd get
10655                    // the relative pain numbers, without logging all
10656                    // the stack traces repeatedly.  We'd want to do
10657                    // likewise in the client code, which also does
10658                    // dup suppression, before the Binder call.
10659                } else {
10660                    if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
10661                        mAlreadyLoggedViolatedStacks.clear();
10662                    }
10663                    mAlreadyLoggedViolatedStacks.add(stackFingerprint);
10664                }
10665            }
10666            if (logIt) {
10667                logStrictModeViolationToDropBox(r, info);
10668            }
10669        }
10670
10671        if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
10672            AppErrorResult result = new AppErrorResult();
10673            synchronized (this) {
10674                final long origId = Binder.clearCallingIdentity();
10675
10676                Message msg = Message.obtain();
10677                msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
10678                HashMap<String, Object> data = new HashMap<String, Object>();
10679                data.put("result", result);
10680                data.put("app", r);
10681                data.put("violationMask", violationMask);
10682                data.put("info", info);
10683                msg.obj = data;
10684                mHandler.sendMessage(msg);
10685
10686                Binder.restoreCallingIdentity(origId);
10687            }
10688            int res = result.get();
10689            Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
10690        }
10691    }
10692
10693    // Depending on the policy in effect, there could be a bunch of
10694    // these in quick succession so we try to batch these together to
10695    // minimize disk writes, number of dropbox entries, and maximize
10696    // compression, by having more fewer, larger records.
10697    private void logStrictModeViolationToDropBox(
10698            ProcessRecord process,
10699            StrictMode.ViolationInfo info) {
10700        if (info == null) {
10701            return;
10702        }
10703        final boolean isSystemApp = process == null ||
10704                (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
10705                                       ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
10706        final String processName = process == null ? "unknown" : process.processName;
10707        final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
10708        final DropBoxManager dbox = (DropBoxManager)
10709                mContext.getSystemService(Context.DROPBOX_SERVICE);
10710
10711        // Exit early if the dropbox isn't configured to accept this report type.
10712        if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
10713
10714        boolean bufferWasEmpty;
10715        boolean needsFlush;
10716        final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
10717        synchronized (sb) {
10718            bufferWasEmpty = sb.length() == 0;
10719            appendDropBoxProcessHeaders(process, processName, sb);
10720            sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
10721            sb.append("System-App: ").append(isSystemApp).append("\n");
10722            sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
10723            if (info.violationNumThisLoop != 0) {
10724                sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
10725            }
10726            if (info.numAnimationsRunning != 0) {
10727                sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
10728            }
10729            if (info.broadcastIntentAction != null) {
10730                sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
10731            }
10732            if (info.durationMillis != -1) {
10733                sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
10734            }
10735            if (info.numInstances != -1) {
10736                sb.append("Instance-Count: ").append(info.numInstances).append("\n");
10737            }
10738            if (info.tags != null) {
10739                for (String tag : info.tags) {
10740                    sb.append("Span-Tag: ").append(tag).append("\n");
10741                }
10742            }
10743            sb.append("\n");
10744            if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
10745                sb.append(info.crashInfo.stackTrace);
10746            }
10747            sb.append("\n");
10748
10749            // Only buffer up to ~64k.  Various logging bits truncate
10750            // things at 128k.
10751            needsFlush = (sb.length() > 64 * 1024);
10752        }
10753
10754        // Flush immediately if the buffer's grown too large, or this
10755        // is a non-system app.  Non-system apps are isolated with a
10756        // different tag & policy and not batched.
10757        //
10758        // Batching is useful during internal testing with
10759        // StrictMode settings turned up high.  Without batching,
10760        // thousands of separate files could be created on boot.
10761        if (!isSystemApp || needsFlush) {
10762            new Thread("Error dump: " + dropboxTag) {
10763                @Override
10764                public void run() {
10765                    String report;
10766                    synchronized (sb) {
10767                        report = sb.toString();
10768                        sb.delete(0, sb.length());
10769                        sb.trimToSize();
10770                    }
10771                    if (report.length() != 0) {
10772                        dbox.addText(dropboxTag, report);
10773                    }
10774                }
10775            }.start();
10776            return;
10777        }
10778
10779        // System app batching:
10780        if (!bufferWasEmpty) {
10781            // An existing dropbox-writing thread is outstanding, so
10782            // we don't need to start it up.  The existing thread will
10783            // catch the buffer appends we just did.
10784            return;
10785        }
10786
10787        // Worker thread to both batch writes and to avoid blocking the caller on I/O.
10788        // (After this point, we shouldn't access AMS internal data structures.)
10789        new Thread("Error dump: " + dropboxTag) {
10790            @Override
10791            public void run() {
10792                // 5 second sleep to let stacks arrive and be batched together
10793                try {
10794                    Thread.sleep(5000);  // 5 seconds
10795                } catch (InterruptedException e) {}
10796
10797                String errorReport;
10798                synchronized (mStrictModeBuffer) {
10799                    errorReport = mStrictModeBuffer.toString();
10800                    if (errorReport.length() == 0) {
10801                        return;
10802                    }
10803                    mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
10804                    mStrictModeBuffer.trimToSize();
10805                }
10806                dbox.addText(dropboxTag, errorReport);
10807            }
10808        }.start();
10809    }
10810
10811    /**
10812     * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
10813     * @param app object of the crashing app, null for the system server
10814     * @param tag reported by the caller
10815     * @param crashInfo describing the context of the error
10816     * @return true if the process should exit immediately (WTF is fatal)
10817     */
10818    public boolean handleApplicationWtf(IBinder app, String tag,
10819            ApplicationErrorReport.CrashInfo crashInfo) {
10820        ProcessRecord r = findAppProcess(app, "WTF");
10821        final String processName = app == null ? "system_server"
10822                : (r == null ? "unknown" : r.processName);
10823
10824        EventLog.writeEvent(EventLogTags.AM_WTF,
10825                UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
10826                processName,
10827                r == null ? -1 : r.info.flags,
10828                tag, crashInfo.exceptionMessage);
10829
10830        addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
10831
10832        if (r != null && r.pid != Process.myPid() &&
10833                Settings.Global.getInt(mContext.getContentResolver(),
10834                        Settings.Global.WTF_IS_FATAL, 0) != 0) {
10835            crashApplication(r, crashInfo);
10836            return true;
10837        } else {
10838            return false;
10839        }
10840    }
10841
10842    /**
10843     * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
10844     * @return the corresponding {@link ProcessRecord} object, or null if none could be found
10845     */
10846    private ProcessRecord findAppProcess(IBinder app, String reason) {
10847        if (app == null) {
10848            return null;
10849        }
10850
10851        synchronized (this) {
10852            final int NP = mProcessNames.getMap().size();
10853            for (int ip=0; ip<NP; ip++) {
10854                SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip);
10855                final int NA = apps.size();
10856                for (int ia=0; ia<NA; ia++) {
10857                    ProcessRecord p = apps.valueAt(ia);
10858                    if (p.thread != null && p.thread.asBinder() == app) {
10859                        return p;
10860                    }
10861                }
10862            }
10863
10864            Slog.w(TAG, "Can't find mystery application for " + reason
10865                    + " from pid=" + Binder.getCallingPid()
10866                    + " uid=" + Binder.getCallingUid() + ": " + app);
10867            return null;
10868        }
10869    }
10870
10871    /**
10872     * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
10873     * to append various headers to the dropbox log text.
10874     */
10875    private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
10876            StringBuilder sb) {
10877        // Watchdog thread ends up invoking this function (with
10878        // a null ProcessRecord) to add the stack file to dropbox.
10879        // Do not acquire a lock on this (am) in such cases, as it
10880        // could cause a potential deadlock, if and when watchdog
10881        // is invoked due to unavailability of lock on am and it
10882        // would prevent watchdog from killing system_server.
10883        if (process == null) {
10884            sb.append("Process: ").append(processName).append("\n");
10885            return;
10886        }
10887        // Note: ProcessRecord 'process' is guarded by the service
10888        // instance.  (notably process.pkgList, which could otherwise change
10889        // concurrently during execution of this method)
10890        synchronized (this) {
10891            sb.append("Process: ").append(processName).append("\n");
10892            int flags = process.info.flags;
10893            IPackageManager pm = AppGlobals.getPackageManager();
10894            sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
10895            for (int ip=0; ip<process.pkgList.size(); ip++) {
10896                String pkg = process.pkgList.keyAt(ip);
10897                sb.append("Package: ").append(pkg);
10898                try {
10899                    PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
10900                    if (pi != null) {
10901                        sb.append(" v").append(pi.versionCode);
10902                        if (pi.versionName != null) {
10903                            sb.append(" (").append(pi.versionName).append(")");
10904                        }
10905                    }
10906                } catch (RemoteException e) {
10907                    Slog.e(TAG, "Error getting package info: " + pkg, e);
10908                }
10909                sb.append("\n");
10910            }
10911        }
10912    }
10913
10914    private static String processClass(ProcessRecord process) {
10915        if (process == null || process.pid == MY_PID) {
10916            return "system_server";
10917        } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10918            return "system_app";
10919        } else {
10920            return "data_app";
10921        }
10922    }
10923
10924    /**
10925     * Write a description of an error (crash, WTF, ANR) to the drop box.
10926     * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
10927     * @param process which caused the error, null means the system server
10928     * @param activity which triggered the error, null if unknown
10929     * @param parent activity related to the error, null if unknown
10930     * @param subject line related to the error, null if absent
10931     * @param report in long form describing the error, null if absent
10932     * @param logFile to include in the report, null if none
10933     * @param crashInfo giving an application stack trace, null if absent
10934     */
10935    public void addErrorToDropBox(String eventType,
10936            ProcessRecord process, String processName, ActivityRecord activity,
10937            ActivityRecord parent, String subject,
10938            final String report, final File logFile,
10939            final ApplicationErrorReport.CrashInfo crashInfo) {
10940        // NOTE -- this must never acquire the ActivityManagerService lock,
10941        // otherwise the watchdog may be prevented from resetting the system.
10942
10943        final String dropboxTag = processClass(process) + "_" + eventType;
10944        final DropBoxManager dbox = (DropBoxManager)
10945                mContext.getSystemService(Context.DROPBOX_SERVICE);
10946
10947        // Exit early if the dropbox isn't configured to accept this report type.
10948        if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
10949
10950        final StringBuilder sb = new StringBuilder(1024);
10951        appendDropBoxProcessHeaders(process, processName, sb);
10952        if (activity != null) {
10953            sb.append("Activity: ").append(activity.shortComponentName).append("\n");
10954        }
10955        if (parent != null && parent.app != null && parent.app.pid != process.pid) {
10956            sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
10957        }
10958        if (parent != null && parent != activity) {
10959            sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
10960        }
10961        if (subject != null) {
10962            sb.append("Subject: ").append(subject).append("\n");
10963        }
10964        sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
10965        if (Debug.isDebuggerConnected()) {
10966            sb.append("Debugger: Connected\n");
10967        }
10968        sb.append("\n");
10969
10970        // Do the rest in a worker thread to avoid blocking the caller on I/O
10971        // (After this point, we shouldn't access AMS internal data structures.)
10972        Thread worker = new Thread("Error dump: " + dropboxTag) {
10973            @Override
10974            public void run() {
10975                if (report != null) {
10976                    sb.append(report);
10977                }
10978                if (logFile != null) {
10979                    try {
10980                        sb.append(FileUtils.readTextFile(logFile, DROPBOX_MAX_SIZE,
10981                                    "\n\n[[TRUNCATED]]"));
10982                    } catch (IOException e) {
10983                        Slog.e(TAG, "Error reading " + logFile, e);
10984                    }
10985                }
10986                if (crashInfo != null && crashInfo.stackTrace != null) {
10987                    sb.append(crashInfo.stackTrace);
10988                }
10989
10990                String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
10991                int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
10992                if (lines > 0) {
10993                    sb.append("\n");
10994
10995                    // Merge several logcat streams, and take the last N lines
10996                    InputStreamReader input = null;
10997                    try {
10998                        java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
10999                                "-v", "time", "-b", "events", "-b", "system", "-b", "main",
11000                                "-t", String.valueOf(lines)).redirectErrorStream(true).start();
11001
11002                        try { logcat.getOutputStream().close(); } catch (IOException e) {}
11003                        try { logcat.getErrorStream().close(); } catch (IOException e) {}
11004                        input = new InputStreamReader(logcat.getInputStream());
11005
11006                        int num;
11007                        char[] buf = new char[8192];
11008                        while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
11009                    } catch (IOException e) {
11010                        Slog.e(TAG, "Error running logcat", e);
11011                    } finally {
11012                        if (input != null) try { input.close(); } catch (IOException e) {}
11013                    }
11014                }
11015
11016                dbox.addText(dropboxTag, sb.toString());
11017            }
11018        };
11019
11020        if (process == null) {
11021            // If process is null, we are being called from some internal code
11022            // and may be about to die -- run this synchronously.
11023            worker.run();
11024        } else {
11025            worker.start();
11026        }
11027    }
11028
11029    /**
11030     * Bring up the "unexpected error" dialog box for a crashing app.
11031     * Deal with edge cases (intercepts from instrumented applications,
11032     * ActivityController, error intent receivers, that sort of thing).
11033     * @param r the application crashing
11034     * @param crashInfo describing the failure
11035     */
11036    private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
11037        long timeMillis = System.currentTimeMillis();
11038        String shortMsg = crashInfo.exceptionClassName;
11039        String longMsg = crashInfo.exceptionMessage;
11040        String stackTrace = crashInfo.stackTrace;
11041        if (shortMsg != null && longMsg != null) {
11042            longMsg = shortMsg + ": " + longMsg;
11043        } else if (shortMsg != null) {
11044            longMsg = shortMsg;
11045        }
11046
11047        AppErrorResult result = new AppErrorResult();
11048        synchronized (this) {
11049            if (mController != null) {
11050                try {
11051                    String name = r != null ? r.processName : null;
11052                    int pid = r != null ? r.pid : Binder.getCallingPid();
11053                    int uid = r != null ? r.info.uid : Binder.getCallingUid();
11054                    if (!mController.appCrashed(name, pid,
11055                            shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
11056                        if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
11057                                && "Native crash".equals(crashInfo.exceptionClassName)) {
11058                            Slog.w(TAG, "Skip killing native crashed app " + name
11059                                    + "(" + pid + ") during testing");
11060                        } else {
11061                            Slog.w(TAG, "Force-killing crashed app " + name
11062                                    + " at watcher's request");
11063                            Process.killProcess(pid);
11064                            if (r != null) {
11065                                Process.killProcessGroup(uid, pid);
11066                            }
11067                        }
11068                        return;
11069                    }
11070                } catch (RemoteException e) {
11071                    mController = null;
11072                    Watchdog.getInstance().setActivityController(null);
11073                }
11074            }
11075
11076            final long origId = Binder.clearCallingIdentity();
11077
11078            // If this process is running instrumentation, finish it.
11079            if (r != null && r.instrumentationClass != null) {
11080                Slog.w(TAG, "Error in app " + r.processName
11081                      + " running instrumentation " + r.instrumentationClass + ":");
11082                if (shortMsg != null) Slog.w(TAG, "  " + shortMsg);
11083                if (longMsg != null) Slog.w(TAG, "  " + longMsg);
11084                Bundle info = new Bundle();
11085                info.putString("shortMsg", shortMsg);
11086                info.putString("longMsg", longMsg);
11087                finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
11088                Binder.restoreCallingIdentity(origId);
11089                return;
11090            }
11091
11092            // If we can't identify the process or it's already exceeded its crash quota,
11093            // quit right away without showing a crash dialog.
11094            if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
11095                Binder.restoreCallingIdentity(origId);
11096                return;
11097            }
11098
11099            Message msg = Message.obtain();
11100            msg.what = SHOW_ERROR_MSG;
11101            HashMap data = new HashMap();
11102            data.put("result", result);
11103            data.put("app", r);
11104            msg.obj = data;
11105            mHandler.sendMessage(msg);
11106
11107            Binder.restoreCallingIdentity(origId);
11108        }
11109
11110        int res = result.get();
11111
11112        Intent appErrorIntent = null;
11113        synchronized (this) {
11114            if (r != null && !r.isolated) {
11115                // XXX Can't keep track of crash time for isolated processes,
11116                // since they don't have a persistent identity.
11117                mProcessCrashTimes.put(r.info.processName, r.uid,
11118                        SystemClock.uptimeMillis());
11119            }
11120            if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
11121                appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
11122            }
11123        }
11124
11125        if (appErrorIntent != null) {
11126            try {
11127                mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
11128            } catch (ActivityNotFoundException e) {
11129                Slog.w(TAG, "bug report receiver dissappeared", e);
11130            }
11131        }
11132    }
11133
11134    Intent createAppErrorIntentLocked(ProcessRecord r,
11135            long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
11136        ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
11137        if (report == null) {
11138            return null;
11139        }
11140        Intent result = new Intent(Intent.ACTION_APP_ERROR);
11141        result.setComponent(r.errorReportReceiver);
11142        result.putExtra(Intent.EXTRA_BUG_REPORT, report);
11143        result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
11144        return result;
11145    }
11146
11147    private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
11148            long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
11149        if (r.errorReportReceiver == null) {
11150            return null;
11151        }
11152
11153        if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
11154            return null;
11155        }
11156
11157        ApplicationErrorReport report = new ApplicationErrorReport();
11158        report.packageName = r.info.packageName;
11159        report.installerPackageName = r.errorReportReceiver.getPackageName();
11160        report.processName = r.processName;
11161        report.time = timeMillis;
11162        report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11163
11164        if (r.crashing || r.forceCrashReport) {
11165            report.type = ApplicationErrorReport.TYPE_CRASH;
11166            report.crashInfo = crashInfo;
11167        } else if (r.notResponding) {
11168            report.type = ApplicationErrorReport.TYPE_ANR;
11169            report.anrInfo = new ApplicationErrorReport.AnrInfo();
11170
11171            report.anrInfo.activity = r.notRespondingReport.tag;
11172            report.anrInfo.cause = r.notRespondingReport.shortMsg;
11173            report.anrInfo.info = r.notRespondingReport.longMsg;
11174        }
11175
11176        return report;
11177    }
11178
11179    public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
11180        enforceNotIsolatedCaller("getProcessesInErrorState");
11181        // assume our apps are happy - lazy create the list
11182        List<ActivityManager.ProcessErrorStateInfo> errList = null;
11183
11184        final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
11185                Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
11186        int userId = UserHandle.getUserId(Binder.getCallingUid());
11187
11188        synchronized (this) {
11189
11190            // iterate across all processes
11191            for (int i=mLruProcesses.size()-1; i>=0; i--) {
11192                ProcessRecord app = mLruProcesses.get(i);
11193                if (!allUsers && app.userId != userId) {
11194                    continue;
11195                }
11196                if ((app.thread != null) && (app.crashing || app.notResponding)) {
11197                    // This one's in trouble, so we'll generate a report for it
11198                    // crashes are higher priority (in case there's a crash *and* an anr)
11199                    ActivityManager.ProcessErrorStateInfo report = null;
11200                    if (app.crashing) {
11201                        report = app.crashingReport;
11202                    } else if (app.notResponding) {
11203                        report = app.notRespondingReport;
11204                    }
11205
11206                    if (report != null) {
11207                        if (errList == null) {
11208                            errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
11209                        }
11210                        errList.add(report);
11211                    } else {
11212                        Slog.w(TAG, "Missing app error report, app = " + app.processName +
11213                                " crashing = " + app.crashing +
11214                                " notResponding = " + app.notResponding);
11215                    }
11216                }
11217            }
11218        }
11219
11220        return errList;
11221    }
11222
11223    static int procStateToImportance(int procState, int memAdj,
11224            ActivityManager.RunningAppProcessInfo currApp) {
11225        int imp = ActivityManager.RunningAppProcessInfo.procStateToImportance(procState);
11226        if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
11227            currApp.lru = memAdj;
11228        } else {
11229            currApp.lru = 0;
11230        }
11231        return imp;
11232    }
11233
11234    private void fillInProcMemInfo(ProcessRecord app,
11235            ActivityManager.RunningAppProcessInfo outInfo) {
11236        outInfo.pid = app.pid;
11237        outInfo.uid = app.info.uid;
11238        if (mHeavyWeightProcess == app) {
11239            outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
11240        }
11241        if (app.persistent) {
11242            outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
11243        }
11244        if (app.activities.size() > 0) {
11245            outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
11246        }
11247        outInfo.lastTrimLevel = app.trimMemoryLevel;
11248        int adj = app.curAdj;
11249        int procState = app.curProcState;
11250        outInfo.importance = procStateToImportance(procState, adj, outInfo);
11251        outInfo.importanceReasonCode = app.adjTypeCode;
11252        outInfo.processState = app.curProcState;
11253    }
11254
11255    public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
11256        enforceNotIsolatedCaller("getRunningAppProcesses");
11257        // Lazy instantiation of list
11258        List<ActivityManager.RunningAppProcessInfo> runList = null;
11259        final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL,
11260                Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
11261        int userId = UserHandle.getUserId(Binder.getCallingUid());
11262        synchronized (this) {
11263            // Iterate across all processes
11264            for (int i=mLruProcesses.size()-1; i>=0; i--) {
11265                ProcessRecord app = mLruProcesses.get(i);
11266                if (!allUsers && app.userId != userId) {
11267                    continue;
11268                }
11269                if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
11270                    // Generate process state info for running application
11271                    ActivityManager.RunningAppProcessInfo currApp =
11272                        new ActivityManager.RunningAppProcessInfo(app.processName,
11273                                app.pid, app.getPackageList());
11274                    fillInProcMemInfo(app, currApp);
11275                    if (app.adjSource instanceof ProcessRecord) {
11276                        currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
11277                        currApp.importanceReasonImportance =
11278                                ActivityManager.RunningAppProcessInfo.procStateToImportance(
11279                                        app.adjSourceProcState);
11280                    } else if (app.adjSource instanceof ActivityRecord) {
11281                        ActivityRecord r = (ActivityRecord)app.adjSource;
11282                        if (r.app != null) currApp.importanceReasonPid = r.app.pid;
11283                    }
11284                    if (app.adjTarget instanceof ComponentName) {
11285                        currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
11286                    }
11287                    //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
11288                    //        + " lru=" + currApp.lru);
11289                    if (runList == null) {
11290                        runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
11291                    }
11292                    runList.add(currApp);
11293                }
11294            }
11295        }
11296        return runList;
11297    }
11298
11299    public List<ApplicationInfo> getRunningExternalApplications() {
11300        enforceNotIsolatedCaller("getRunningExternalApplications");
11301        List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
11302        List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
11303        if (runningApps != null && runningApps.size() > 0) {
11304            Set<String> extList = new HashSet<String>();
11305            for (ActivityManager.RunningAppProcessInfo app : runningApps) {
11306                if (app.pkgList != null) {
11307                    for (String pkg : app.pkgList) {
11308                        extList.add(pkg);
11309                    }
11310                }
11311            }
11312            IPackageManager pm = AppGlobals.getPackageManager();
11313            for (String pkg : extList) {
11314                try {
11315                    ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
11316                    if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
11317                        retList.add(info);
11318                    }
11319                } catch (RemoteException e) {
11320                }
11321            }
11322        }
11323        return retList;
11324    }
11325
11326    @Override
11327    public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
11328        enforceNotIsolatedCaller("getMyMemoryState");
11329        synchronized (this) {
11330            ProcessRecord proc;
11331            synchronized (mPidsSelfLocked) {
11332                proc = mPidsSelfLocked.get(Binder.getCallingPid());
11333            }
11334            fillInProcMemInfo(proc, outInfo);
11335        }
11336    }
11337
11338    @Override
11339    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11340        if (checkCallingPermission(android.Manifest.permission.DUMP)
11341                != PackageManager.PERMISSION_GRANTED) {
11342            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11343                    + Binder.getCallingPid()
11344                    + ", uid=" + Binder.getCallingUid()
11345                    + " without permission "
11346                    + android.Manifest.permission.DUMP);
11347            return;
11348        }
11349
11350        boolean dumpAll = false;
11351        boolean dumpClient = false;
11352        String dumpPackage = null;
11353
11354        int opti = 0;
11355        while (opti < args.length) {
11356            String opt = args[opti];
11357            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11358                break;
11359            }
11360            opti++;
11361            if ("-a".equals(opt)) {
11362                dumpAll = true;
11363            } else if ("-c".equals(opt)) {
11364                dumpClient = true;
11365            } else if ("-h".equals(opt)) {
11366                pw.println("Activity manager dump options:");
11367                pw.println("  [-a] [-c] [-h] [cmd] ...");
11368                pw.println("  cmd may be one of:");
11369                pw.println("    a[ctivities]: activity stack state");
11370                pw.println("    b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
11371                pw.println("    i[ntents] [PACKAGE_NAME]: pending intent state");
11372                pw.println("    p[rocesses] [PACKAGE_NAME]: process state");
11373                pw.println("    o[om]: out of memory management");
11374                pw.println("    prov[iders] [COMP_SPEC ...]: content provider state");
11375                pw.println("    provider [COMP_SPEC]: provider client-side state");
11376                pw.println("    s[ervices] [COMP_SPEC ...]: service state");
11377                pw.println("    service [COMP_SPEC]: service client-side state");
11378                pw.println("    package [PACKAGE_NAME]: all state related to given package");
11379                pw.println("    all: dump all activities");
11380                pw.println("    top: dump the top activity");
11381                pw.println("  cmd may also be a COMP_SPEC to dump activities.");
11382                pw.println("  COMP_SPEC may be a component name (com.foo/.myApp),");
11383                pw.println("    a partial substring in a component name, a");
11384                pw.println("    hex object identifier.");
11385                pw.println("  -a: include all available server state.");
11386                pw.println("  -c: include client state.");
11387                return;
11388            } else {
11389                pw.println("Unknown argument: " + opt + "; use -h for help");
11390            }
11391        }
11392
11393        long origId = Binder.clearCallingIdentity();
11394        boolean more = false;
11395        // Is the caller requesting to dump a particular piece of data?
11396        if (opti < args.length) {
11397            String cmd = args[opti];
11398            opti++;
11399            if ("activities".equals(cmd) || "a".equals(cmd)) {
11400                synchronized (this) {
11401                    dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
11402                }
11403            } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
11404                String[] newArgs;
11405                String name;
11406                if (opti >= args.length) {
11407                    name = null;
11408                    newArgs = EMPTY_STRING_ARRAY;
11409                } else {
11410                    name = args[opti];
11411                    opti++;
11412                    newArgs = new String[args.length - opti];
11413                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
11414                            args.length - opti);
11415                }
11416                synchronized (this) {
11417                    dumpBroadcastsLocked(fd, pw, args, opti, true, name);
11418                }
11419            } else if ("intents".equals(cmd) || "i".equals(cmd)) {
11420                String[] newArgs;
11421                String name;
11422                if (opti >= args.length) {
11423                    name = null;
11424                    newArgs = EMPTY_STRING_ARRAY;
11425                } else {
11426                    name = args[opti];
11427                    opti++;
11428                    newArgs = new String[args.length - opti];
11429                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
11430                            args.length - opti);
11431                }
11432                synchronized (this) {
11433                    dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
11434                }
11435            } else if ("processes".equals(cmd) || "p".equals(cmd)) {
11436                String[] newArgs;
11437                String name;
11438                if (opti >= args.length) {
11439                    name = null;
11440                    newArgs = EMPTY_STRING_ARRAY;
11441                } else {
11442                    name = args[opti];
11443                    opti++;
11444                    newArgs = new String[args.length - opti];
11445                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
11446                            args.length - opti);
11447                }
11448                synchronized (this) {
11449                    dumpProcessesLocked(fd, pw, args, opti, true, name);
11450                }
11451            } else if ("oom".equals(cmd) || "o".equals(cmd)) {
11452                synchronized (this) {
11453                    dumpOomLocked(fd, pw, args, opti, true);
11454                }
11455            } else if ("provider".equals(cmd)) {
11456                String[] newArgs;
11457                String name;
11458                if (opti >= args.length) {
11459                    name = null;
11460                    newArgs = EMPTY_STRING_ARRAY;
11461                } else {
11462                    name = args[opti];
11463                    opti++;
11464                    newArgs = new String[args.length - opti];
11465                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
11466                }
11467                if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
11468                    pw.println("No providers match: " + name);
11469                    pw.println("Use -h for help.");
11470                }
11471            } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
11472                synchronized (this) {
11473                    dumpProvidersLocked(fd, pw, args, opti, true, null);
11474                }
11475            } else if ("service".equals(cmd)) {
11476                String[] newArgs;
11477                String name;
11478                if (opti >= args.length) {
11479                    name = null;
11480                    newArgs = EMPTY_STRING_ARRAY;
11481                } else {
11482                    name = args[opti];
11483                    opti++;
11484                    newArgs = new String[args.length - opti];
11485                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
11486                            args.length - opti);
11487                }
11488                if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
11489                    pw.println("No services match: " + name);
11490                    pw.println("Use -h for help.");
11491                }
11492            } else if ("package".equals(cmd)) {
11493                String[] newArgs;
11494                if (opti >= args.length) {
11495                    pw.println("package: no package name specified");
11496                    pw.println("Use -h for help.");
11497                } else {
11498                    dumpPackage = args[opti];
11499                    opti++;
11500                    newArgs = new String[args.length - opti];
11501                    if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
11502                            args.length - opti);
11503                    args = newArgs;
11504                    opti = 0;
11505                    more = true;
11506                }
11507            } else if ("services".equals(cmd) || "s".equals(cmd)) {
11508                synchronized (this) {
11509                    mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
11510                }
11511            } else {
11512                // Dumping a single activity?
11513                if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
11514                    pw.println("Bad activity command, or no activities match: " + cmd);
11515                    pw.println("Use -h for help.");
11516                }
11517            }
11518            if (!more) {
11519                Binder.restoreCallingIdentity(origId);
11520                return;
11521            }
11522        }
11523
11524        // No piece of data specified, dump everything.
11525        synchronized (this) {
11526            dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
11527            pw.println();
11528            if (dumpAll) {
11529                pw.println("-------------------------------------------------------------------------------");
11530            }
11531            dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
11532            pw.println();
11533            if (dumpAll) {
11534                pw.println("-------------------------------------------------------------------------------");
11535            }
11536            dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
11537            pw.println();
11538            if (dumpAll) {
11539                pw.println("-------------------------------------------------------------------------------");
11540            }
11541            mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
11542            pw.println();
11543            if (dumpAll) {
11544                pw.println("-------------------------------------------------------------------------------");
11545            }
11546            dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
11547            pw.println();
11548            if (dumpAll) {
11549                pw.println("-------------------------------------------------------------------------------");
11550            }
11551            dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
11552        }
11553        Binder.restoreCallingIdentity(origId);
11554    }
11555
11556    void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11557            int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
11558        pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
11559
11560        boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient,
11561                dumpPackage);
11562        boolean needSep = printedAnything;
11563
11564        boolean printed = ActivityStackSupervisor.printThisActivity(pw, mFocusedActivity,
11565                dumpPackage, needSep, "  mFocusedActivity: ");
11566        if (printed) {
11567            printedAnything = true;
11568            needSep = false;
11569        }
11570
11571        if (dumpPackage == null) {
11572            if (needSep) {
11573                pw.println();
11574            }
11575            needSep = true;
11576            printedAnything = true;
11577            mStackSupervisor.dump(pw, "  ");
11578        }
11579
11580        if (mRecentTasks.size() > 0) {
11581            boolean printedHeader = false;
11582
11583            final int N = mRecentTasks.size();
11584            for (int i=0; i<N; i++) {
11585                TaskRecord tr = mRecentTasks.get(i);
11586                if (dumpPackage != null) {
11587                    if (tr.realActivity == null ||
11588                            !dumpPackage.equals(tr.realActivity)) {
11589                        continue;
11590                    }
11591                }
11592                if (!printedHeader) {
11593                    if (needSep) {
11594                        pw.println();
11595                    }
11596                    pw.println("  Recent tasks:");
11597                    printedHeader = true;
11598                    printedAnything = true;
11599                }
11600                pw.print("  * Recent #"); pw.print(i); pw.print(": ");
11601                        pw.println(tr);
11602                if (dumpAll) {
11603                    mRecentTasks.get(i).dump(pw, "    ");
11604                }
11605            }
11606        }
11607
11608        if (!printedAnything) {
11609            pw.println("  (nothing)");
11610        }
11611    }
11612
11613    void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
11614            int opti, boolean dumpAll, String dumpPackage) {
11615        boolean needSep = false;
11616        boolean printedAnything = false;
11617        int numPers = 0;
11618
11619        pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
11620
11621        if (dumpAll) {
11622            final int NP = mProcessNames.getMap().size();
11623            for (int ip=0; ip<NP; ip++) {
11624                SparseArray<ProcessRecord> procs = mProcessNames.getMap().valueAt(ip);
11625                final int NA = procs.size();
11626                for (int ia=0; ia<NA; ia++) {
11627                    ProcessRecord r = procs.valueAt(ia);
11628                    if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11629                        continue;
11630                    }
11631                    if (!needSep) {
11632                        pw.println("  All known processes:");
11633                        needSep = true;
11634                        printedAnything = true;
11635                    }
11636                    pw.print(r.persistent ? "  *PERS*" : "  *APP*");
11637                        pw.print(" UID "); pw.print(procs.keyAt(ia));
11638                        pw.print(" "); pw.println(r);
11639                    r.dump(pw, "    ");
11640                    if (r.persistent) {
11641                        numPers++;
11642                    }
11643                }
11644            }
11645        }
11646
11647        if (mIsolatedProcesses.size() > 0) {
11648            boolean printed = false;
11649            for (int i=0; i<mIsolatedProcesses.size(); i++) {
11650                ProcessRecord r = mIsolatedProcesses.valueAt(i);
11651                if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11652                    continue;
11653                }
11654                if (!printed) {
11655                    if (needSep) {
11656                        pw.println();
11657                    }
11658                    pw.println("  Isolated process list (sorted by uid):");
11659                    printedAnything = true;
11660                    printed = true;
11661                    needSep = true;
11662                }
11663                pw.println(String.format("%sIsolated #%2d: %s",
11664                        "    ", i, r.toString()));
11665            }
11666        }
11667
11668        if (mLruProcesses.size() > 0) {
11669            if (needSep) {
11670                pw.println();
11671            }
11672            pw.print("  Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size());
11673                    pw.print(" total, non-act at ");
11674                    pw.print(mLruProcesses.size()-mLruProcessActivityStart);
11675                    pw.print(", non-svc at ");
11676                    pw.print(mLruProcesses.size()-mLruProcessServiceStart);
11677                    pw.println("):");
11678            dumpProcessOomList(pw, this, mLruProcesses, "    ", "Proc", "PERS", false, dumpPackage);
11679            needSep = true;
11680            printedAnything = true;
11681        }
11682
11683        if (dumpAll || dumpPackage != null) {
11684            synchronized (mPidsSelfLocked) {
11685                boolean printed = false;
11686                for (int i=0; i<mPidsSelfLocked.size(); i++) {
11687                    ProcessRecord r = mPidsSelfLocked.valueAt(i);
11688                    if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
11689                        continue;
11690                    }
11691                    if (!printed) {
11692                        if (needSep) pw.println();
11693                        needSep = true;
11694                        pw.println("  PID mappings:");
11695                        printed = true;
11696                        printedAnything = true;
11697                    }
11698                    pw.print("    PID #"); pw.print(mPidsSelfLocked.keyAt(i));
11699                        pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
11700                }
11701            }
11702        }
11703
11704        if (mForegroundProcesses.size() > 0) {
11705            synchronized (mPidsSelfLocked) {
11706                boolean printed = false;
11707                for (int i=0; i<mForegroundProcesses.size(); i++) {
11708                    ProcessRecord r = mPidsSelfLocked.get(
11709                            mForegroundProcesses.valueAt(i).pid);
11710                    if (dumpPackage != null && (r == null
11711                            || !r.pkgList.containsKey(dumpPackage))) {
11712                        continue;
11713                    }
11714                    if (!printed) {
11715                        if (needSep) pw.println();
11716                        needSep = true;
11717                        pw.println("  Foreground Processes:");
11718                        printed = true;
11719                        printedAnything = true;
11720                    }
11721                    pw.print("    PID #"); pw.print(mForegroundProcesses.keyAt(i));
11722                            pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
11723                }
11724            }
11725        }
11726
11727        if (mPersistentStartingProcesses.size() > 0) {
11728            if (needSep) pw.println();
11729            needSep = true;
11730            printedAnything = true;
11731            pw.println("  Persisent processes that are starting:");
11732            dumpProcessList(pw, this, mPersistentStartingProcesses, "    ",
11733                    "Starting Norm", "Restarting PERS", dumpPackage);
11734        }
11735
11736        if (mRemovedProcesses.size() > 0) {
11737            if (needSep) pw.println();
11738            needSep = true;
11739            printedAnything = true;
11740            pw.println("  Processes that are being removed:");
11741            dumpProcessList(pw, this, mRemovedProcesses, "    ",
11742                    "Removed Norm", "Removed PERS", dumpPackage);
11743        }
11744
11745        if (mProcessesOnHold.size() > 0) {
11746            if (needSep) pw.println();
11747            needSep = true;
11748            printedAnything = true;
11749            pw.println("  Processes that are on old until the system is ready:");
11750            dumpProcessList(pw, this, mProcessesOnHold, "    ",
11751                    "OnHold Norm", "OnHold PERS", dumpPackage);
11752        }
11753
11754        needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
11755
11756        if (mProcessCrashTimes.getMap().size() > 0) {
11757            boolean printed = false;
11758            long now = SystemClock.uptimeMillis();
11759            final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
11760            final int NP = pmap.size();
11761            for (int ip=0; ip<NP; ip++) {
11762                String pname = pmap.keyAt(ip);
11763                SparseArray<Long> uids = pmap.valueAt(ip);
11764                final int N = uids.size();
11765                for (int i=0; i<N; i++) {
11766                    int puid = uids.keyAt(i);
11767                    ProcessRecord r = mProcessNames.get(pname, puid);
11768                    if (dumpPackage != null && (r == null
11769                            || !r.pkgList.containsKey(dumpPackage))) {
11770                        continue;
11771                    }
11772                    if (!printed) {
11773                        if (needSep) pw.println();
11774                        needSep = true;
11775                        pw.println("  Time since processes crashed:");
11776                        printed = true;
11777                        printedAnything = true;
11778                    }
11779                    pw.print("    Process "); pw.print(pname);
11780                            pw.print(" uid "); pw.print(puid);
11781                            pw.print(": last crashed ");
11782                            TimeUtils.formatDuration(now-uids.valueAt(i), pw);
11783                            pw.println(" ago");
11784                }
11785            }
11786        }
11787
11788        if (mBadProcesses.getMap().size() > 0) {
11789            boolean printed = false;
11790            final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap();
11791            final int NP = pmap.size();
11792            for (int ip=0; ip<NP; ip++) {
11793                String pname = pmap.keyAt(ip);
11794                SparseArray<BadProcessInfo> uids = pmap.valueAt(ip);
11795                final int N = uids.size();
11796                for (int i=0; i<N; i++) {
11797                    int puid = uids.keyAt(i);
11798                    ProcessRecord r = mProcessNames.get(pname, puid);
11799                    if (dumpPackage != null && (r == null
11800                            || !r.pkgList.containsKey(dumpPackage))) {
11801                        continue;
11802                    }
11803                    if (!printed) {
11804                        if (needSep) pw.println();
11805                        needSep = true;
11806                        pw.println("  Bad processes:");
11807                        printedAnything = true;
11808                    }
11809                    BadProcessInfo info = uids.valueAt(i);
11810                    pw.print("    Bad process "); pw.print(pname);
11811                            pw.print(" uid "); pw.print(puid);
11812                            pw.print(": crashed at time "); pw.println(info.time);
11813                    if (info.shortMsg != null) {
11814                        pw.print("      Short msg: "); pw.println(info.shortMsg);
11815                    }
11816                    if (info.longMsg != null) {
11817                        pw.print("      Long msg: "); pw.println(info.longMsg);
11818                    }
11819                    if (info.stack != null) {
11820                        pw.println("      Stack:");
11821                        int lastPos = 0;
11822                        for (int pos=0; pos<info.stack.length(); pos++) {
11823                            if (info.stack.charAt(pos) == '\n') {
11824                                pw.print("        ");
11825                                pw.write(info.stack, lastPos, pos-lastPos);
11826                                pw.println();
11827                                lastPos = pos+1;
11828                            }
11829                        }
11830                        if (lastPos < info.stack.length()) {
11831                            pw.print("        ");
11832                            pw.write(info.stack, lastPos, info.stack.length()-lastPos);
11833                            pw.println();
11834                        }
11835                    }
11836                }
11837            }
11838        }
11839
11840        if (dumpPackage == null) {
11841            pw.println();
11842            needSep = false;
11843            pw.println("  mStartedUsers:");
11844            for (int i=0; i<mStartedUsers.size(); i++) {
11845                UserStartedState uss = mStartedUsers.valueAt(i);
11846                pw.print("    User #"); pw.print(uss.mHandle.getIdentifier());
11847                        pw.print(": "); uss.dump("", pw);
11848            }
11849            pw.print("  mStartedUserArray: [");
11850            for (int i=0; i<mStartedUserArray.length; i++) {
11851                if (i > 0) pw.print(", ");
11852                pw.print(mStartedUserArray[i]);
11853            }
11854            pw.println("]");
11855            pw.print("  mUserLru: [");
11856            for (int i=0; i<mUserLru.size(); i++) {
11857                if (i > 0) pw.print(", ");
11858                pw.print(mUserLru.get(i));
11859            }
11860            pw.println("]");
11861            if (dumpAll) {
11862                pw.print("  mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
11863            }
11864            synchronized (mUserProfileGroupIdsSelfLocked) {
11865                if (mUserProfileGroupIdsSelfLocked.size() > 0) {
11866                    pw.println("  mUserProfileGroupIds:");
11867                    for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
11868                        pw.print("    User #");
11869                        pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
11870                        pw.print(" -> profile #");
11871                        pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
11872                    }
11873                }
11874            }
11875        }
11876        if (mHomeProcess != null && (dumpPackage == null
11877                || mHomeProcess.pkgList.containsKey(dumpPackage))) {
11878            if (needSep) {
11879                pw.println();
11880                needSep = false;
11881            }
11882            pw.println("  mHomeProcess: " + mHomeProcess);
11883        }
11884        if (mPreviousProcess != null && (dumpPackage == null
11885                || mPreviousProcess.pkgList.containsKey(dumpPackage))) {
11886            if (needSep) {
11887                pw.println();
11888                needSep = false;
11889            }
11890            pw.println("  mPreviousProcess: " + mPreviousProcess);
11891        }
11892        if (dumpAll) {
11893            StringBuilder sb = new StringBuilder(128);
11894            sb.append("  mPreviousProcessVisibleTime: ");
11895            TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
11896            pw.println(sb);
11897        }
11898        if (mHeavyWeightProcess != null && (dumpPackage == null
11899                || mHeavyWeightProcess.pkgList.containsKey(dumpPackage))) {
11900            if (needSep) {
11901                pw.println();
11902                needSep = false;
11903            }
11904            pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
11905        }
11906        if (dumpPackage == null) {
11907            pw.println("  mConfiguration: " + mConfiguration);
11908        }
11909        if (dumpAll) {
11910            pw.println("  mConfigWillChange: " + getFocusedStack().mConfigWillChange);
11911            if (mCompatModePackages.getPackages().size() > 0) {
11912                boolean printed = false;
11913                for (Map.Entry<String, Integer> entry
11914                        : mCompatModePackages.getPackages().entrySet()) {
11915                    String pkg = entry.getKey();
11916                    int mode = entry.getValue();
11917                    if (dumpPackage != null && !dumpPackage.equals(pkg)) {
11918                        continue;
11919                    }
11920                    if (!printed) {
11921                        pw.println("  mScreenCompatPackages:");
11922                        printed = true;
11923                    }
11924                    pw.print("    "); pw.print(pkg); pw.print(": ");
11925                            pw.print(mode); pw.println();
11926                }
11927            }
11928        }
11929        if (dumpPackage == null) {
11930            if (mSleeping || mWentToSleep || mLockScreenShown) {
11931                pw.println("  mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
11932                        + " mLockScreenShown " + mLockScreenShown);
11933            }
11934            if (mShuttingDown || mRunningVoice) {
11935                pw.print("  mShuttingDown=" + mShuttingDown + " mRunningVoice=" + mRunningVoice);
11936            }
11937        }
11938        if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
11939                || mOrigWaitForDebugger) {
11940            if (dumpPackage == null || dumpPackage.equals(mDebugApp)
11941                    || dumpPackage.equals(mOrigDebugApp)) {
11942                if (needSep) {
11943                    pw.println();
11944                    needSep = false;
11945                }
11946                pw.println("  mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
11947                        + " mDebugTransient=" + mDebugTransient
11948                        + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
11949            }
11950        }
11951        if (mOpenGlTraceApp != null) {
11952            if (dumpPackage == null || dumpPackage.equals(mOpenGlTraceApp)) {
11953                if (needSep) {
11954                    pw.println();
11955                    needSep = false;
11956                }
11957                pw.println("  mOpenGlTraceApp=" + mOpenGlTraceApp);
11958            }
11959        }
11960        if (mProfileApp != null || mProfileProc != null || mProfileFile != null
11961                || mProfileFd != null) {
11962            if (dumpPackage == null || dumpPackage.equals(mProfileApp)) {
11963                if (needSep) {
11964                    pw.println();
11965                    needSep = false;
11966                }
11967                pw.println("  mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
11968                pw.println("  mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
11969                pw.println("  mProfileType=" + mProfileType + " mAutoStopProfiler="
11970                        + mAutoStopProfiler);
11971            }
11972        }
11973        if (dumpPackage == null) {
11974            if (mAlwaysFinishActivities || mController != null) {
11975                pw.println("  mAlwaysFinishActivities=" + mAlwaysFinishActivities
11976                        + " mController=" + mController);
11977            }
11978            if (dumpAll) {
11979                pw.println("  Total persistent processes: " + numPers);
11980                pw.println("  mProcessesReady=" + mProcessesReady
11981                        + " mSystemReady=" + mSystemReady);
11982                pw.println("  mBooting=" + mBooting
11983                        + " mBooted=" + mBooted
11984                        + " mFactoryTest=" + mFactoryTest);
11985                pw.print("  mLastPowerCheckRealtime=");
11986                        TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
11987                        pw.println("");
11988                pw.print("  mLastPowerCheckUptime=");
11989                        TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
11990                        pw.println("");
11991                pw.println("  mGoingToSleep=" + mStackSupervisor.mGoingToSleep);
11992                pw.println("  mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity);
11993                pw.println("  mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
11994                pw.println("  mNumNonCachedProcs=" + mNumNonCachedProcs
11995                        + " (" + mLruProcesses.size() + " total)"
11996                        + " mNumCachedHiddenProcs=" + mNumCachedHiddenProcs
11997                        + " mNumServiceProcs=" + mNumServiceProcs
11998                        + " mNewNumServiceProcs=" + mNewNumServiceProcs);
11999                pw.println("  mAllowLowerMemLevel=" + mAllowLowerMemLevel
12000                        + " mLastMemoryLevel" + mLastMemoryLevel
12001                        + " mLastNumProcesses" + mLastNumProcesses);
12002                long now = SystemClock.uptimeMillis();
12003                pw.print("  mLastIdleTime=");
12004                        TimeUtils.formatDuration(now, mLastIdleTime, pw);
12005                        pw.print(" mLowRamSinceLastIdle=");
12006                        TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw);
12007                        pw.println();
12008            }
12009        }
12010
12011        if (!printedAnything) {
12012            pw.println("  (nothing)");
12013        }
12014    }
12015
12016    boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
12017            int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
12018        if (mProcessesToGc.size() > 0) {
12019            boolean printed = false;
12020            long now = SystemClock.uptimeMillis();
12021            for (int i=0; i<mProcessesToGc.size(); i++) {
12022                ProcessRecord proc = mProcessesToGc.get(i);
12023                if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
12024                    continue;
12025                }
12026                if (!printed) {
12027                    if (needSep) pw.println();
12028                    needSep = true;
12029                    pw.println("  Processes that are waiting to GC:");
12030                    printed = true;
12031                }
12032                pw.print("    Process "); pw.println(proc);
12033                pw.print("      lowMem="); pw.print(proc.reportLowMemory);
12034                        pw.print(", last gced=");
12035                        pw.print(now-proc.lastRequestedGc);
12036                        pw.print(" ms ago, last lowMem=");
12037                        pw.print(now-proc.lastLowMemory);
12038                        pw.println(" ms ago");
12039
12040            }
12041        }
12042        return needSep;
12043    }
12044
12045    void printOomLevel(PrintWriter pw, String name, int adj) {
12046        pw.print("    ");
12047        if (adj >= 0) {
12048            pw.print(' ');
12049            if (adj < 10) pw.print(' ');
12050        } else {
12051            if (adj > -10) pw.print(' ');
12052        }
12053        pw.print(adj);
12054        pw.print(": ");
12055        pw.print(name);
12056        pw.print(" (");
12057        pw.print(mProcessList.getMemLevel(adj)/1024);
12058        pw.println(" kB)");
12059    }
12060
12061    boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12062            int opti, boolean dumpAll) {
12063        boolean needSep = false;
12064
12065        if (mLruProcesses.size() > 0) {
12066            if (needSep) pw.println();
12067            needSep = true;
12068            pw.println("  OOM levels:");
12069            printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ);
12070            printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ);
12071            printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ);
12072            printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ);
12073            printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ);
12074            printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ);
12075            printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ);
12076            printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ);
12077            printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ);
12078            printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ);
12079            printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ);
12080            printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ);
12081            printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ);
12082
12083            if (needSep) pw.println();
12084            pw.print("  Process OOM control ("); pw.print(mLruProcesses.size());
12085                    pw.print(" total, non-act at ");
12086                    pw.print(mLruProcesses.size()-mLruProcessActivityStart);
12087                    pw.print(", non-svc at ");
12088                    pw.print(mLruProcesses.size()-mLruProcessServiceStart);
12089                    pw.println("):");
12090            dumpProcessOomList(pw, this, mLruProcesses, "    ", "Proc", "PERS", true, null);
12091            needSep = true;
12092        }
12093
12094        dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
12095
12096        pw.println();
12097        pw.println("  mHomeProcess: " + mHomeProcess);
12098        pw.println("  mPreviousProcess: " + mPreviousProcess);
12099        if (mHeavyWeightProcess != null) {
12100            pw.println("  mHeavyWeightProcess: " + mHeavyWeightProcess);
12101        }
12102
12103        return true;
12104    }
12105
12106    /**
12107     * There are three ways to call this:
12108     *  - no provider specified: dump all the providers
12109     *  - a flattened component name that matched an existing provider was specified as the
12110     *    first arg: dump that one provider
12111     *  - the first arg isn't the flattened component name of an existing provider:
12112     *    dump all providers whose component contains the first arg as a substring
12113     */
12114    protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
12115            int opti, boolean dumpAll) {
12116        return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
12117    }
12118
12119    static class ItemMatcher {
12120        ArrayList<ComponentName> components;
12121        ArrayList<String> strings;
12122        ArrayList<Integer> objects;
12123        boolean all;
12124
12125        ItemMatcher() {
12126            all = true;
12127        }
12128
12129        void build(String name) {
12130            ComponentName componentName = ComponentName.unflattenFromString(name);
12131            if (componentName != null) {
12132                if (components == null) {
12133                    components = new ArrayList<ComponentName>();
12134                }
12135                components.add(componentName);
12136                all = false;
12137            } else {
12138                int objectId = 0;
12139                // Not a '/' separated full component name; maybe an object ID?
12140                try {
12141                    objectId = Integer.parseInt(name, 16);
12142                    if (objects == null) {
12143                        objects = new ArrayList<Integer>();
12144                    }
12145                    objects.add(objectId);
12146                    all = false;
12147                } catch (RuntimeException e) {
12148                    // Not an integer; just do string match.
12149                    if (strings == null) {
12150                        strings = new ArrayList<String>();
12151                    }
12152                    strings.add(name);
12153                    all = false;
12154                }
12155            }
12156        }
12157
12158        int build(String[] args, int opti) {
12159            for (; opti<args.length; opti++) {
12160                String name = args[opti];
12161                if ("--".equals(name)) {
12162                    return opti+1;
12163                }
12164                build(name);
12165            }
12166            return opti;
12167        }
12168
12169        boolean match(Object object, ComponentName comp) {
12170            if (all) {
12171                return true;
12172            }
12173            if (components != null) {
12174                for (int i=0; i<components.size(); i++) {
12175                    if (components.get(i).equals(comp)) {
12176                        return true;
12177                    }
12178                }
12179            }
12180            if (objects != null) {
12181                for (int i=0; i<objects.size(); i++) {
12182                    if (System.identityHashCode(object) == objects.get(i)) {
12183                        return true;
12184                    }
12185                }
12186            }
12187            if (strings != null) {
12188                String flat = comp.flattenToString();
12189                for (int i=0; i<strings.size(); i++) {
12190                    if (flat.contains(strings.get(i))) {
12191                        return true;
12192                    }
12193                }
12194            }
12195            return false;
12196        }
12197    }
12198
12199    /**
12200     * There are three things that cmd can be:
12201     *  - a flattened component name that matches an existing activity
12202     *  - the cmd arg isn't the flattened component name of an existing activity:
12203     *    dump all activity whose component contains the cmd as a substring
12204     *  - A hex number of the ActivityRecord object instance.
12205     */
12206    protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
12207            int opti, boolean dumpAll) {
12208        ArrayList<ActivityRecord> activities;
12209
12210        synchronized (this) {
12211            activities = mStackSupervisor.getDumpActivitiesLocked(name);
12212        }
12213
12214        if (activities.size() <= 0) {
12215            return false;
12216        }
12217
12218        String[] newArgs = new String[args.length - opti];
12219        System.arraycopy(args, opti, newArgs, 0, args.length - opti);
12220
12221        TaskRecord lastTask = null;
12222        boolean needSep = false;
12223        for (int i=activities.size()-1; i>=0; i--) {
12224            ActivityRecord r = activities.get(i);
12225            if (needSep) {
12226                pw.println();
12227            }
12228            needSep = true;
12229            synchronized (this) {
12230                if (lastTask != r.task) {
12231                    lastTask = r.task;
12232                    pw.print("TASK "); pw.print(lastTask.affinity);
12233                            pw.print(" id="); pw.println(lastTask.taskId);
12234                    if (dumpAll) {
12235                        lastTask.dump(pw, "  ");
12236                    }
12237                }
12238            }
12239            dumpActivity("  ", fd, pw, activities.get(i), newArgs, dumpAll);
12240        }
12241        return true;
12242    }
12243
12244    /**
12245     * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
12246     * there is a thread associated with the activity.
12247     */
12248    private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
12249            final ActivityRecord r, String[] args, boolean dumpAll) {
12250        String innerPrefix = prefix + "  ";
12251        synchronized (this) {
12252            pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
12253                    pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
12254                    pw.print(" pid=");
12255                    if (r.app != null) pw.println(r.app.pid);
12256                    else pw.println("(not running)");
12257            if (dumpAll) {
12258                r.dump(pw, innerPrefix);
12259            }
12260        }
12261        if (r.app != null && r.app.thread != null) {
12262            // flush anything that is already in the PrintWriter since the thread is going
12263            // to write to the file descriptor directly
12264            pw.flush();
12265            try {
12266                TransferPipe tp = new TransferPipe();
12267                try {
12268                    r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
12269                            r.appToken, innerPrefix, args);
12270                    tp.go(fd);
12271                } finally {
12272                    tp.kill();
12273                }
12274            } catch (IOException e) {
12275                pw.println(innerPrefix + "Failure while dumping the activity: " + e);
12276            } catch (RemoteException e) {
12277                pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
12278            }
12279        }
12280    }
12281
12282    void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12283            int opti, boolean dumpAll, String dumpPackage) {
12284        boolean needSep = false;
12285        boolean onlyHistory = false;
12286        boolean printedAnything = false;
12287
12288        if ("history".equals(dumpPackage)) {
12289            if (opti < args.length && "-s".equals(args[opti])) {
12290                dumpAll = false;
12291            }
12292            onlyHistory = true;
12293            dumpPackage = null;
12294        }
12295
12296        pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
12297        if (!onlyHistory && dumpAll) {
12298            if (mRegisteredReceivers.size() > 0) {
12299                boolean printed = false;
12300                Iterator it = mRegisteredReceivers.values().iterator();
12301                while (it.hasNext()) {
12302                    ReceiverList r = (ReceiverList)it.next();
12303                    if (dumpPackage != null && (r.app == null ||
12304                            !dumpPackage.equals(r.app.info.packageName))) {
12305                        continue;
12306                    }
12307                    if (!printed) {
12308                        pw.println("  Registered Receivers:");
12309                        needSep = true;
12310                        printed = true;
12311                        printedAnything = true;
12312                    }
12313                    pw.print("  * "); pw.println(r);
12314                    r.dump(pw, "    ");
12315                }
12316            }
12317
12318            if (mReceiverResolver.dump(pw, needSep ?
12319                    "\n  Receiver Resolver Table:" : "  Receiver Resolver Table:",
12320                    "    ", dumpPackage, false)) {
12321                needSep = true;
12322                printedAnything = true;
12323            }
12324        }
12325
12326        for (BroadcastQueue q : mBroadcastQueues) {
12327            needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
12328            printedAnything |= needSep;
12329        }
12330
12331        needSep = true;
12332
12333        if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
12334            for (int user=0; user<mStickyBroadcasts.size(); user++) {
12335                if (needSep) {
12336                    pw.println();
12337                }
12338                needSep = true;
12339                printedAnything = true;
12340                pw.print("  Sticky broadcasts for user ");
12341                        pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
12342                StringBuilder sb = new StringBuilder(128);
12343                for (Map.Entry<String, ArrayList<Intent>> ent
12344                        : mStickyBroadcasts.valueAt(user).entrySet()) {
12345                    pw.print("  * Sticky action "); pw.print(ent.getKey());
12346                    if (dumpAll) {
12347                        pw.println(":");
12348                        ArrayList<Intent> intents = ent.getValue();
12349                        final int N = intents.size();
12350                        for (int i=0; i<N; i++) {
12351                            sb.setLength(0);
12352                            sb.append("    Intent: ");
12353                            intents.get(i).toShortString(sb, false, true, false, false);
12354                            pw.println(sb.toString());
12355                            Bundle bundle = intents.get(i).getExtras();
12356                            if (bundle != null) {
12357                                pw.print("      ");
12358                                pw.println(bundle.toString());
12359                            }
12360                        }
12361                    } else {
12362                        pw.println("");
12363                    }
12364                }
12365            }
12366        }
12367
12368        if (!onlyHistory && dumpAll) {
12369            pw.println();
12370            for (BroadcastQueue queue : mBroadcastQueues) {
12371                pw.println("  mBroadcastsScheduled [" + queue.mQueueName + "]="
12372                        + queue.mBroadcastsScheduled);
12373            }
12374            pw.println("  mHandler:");
12375            mHandler.dump(new PrintWriterPrinter(pw), "    ");
12376            needSep = true;
12377            printedAnything = true;
12378        }
12379
12380        if (!printedAnything) {
12381            pw.println("  (nothing)");
12382        }
12383    }
12384
12385    void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12386            int opti, boolean dumpAll, String dumpPackage) {
12387        boolean needSep;
12388        boolean printedAnything = false;
12389
12390        ItemMatcher matcher = new ItemMatcher();
12391        matcher.build(args, opti);
12392
12393        pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
12394
12395        needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage);
12396        printedAnything |= needSep;
12397
12398        if (mLaunchingProviders.size() > 0) {
12399            boolean printed = false;
12400            for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
12401                ContentProviderRecord r = mLaunchingProviders.get(i);
12402                if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
12403                    continue;
12404                }
12405                if (!printed) {
12406                    if (needSep) pw.println();
12407                    needSep = true;
12408                    pw.println("  Launching content providers:");
12409                    printed = true;
12410                    printedAnything = true;
12411                }
12412                pw.print("  Launching #"); pw.print(i); pw.print(": ");
12413                        pw.println(r);
12414            }
12415        }
12416
12417        if (mGrantedUriPermissions.size() > 0) {
12418            boolean printed = false;
12419            int dumpUid = -2;
12420            if (dumpPackage != null) {
12421                try {
12422                    dumpUid = mContext.getPackageManager().getPackageUid(dumpPackage, 0);
12423                } catch (NameNotFoundException e) {
12424                    dumpUid = -1;
12425                }
12426            }
12427            for (int i=0; i<mGrantedUriPermissions.size(); i++) {
12428                int uid = mGrantedUriPermissions.keyAt(i);
12429                if (dumpUid >= -1 && UserHandle.getAppId(uid) != dumpUid) {
12430                    continue;
12431                }
12432                final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
12433                if (!printed) {
12434                    if (needSep) pw.println();
12435                    needSep = true;
12436                    pw.println("  Granted Uri Permissions:");
12437                    printed = true;
12438                    printedAnything = true;
12439                }
12440                pw.print("  * UID "); pw.print(uid); pw.println(" holds:");
12441                for (UriPermission perm : perms.values()) {
12442                    pw.print("    "); pw.println(perm);
12443                    if (dumpAll) {
12444                        perm.dump(pw, "      ");
12445                    }
12446                }
12447            }
12448        }
12449
12450        if (!printedAnything) {
12451            pw.println("  (nothing)");
12452        }
12453    }
12454
12455    void dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
12456            int opti, boolean dumpAll, String dumpPackage) {
12457        boolean printed = false;
12458
12459        pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
12460
12461        if (mIntentSenderRecords.size() > 0) {
12462            Iterator<WeakReference<PendingIntentRecord>> it
12463                    = mIntentSenderRecords.values().iterator();
12464            while (it.hasNext()) {
12465                WeakReference<PendingIntentRecord> ref = it.next();
12466                PendingIntentRecord rec = ref != null ? ref.get(): null;
12467                if (dumpPackage != null && (rec == null
12468                        || !dumpPackage.equals(rec.key.packageName))) {
12469                    continue;
12470                }
12471                printed = true;
12472                if (rec != null) {
12473                    pw.print("  * "); pw.println(rec);
12474                    if (dumpAll) {
12475                        rec.dump(pw, "    ");
12476                    }
12477                } else {
12478                    pw.print("  * "); pw.println(ref);
12479                }
12480            }
12481        }
12482
12483        if (!printed) {
12484            pw.println("  (nothing)");
12485        }
12486    }
12487
12488    private static final int dumpProcessList(PrintWriter pw,
12489            ActivityManagerService service, List list,
12490            String prefix, String normalLabel, String persistentLabel,
12491            String dumpPackage) {
12492        int numPers = 0;
12493        final int N = list.size()-1;
12494        for (int i=N; i>=0; i--) {
12495            ProcessRecord r = (ProcessRecord)list.get(i);
12496            if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
12497                continue;
12498            }
12499            pw.println(String.format("%s%s #%2d: %s",
12500                    prefix, (r.persistent ? persistentLabel : normalLabel),
12501                    i, r.toString()));
12502            if (r.persistent) {
12503                numPers++;
12504            }
12505        }
12506        return numPers;
12507    }
12508
12509    private static final boolean dumpProcessOomList(PrintWriter pw,
12510            ActivityManagerService service, List<ProcessRecord> origList,
12511            String prefix, String normalLabel, String persistentLabel,
12512            boolean inclDetails, String dumpPackage) {
12513
12514        ArrayList<Pair<ProcessRecord, Integer>> list
12515                = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
12516        for (int i=0; i<origList.size(); i++) {
12517            ProcessRecord r = origList.get(i);
12518            if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) {
12519                continue;
12520            }
12521            list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
12522        }
12523
12524        if (list.size() <= 0) {
12525            return false;
12526        }
12527
12528        Comparator<Pair<ProcessRecord, Integer>> comparator
12529                = new Comparator<Pair<ProcessRecord, Integer>>() {
12530            @Override
12531            public int compare(Pair<ProcessRecord, Integer> object1,
12532                    Pair<ProcessRecord, Integer> object2) {
12533                if (object1.first.setAdj != object2.first.setAdj) {
12534                    return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
12535                }
12536                if (object1.second.intValue() != object2.second.intValue()) {
12537                    return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
12538                }
12539                return 0;
12540            }
12541        };
12542
12543        Collections.sort(list, comparator);
12544
12545        final long curRealtime = SystemClock.elapsedRealtime();
12546        final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
12547        final long curUptime = SystemClock.uptimeMillis();
12548        final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
12549
12550        for (int i=list.size()-1; i>=0; i--) {
12551            ProcessRecord r = list.get(i).first;
12552            String oomAdj = ProcessList.makeOomAdjString(r.setAdj);
12553            char schedGroup;
12554            switch (r.setSchedGroup) {
12555                case Process.THREAD_GROUP_BG_NONINTERACTIVE:
12556                    schedGroup = 'B';
12557                    break;
12558                case Process.THREAD_GROUP_DEFAULT:
12559                    schedGroup = 'F';
12560                    break;
12561                default:
12562                    schedGroup = '?';
12563                    break;
12564            }
12565            char foreground;
12566            if (r.foregroundActivities) {
12567                foreground = 'A';
12568            } else if (r.foregroundServices) {
12569                foreground = 'S';
12570            } else {
12571                foreground = ' ';
12572            }
12573            String procState = ProcessList.makeProcStateString(r.curProcState);
12574            pw.print(prefix);
12575            pw.print(r.persistent ? persistentLabel : normalLabel);
12576            pw.print(" #");
12577            int num = (origList.size()-1)-list.get(i).second;
12578            if (num < 10) pw.print(' ');
12579            pw.print(num);
12580            pw.print(": ");
12581            pw.print(oomAdj);
12582            pw.print(' ');
12583            pw.print(schedGroup);
12584            pw.print('/');
12585            pw.print(foreground);
12586            pw.print('/');
12587            pw.print(procState);
12588            pw.print(" trm:");
12589            if (r.trimMemoryLevel < 10) pw.print(' ');
12590            pw.print(r.trimMemoryLevel);
12591            pw.print(' ');
12592            pw.print(r.toShortString());
12593            pw.print(" (");
12594            pw.print(r.adjType);
12595            pw.println(')');
12596            if (r.adjSource != null || r.adjTarget != null) {
12597                pw.print(prefix);
12598                pw.print("    ");
12599                if (r.adjTarget instanceof ComponentName) {
12600                    pw.print(((ComponentName)r.adjTarget).flattenToShortString());
12601                } else if (r.adjTarget != null) {
12602                    pw.print(r.adjTarget.toString());
12603                } else {
12604                    pw.print("{null}");
12605                }
12606                pw.print("<=");
12607                if (r.adjSource instanceof ProcessRecord) {
12608                    pw.print("Proc{");
12609                    pw.print(((ProcessRecord)r.adjSource).toShortString());
12610                    pw.println("}");
12611                } else if (r.adjSource != null) {
12612                    pw.println(r.adjSource.toString());
12613                } else {
12614                    pw.println("{null}");
12615                }
12616            }
12617            if (inclDetails) {
12618                pw.print(prefix);
12619                pw.print("    ");
12620                pw.print("oom: max="); pw.print(r.maxAdj);
12621                pw.print(" curRaw="); pw.print(r.curRawAdj);
12622                pw.print(" setRaw="); pw.print(r.setRawAdj);
12623                pw.print(" cur="); pw.print(r.curAdj);
12624                pw.print(" set="); pw.println(r.setAdj);
12625                pw.print(prefix);
12626                pw.print("    ");
12627                pw.print("state: cur="); pw.print(ProcessList.makeProcStateString(r.curProcState));
12628                pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState));
12629                pw.print(" lastPss="); pw.print(r.lastPss);
12630                pw.print(" lastCachedPss="); pw.println(r.lastCachedPss);
12631                pw.print(prefix);
12632                pw.print("    ");
12633                pw.print("cached="); pw.print(r.cached);
12634                pw.print(" empty="); pw.print(r.empty);
12635                pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
12636
12637                if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
12638                    if (r.lastWakeTime != 0) {
12639                        long wtime;
12640                        BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
12641                        synchronized (stats) {
12642                            wtime = stats.getProcessWakeTime(r.info.uid,
12643                                    r.pid, curRealtime);
12644                        }
12645                        long timeUsed = wtime - r.lastWakeTime;
12646                        pw.print(prefix);
12647                        pw.print("    ");
12648                        pw.print("keep awake over ");
12649                        TimeUtils.formatDuration(realtimeSince, pw);
12650                        pw.print(" used ");
12651                        TimeUtils.formatDuration(timeUsed, pw);
12652                        pw.print(" (");
12653                        pw.print((timeUsed*100)/realtimeSince);
12654                        pw.println("%)");
12655                    }
12656                    if (r.lastCpuTime != 0) {
12657                        long timeUsed = r.curCpuTime - r.lastCpuTime;
12658                        pw.print(prefix);
12659                        pw.print("    ");
12660                        pw.print("run cpu over ");
12661                        TimeUtils.formatDuration(uptimeSince, pw);
12662                        pw.print(" used ");
12663                        TimeUtils.formatDuration(timeUsed, pw);
12664                        pw.print(" (");
12665                        pw.print((timeUsed*100)/uptimeSince);
12666                        pw.println("%)");
12667                    }
12668                }
12669            }
12670        }
12671        return true;
12672    }
12673
12674    ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
12675        ArrayList<ProcessRecord> procs;
12676        synchronized (this) {
12677            if (args != null && args.length > start
12678                    && args[start].charAt(0) != '-') {
12679                procs = new ArrayList<ProcessRecord>();
12680                int pid = -1;
12681                try {
12682                    pid = Integer.parseInt(args[start]);
12683                } catch (NumberFormatException e) {
12684                }
12685                for (int i=mLruProcesses.size()-1; i>=0; i--) {
12686                    ProcessRecord proc = mLruProcesses.get(i);
12687                    if (proc.pid == pid) {
12688                        procs.add(proc);
12689                    } else if (proc.processName.equals(args[start])) {
12690                        procs.add(proc);
12691                    }
12692                }
12693                if (procs.size() <= 0) {
12694                    return null;
12695                }
12696            } else {
12697                procs = new ArrayList<ProcessRecord>(mLruProcesses);
12698            }
12699        }
12700        return procs;
12701    }
12702
12703    final void dumpGraphicsHardwareUsage(FileDescriptor fd,
12704            PrintWriter pw, String[] args) {
12705        ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
12706        if (procs == null) {
12707            pw.println("No process found for: " + args[0]);
12708            return;
12709        }
12710
12711        long uptime = SystemClock.uptimeMillis();
12712        long realtime = SystemClock.elapsedRealtime();
12713        pw.println("Applications Graphics Acceleration Info:");
12714        pw.println("Uptime: " + uptime + " Realtime: " + realtime);
12715
12716        for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12717            ProcessRecord r = procs.get(i);
12718            if (r.thread != null) {
12719                pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
12720                pw.flush();
12721                try {
12722                    TransferPipe tp = new TransferPipe();
12723                    try {
12724                        r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
12725                        tp.go(fd);
12726                    } finally {
12727                        tp.kill();
12728                    }
12729                } catch (IOException e) {
12730                    pw.println("Failure while dumping the app: " + r);
12731                    pw.flush();
12732                } catch (RemoteException e) {
12733                    pw.println("Got a RemoteException while dumping the app " + r);
12734                    pw.flush();
12735                }
12736            }
12737        }
12738    }
12739
12740    final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
12741        ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
12742        if (procs == null) {
12743            pw.println("No process found for: " + args[0]);
12744            return;
12745        }
12746
12747        pw.println("Applications Database Info:");
12748
12749        for (int i = procs.size() - 1 ; i >= 0 ; i--) {
12750            ProcessRecord r = procs.get(i);
12751            if (r.thread != null) {
12752                pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
12753                pw.flush();
12754                try {
12755                    TransferPipe tp = new TransferPipe();
12756                    try {
12757                        r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
12758                        tp.go(fd);
12759                    } finally {
12760                        tp.kill();
12761                    }
12762                } catch (IOException e) {
12763                    pw.println("Failure while dumping the app: " + r);
12764                    pw.flush();
12765                } catch (RemoteException e) {
12766                    pw.println("Got a RemoteException while dumping the app " + r);
12767                    pw.flush();
12768                }
12769            }
12770        }
12771    }
12772
12773    final static class MemItem {
12774        final boolean isProc;
12775        final String label;
12776        final String shortLabel;
12777        final long pss;
12778        final int id;
12779        final boolean hasActivities;
12780        ArrayList<MemItem> subitems;
12781
12782        public MemItem(String _label, String _shortLabel, long _pss, int _id,
12783                boolean _hasActivities) {
12784            isProc = true;
12785            label = _label;
12786            shortLabel = _shortLabel;
12787            pss = _pss;
12788            id = _id;
12789            hasActivities = _hasActivities;
12790        }
12791
12792        public MemItem(String _label, String _shortLabel, long _pss, int _id) {
12793            isProc = false;
12794            label = _label;
12795            shortLabel = _shortLabel;
12796            pss = _pss;
12797            id = _id;
12798            hasActivities = false;
12799        }
12800    }
12801
12802    static final void dumpMemItems(PrintWriter pw, String prefix, String tag,
12803            ArrayList<MemItem> items, boolean sort, boolean isCompact) {
12804        if (sort && !isCompact) {
12805            Collections.sort(items, new Comparator<MemItem>() {
12806                @Override
12807                public int compare(MemItem lhs, MemItem rhs) {
12808                    if (lhs.pss < rhs.pss) {
12809                        return 1;
12810                    } else if (lhs.pss > rhs.pss) {
12811                        return -1;
12812                    }
12813                    return 0;
12814                }
12815            });
12816        }
12817
12818        for (int i=0; i<items.size(); i++) {
12819            MemItem mi = items.get(i);
12820            if (!isCompact) {
12821                pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
12822            } else if (mi.isProc) {
12823                pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel);
12824                pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss);
12825                pw.println(mi.hasActivities ? ",a" : ",e");
12826            } else {
12827                pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(",");
12828                pw.println(mi.pss);
12829            }
12830            if (mi.subitems != null) {
12831                dumpMemItems(pw, prefix + "           ", mi.shortLabel, mi.subitems,
12832                        true, isCompact);
12833            }
12834        }
12835    }
12836
12837    // These are in KB.
12838    static final long[] DUMP_MEM_BUCKETS = new long[] {
12839        5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
12840        120*1024, 160*1024, 200*1024,
12841        250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
12842        1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
12843    };
12844
12845    static final void appendMemBucket(StringBuilder out, long memKB, String label,
12846            boolean stackLike) {
12847        int start = label.lastIndexOf('.');
12848        if (start >= 0) start++;
12849        else start = 0;
12850        int end = label.length();
12851        for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
12852            if (DUMP_MEM_BUCKETS[i] >= memKB) {
12853                long bucket = DUMP_MEM_BUCKETS[i]/1024;
12854                out.append(bucket);
12855                out.append(stackLike ? "MB." : "MB ");
12856                out.append(label, start, end);
12857                return;
12858            }
12859        }
12860        out.append(memKB/1024);
12861        out.append(stackLike ? "MB." : "MB ");
12862        out.append(label, start, end);
12863    }
12864
12865    static final int[] DUMP_MEM_OOM_ADJ = new int[] {
12866            ProcessList.NATIVE_ADJ,
12867            ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
12868            ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ,
12869            ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
12870            ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
12871            ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MAX_ADJ
12872    };
12873    static final String[] DUMP_MEM_OOM_LABEL = new String[] {
12874            "Native",
12875            "System", "Persistent", "Foreground",
12876            "Visible", "Perceptible",
12877            "Heavy Weight", "Backup",
12878            "A Services", "Home",
12879            "Previous", "B Services", "Cached"
12880    };
12881    static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] {
12882            "native",
12883            "sys", "pers", "fore",
12884            "vis", "percept",
12885            "heavy", "backup",
12886            "servicea", "home",
12887            "prev", "serviceb", "cached"
12888    };
12889
12890    private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime,
12891            long realtime, boolean isCheckinRequest, boolean isCompact) {
12892        if (isCheckinRequest || isCompact) {
12893            // short checkin version
12894            pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime);
12895        } else {
12896            pw.println("Applications Memory Usage (kB):");
12897            pw.println("Uptime: " + uptime + " Realtime: " + realtime);
12898        }
12899    }
12900
12901    final void dumpApplicationMemoryUsage(FileDescriptor fd,
12902            PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) {
12903        boolean dumpDetails = false;
12904        boolean dumpFullDetails = false;
12905        boolean dumpDalvik = false;
12906        boolean oomOnly = false;
12907        boolean isCompact = false;
12908        boolean localOnly = false;
12909
12910        int opti = 0;
12911        while (opti < args.length) {
12912            String opt = args[opti];
12913            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12914                break;
12915            }
12916            opti++;
12917            if ("-a".equals(opt)) {
12918                dumpDetails = true;
12919                dumpFullDetails = true;
12920                dumpDalvik = true;
12921            } else if ("-d".equals(opt)) {
12922                dumpDalvik = true;
12923            } else if ("-c".equals(opt)) {
12924                isCompact = true;
12925            } else if ("--oom".equals(opt)) {
12926                oomOnly = true;
12927            } else if ("--local".equals(opt)) {
12928                localOnly = true;
12929            } else if ("-h".equals(opt)) {
12930                pw.println("meminfo dump options: [-a] [-d] [-c] [--oom] [process]");
12931                pw.println("  -a: include all available information for each process.");
12932                pw.println("  -d: include dalvik details when dumping process details.");
12933                pw.println("  -c: dump in a compact machine-parseable representation.");
12934                pw.println("  --oom: only show processes organized by oom adj.");
12935                pw.println("  --local: only collect details locally, don't call process.");
12936                pw.println("If [process] is specified it can be the name or ");
12937                pw.println("pid of a specific process to dump.");
12938                return;
12939            } else {
12940                pw.println("Unknown argument: " + opt + "; use -h for help");
12941            }
12942        }
12943
12944        final boolean isCheckinRequest = scanArgs(args, "--checkin");
12945        long uptime = SystemClock.uptimeMillis();
12946        long realtime = SystemClock.elapsedRealtime();
12947        final long[] tmpLong = new long[1];
12948
12949        ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
12950        if (procs == null) {
12951            // No Java processes.  Maybe they want to print a native process.
12952            if (args != null && args.length > opti
12953                    && args[opti].charAt(0) != '-') {
12954                ArrayList<ProcessCpuTracker.Stats> nativeProcs
12955                        = new ArrayList<ProcessCpuTracker.Stats>();
12956                updateCpuStatsNow();
12957                int findPid = -1;
12958                try {
12959                    findPid = Integer.parseInt(args[opti]);
12960                } catch (NumberFormatException e) {
12961                }
12962                synchronized (mProcessCpuThread) {
12963                    final int N = mProcessCpuTracker.countStats();
12964                    for (int i=0; i<N; i++) {
12965                        ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
12966                        if (st.pid == findPid || (st.baseName != null
12967                                && st.baseName.equals(args[opti]))) {
12968                            nativeProcs.add(st);
12969                        }
12970                    }
12971                }
12972                if (nativeProcs.size() > 0) {
12973                    dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest,
12974                            isCompact);
12975                    Debug.MemoryInfo mi = null;
12976                    for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) {
12977                        final ProcessCpuTracker.Stats r = nativeProcs.get(i);
12978                        final int pid = r.pid;
12979                        if (!isCheckinRequest && dumpDetails) {
12980                            pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **");
12981                        }
12982                        if (mi == null) {
12983                            mi = new Debug.MemoryInfo();
12984                        }
12985                        if (dumpDetails || (!brief && !oomOnly)) {
12986                            Debug.getMemoryInfo(pid, mi);
12987                        } else {
12988                            mi.dalvikPss = (int)Debug.getPss(pid, tmpLong);
12989                            mi.dalvikPrivateDirty = (int)tmpLong[0];
12990                        }
12991                        ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails,
12992                                dumpDalvik, pid, r.baseName, 0, 0, 0, 0, 0, 0);
12993                        if (isCheckinRequest) {
12994                            pw.println();
12995                        }
12996                    }
12997                    return;
12998                }
12999            }
13000            pw.println("No process found for: " + args[opti]);
13001            return;
13002        }
13003
13004        if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest)) {
13005            dumpDetails = true;
13006        }
13007
13008        dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact);
13009
13010        String[] innerArgs = new String[args.length-opti];
13011        System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
13012
13013        ArrayList<MemItem> procMems = new ArrayList<MemItem>();
13014        final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>();
13015        long nativePss=0, dalvikPss=0, otherPss=0;
13016        long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
13017
13018        long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
13019        ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
13020                new ArrayList[DUMP_MEM_OOM_LABEL.length];
13021
13022        long totalPss = 0;
13023        long cachedPss = 0;
13024
13025        Debug.MemoryInfo mi = null;
13026        for (int i = procs.size() - 1 ; i >= 0 ; i--) {
13027            final ProcessRecord r = procs.get(i);
13028            final IApplicationThread thread;
13029            final int pid;
13030            final int oomAdj;
13031            final boolean hasActivities;
13032            synchronized (this) {
13033                thread = r.thread;
13034                pid = r.pid;
13035                oomAdj = r.getSetAdjWithServices();
13036                hasActivities = r.activities.size() > 0;
13037            }
13038            if (thread != null) {
13039                if (!isCheckinRequest && dumpDetails) {
13040                    pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **");
13041                }
13042                if (mi == null) {
13043                    mi = new Debug.MemoryInfo();
13044                }
13045                if (dumpDetails || (!brief && !oomOnly)) {
13046                    Debug.getMemoryInfo(pid, mi);
13047                } else {
13048                    mi.dalvikPss = (int)Debug.getPss(pid, tmpLong);
13049                    mi.dalvikPrivateDirty = (int)tmpLong[0];
13050                }
13051                if (dumpDetails) {
13052                    if (localOnly) {
13053                        ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails,
13054                                dumpDalvik, pid, r.processName, 0, 0, 0, 0, 0, 0);
13055                        if (isCheckinRequest) {
13056                            pw.println();
13057                        }
13058                    } else {
13059                        try {
13060                            pw.flush();
13061                            thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails,
13062                                    dumpDalvik, innerArgs);
13063                        } catch (RemoteException e) {
13064                            if (!isCheckinRequest) {
13065                                pw.println("Got RemoteException!");
13066                                pw.flush();
13067                            }
13068                        }
13069                    }
13070                }
13071
13072                final long myTotalPss = mi.getTotalPss();
13073                final long myTotalUss = mi.getTotalUss();
13074
13075                synchronized (this) {
13076                    if (r.thread != null && oomAdj == r.getSetAdjWithServices()) {
13077                        // Record this for posterity if the process has been stable.
13078                        r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList);
13079                    }
13080                }
13081
13082                if (!isCheckinRequest && mi != null) {
13083                    totalPss += myTotalPss;
13084                    MemItem pssItem = new MemItem(r.processName + " (pid " + pid +
13085                            (hasActivities ? " / activities)" : ")"),
13086                            r.processName, myTotalPss, pid, hasActivities);
13087                    procMems.add(pssItem);
13088                    procMemsMap.put(pid, pssItem);
13089
13090                    nativePss += mi.nativePss;
13091                    dalvikPss += mi.dalvikPss;
13092                    otherPss += mi.otherPss;
13093                    for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13094                        long mem = mi.getOtherPss(j);
13095                        miscPss[j] += mem;
13096                        otherPss -= mem;
13097                    }
13098
13099                    if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
13100                        cachedPss += myTotalPss;
13101                    }
13102
13103                    for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
13104                        if (oomAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
13105                                || oomIndex == (oomPss.length-1)) {
13106                            oomPss[oomIndex] += myTotalPss;
13107                            if (oomProcs[oomIndex] == null) {
13108                                oomProcs[oomIndex] = new ArrayList<MemItem>();
13109                            }
13110                            oomProcs[oomIndex].add(pssItem);
13111                            break;
13112                        }
13113                    }
13114                }
13115            }
13116        }
13117
13118        long nativeProcTotalPss = 0;
13119
13120        if (!isCheckinRequest && procs.size() > 1) {
13121            // If we are showing aggregations, also look for native processes to
13122            // include so that our aggregations are more accurate.
13123            updateCpuStatsNow();
13124            synchronized (mProcessCpuThread) {
13125                final int N = mProcessCpuTracker.countStats();
13126                for (int i=0; i<N; i++) {
13127                    ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i);
13128                    if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) {
13129                        if (mi == null) {
13130                            mi = new Debug.MemoryInfo();
13131                        }
13132                        if (!brief && !oomOnly) {
13133                            Debug.getMemoryInfo(st.pid, mi);
13134                        } else {
13135                            mi.nativePss = (int)Debug.getPss(st.pid, tmpLong);
13136                            mi.nativePrivateDirty = (int)tmpLong[0];
13137                        }
13138
13139                        final long myTotalPss = mi.getTotalPss();
13140                        totalPss += myTotalPss;
13141                        nativeProcTotalPss += myTotalPss;
13142
13143                        MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")",
13144                                st.name, myTotalPss, st.pid, false);
13145                        procMems.add(pssItem);
13146
13147                        nativePss += mi.nativePss;
13148                        dalvikPss += mi.dalvikPss;
13149                        otherPss += mi.otherPss;
13150                        for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13151                            long mem = mi.getOtherPss(j);
13152                            miscPss[j] += mem;
13153                            otherPss -= mem;
13154                        }
13155                        oomPss[0] += myTotalPss;
13156                        if (oomProcs[0] == null) {
13157                            oomProcs[0] = new ArrayList<MemItem>();
13158                        }
13159                        oomProcs[0].add(pssItem);
13160                    }
13161                }
13162            }
13163
13164            ArrayList<MemItem> catMems = new ArrayList<MemItem>();
13165
13166            catMems.add(new MemItem("Native", "Native", nativePss, -1));
13167            catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
13168            catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
13169            for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
13170                String label = Debug.MemoryInfo.getOtherLabel(j);
13171                catMems.add(new MemItem(label, label, miscPss[j], j));
13172            }
13173
13174            ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
13175            for (int j=0; j<oomPss.length; j++) {
13176                if (oomPss[j] != 0) {
13177                    String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j]
13178                            : DUMP_MEM_OOM_LABEL[j];
13179                    MemItem item = new MemItem(label, label, oomPss[j],
13180                            DUMP_MEM_OOM_ADJ[j]);
13181                    item.subitems = oomProcs[j];
13182                    oomMems.add(item);
13183                }
13184            }
13185
13186            if (!brief && !oomOnly && !isCompact) {
13187                pw.println();
13188                pw.println("Total PSS by process:");
13189                dumpMemItems(pw, "  ", "proc", procMems, true, isCompact);
13190                pw.println();
13191            }
13192            if (!isCompact) {
13193                pw.println("Total PSS by OOM adjustment:");
13194            }
13195            dumpMemItems(pw, "  ", "oom", oomMems, false, isCompact);
13196            if (!brief && !oomOnly) {
13197                PrintWriter out = categoryPw != null ? categoryPw : pw;
13198                if (!isCompact) {
13199                    out.println();
13200                    out.println("Total PSS by category:");
13201                }
13202                dumpMemItems(out, "  ", "cat", catMems, true, isCompact);
13203            }
13204            if (!isCompact) {
13205                pw.println();
13206            }
13207            MemInfoReader memInfo = new MemInfoReader();
13208            memInfo.readMemInfo();
13209            if (nativeProcTotalPss > 0) {
13210                synchronized (this) {
13211                    mProcessStats.addSysMemUsageLocked(memInfo.getCachedSizeKb(),
13212                            memInfo.getFreeSizeKb(), memInfo.getZramTotalSizeKb(),
13213                            memInfo.getBuffersSizeKb()+memInfo.getShmemSizeKb()+memInfo.getSlabSizeKb(),
13214                            nativeProcTotalPss);
13215                }
13216            }
13217            if (!brief) {
13218                if (!isCompact) {
13219                    pw.print("Total RAM: "); pw.print(memInfo.getTotalSizeKb());
13220                    pw.print(" kB (status ");
13221                    switch (mLastMemoryLevel) {
13222                        case ProcessStats.ADJ_MEM_FACTOR_NORMAL:
13223                            pw.println("normal)");
13224                            break;
13225                        case ProcessStats.ADJ_MEM_FACTOR_MODERATE:
13226                            pw.println("moderate)");
13227                            break;
13228                        case ProcessStats.ADJ_MEM_FACTOR_LOW:
13229                            pw.println("low)");
13230                            break;
13231                        case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
13232                            pw.println("critical)");
13233                            break;
13234                        default:
13235                            pw.print(mLastMemoryLevel);
13236                            pw.println(")");
13237                            break;
13238                    }
13239                    pw.print(" Free RAM: "); pw.print(cachedPss + memInfo.getCachedSizeKb()
13240                            + memInfo.getFreeSizeKb()); pw.print(" kB (");
13241                            pw.print(cachedPss); pw.print(" cached pss + ");
13242                            pw.print(memInfo.getCachedSizeKb()); pw.print(" cached + ");
13243                            pw.print(memInfo.getFreeSizeKb()); pw.println(" free)");
13244                } else {
13245                    pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(",");
13246                    pw.print(cachedPss + memInfo.getCachedSizeKb()
13247                            + memInfo.getFreeSizeKb()); pw.print(",");
13248                    pw.println(totalPss - cachedPss);
13249                }
13250            }
13251            if (!isCompact) {
13252                pw.print(" Used RAM: "); pw.print(totalPss - cachedPss
13253                        + memInfo.getBuffersSizeKb() + memInfo.getShmemSizeKb()
13254                        + memInfo.getSlabSizeKb()); pw.print(" kB (");
13255                        pw.print(totalPss - cachedPss); pw.print(" used pss + ");
13256                        pw.print(memInfo.getBuffersSizeKb()); pw.print(" buffers + ");
13257                        pw.print(memInfo.getShmemSizeKb()); pw.print(" shmem + ");
13258                        pw.print(memInfo.getSlabSizeKb()); pw.println(" slab)");
13259                pw.print(" Lost RAM: "); pw.print(memInfo.getTotalSizeKb()
13260                        - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb()
13261                        - memInfo.getBuffersSizeKb() - memInfo.getShmemSizeKb()
13262                        - memInfo.getSlabSizeKb()); pw.println(" kB");
13263            }
13264            if (!brief) {
13265                if (memInfo.getZramTotalSizeKb() != 0) {
13266                    if (!isCompact) {
13267                        pw.print("     ZRAM: "); pw.print(memInfo.getZramTotalSizeKb());
13268                                pw.print(" kB physical used for ");
13269                                pw.print(memInfo.getSwapTotalSizeKb()
13270                                        - memInfo.getSwapFreeSizeKb());
13271                                pw.print(" kB in swap (");
13272                                pw.print(memInfo.getSwapTotalSizeKb());
13273                                pw.println(" kB total swap)");
13274                    } else {
13275                        pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(",");
13276                                pw.print(memInfo.getSwapTotalSizeKb()); pw.print(",");
13277                                pw.println(memInfo.getSwapFreeSizeKb());
13278                    }
13279                }
13280                final int[] SINGLE_LONG_FORMAT = new int[] {
13281                    Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
13282                };
13283                long[] longOut = new long[1];
13284                Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
13285                        SINGLE_LONG_FORMAT, null, longOut, null);
13286                long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
13287                longOut[0] = 0;
13288                Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
13289                        SINGLE_LONG_FORMAT, null, longOut, null);
13290                long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
13291                longOut[0] = 0;
13292                Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
13293                        SINGLE_LONG_FORMAT, null, longOut, null);
13294                long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
13295                longOut[0] = 0;
13296                Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
13297                        SINGLE_LONG_FORMAT, null, longOut, null);
13298                long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
13299                if (!isCompact) {
13300                    if (sharing != 0 || shared != 0 || unshared != 0 || voltile != 0) {
13301                        pw.print("      KSM: "); pw.print(sharing);
13302                                pw.print(" kB saved from shared ");
13303                                pw.print(shared); pw.println(" kB");
13304                        pw.print("           "); pw.print(unshared); pw.print(" kB unshared; ");
13305                                pw.print(voltile); pw.println(" kB volatile");
13306                    }
13307                    pw.print("   Tuning: ");
13308                    pw.print(ActivityManager.staticGetMemoryClass());
13309                    pw.print(" (large ");
13310                    pw.print(ActivityManager.staticGetLargeMemoryClass());
13311                    pw.print("), oom ");
13312                    pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
13313                    pw.print(" kB");
13314                    pw.print(", restore limit ");
13315                    pw.print(mProcessList.getCachedRestoreThresholdKb());
13316                    pw.print(" kB");
13317                    if (ActivityManager.isLowRamDeviceStatic()) {
13318                        pw.print(" (low-ram)");
13319                    }
13320                    if (ActivityManager.isHighEndGfx()) {
13321                        pw.print(" (high-end-gfx)");
13322                    }
13323                    pw.println();
13324                } else {
13325                    pw.print("ksm,"); pw.print(sharing); pw.print(",");
13326                    pw.print(shared); pw.print(","); pw.print(unshared); pw.print(",");
13327                    pw.println(voltile);
13328                    pw.print("tuning,");
13329                    pw.print(ActivityManager.staticGetMemoryClass());
13330                    pw.print(',');
13331                    pw.print(ActivityManager.staticGetLargeMemoryClass());
13332                    pw.print(',');
13333                    pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024);
13334                    if (ActivityManager.isLowRamDeviceStatic()) {
13335                        pw.print(",low-ram");
13336                    }
13337                    if (ActivityManager.isHighEndGfx()) {
13338                        pw.print(",high-end-gfx");
13339                    }
13340                    pw.println();
13341                }
13342            }
13343        }
13344    }
13345
13346    /**
13347     * Searches array of arguments for the specified string
13348     * @param args array of argument strings
13349     * @param value value to search for
13350     * @return true if the value is contained in the array
13351     */
13352    private static boolean scanArgs(String[] args, String value) {
13353        if (args != null) {
13354            for (String arg : args) {
13355                if (value.equals(arg)) {
13356                    return true;
13357                }
13358            }
13359        }
13360        return false;
13361    }
13362
13363    private final boolean removeDyingProviderLocked(ProcessRecord proc,
13364            ContentProviderRecord cpr, boolean always) {
13365        final boolean inLaunching = mLaunchingProviders.contains(cpr);
13366
13367        if (!inLaunching || always) {
13368            synchronized (cpr) {
13369                cpr.launchingApp = null;
13370                cpr.notifyAll();
13371            }
13372            mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
13373            String names[] = cpr.info.authority.split(";");
13374            for (int j = 0; j < names.length; j++) {
13375                mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
13376            }
13377        }
13378
13379        for (int i=0; i<cpr.connections.size(); i++) {
13380            ContentProviderConnection conn = cpr.connections.get(i);
13381            if (conn.waiting) {
13382                // If this connection is waiting for the provider, then we don't
13383                // need to mess with its process unless we are always removing
13384                // or for some reason the provider is not currently launching.
13385                if (inLaunching && !always) {
13386                    continue;
13387                }
13388            }
13389            ProcessRecord capp = conn.client;
13390            conn.dead = true;
13391            if (conn.stableCount > 0) {
13392                if (!capp.persistent && capp.thread != null
13393                        && capp.pid != 0
13394                        && capp.pid != MY_PID) {
13395                    killUnneededProcessLocked(capp, "depends on provider "
13396                            + cpr.name.flattenToShortString()
13397                            + " in dying proc " + (proc != null ? proc.processName : "??"));
13398                }
13399            } else if (capp.thread != null && conn.provider.provider != null) {
13400                try {
13401                    capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
13402                } catch (RemoteException e) {
13403                }
13404                // In the protocol here, we don't expect the client to correctly
13405                // clean up this connection, we'll just remove it.
13406                cpr.connections.remove(i);
13407                conn.client.conProviders.remove(conn);
13408            }
13409        }
13410
13411        if (inLaunching && always) {
13412            mLaunchingProviders.remove(cpr);
13413        }
13414        return inLaunching;
13415    }
13416
13417    /**
13418     * Main code for cleaning up a process when it has gone away.  This is
13419     * called both as a result of the process dying, or directly when stopping
13420     * a process when running in single process mode.
13421     */
13422    private final void cleanUpApplicationRecordLocked(ProcessRecord app,
13423            boolean restarting, boolean allowRestart, int index) {
13424        if (index >= 0) {
13425            removeLruProcessLocked(app);
13426            ProcessList.remove(app.pid);
13427        }
13428
13429        mProcessesToGc.remove(app);
13430        mPendingPssProcesses.remove(app);
13431
13432        // Dismiss any open dialogs.
13433        if (app.crashDialog != null && !app.forceCrashReport) {
13434            app.crashDialog.dismiss();
13435            app.crashDialog = null;
13436        }
13437        if (app.anrDialog != null) {
13438            app.anrDialog.dismiss();
13439            app.anrDialog = null;
13440        }
13441        if (app.waitDialog != null) {
13442            app.waitDialog.dismiss();
13443            app.waitDialog = null;
13444        }
13445
13446        app.crashing = false;
13447        app.notResponding = false;
13448
13449        app.resetPackageList(mProcessStats);
13450        app.unlinkDeathRecipient();
13451        app.makeInactive(mProcessStats);
13452        app.waitingToKill = null;
13453        app.forcingToForeground = null;
13454        updateProcessForegroundLocked(app, false, false);
13455        app.foregroundActivities = false;
13456        app.hasShownUi = false;
13457        app.treatLikeActivity = false;
13458        app.hasAboveClient = false;
13459        app.hasClientActivities = false;
13460
13461        mServices.killServicesLocked(app, allowRestart);
13462
13463        boolean restart = false;
13464
13465        // Remove published content providers.
13466        for (int i=app.pubProviders.size()-1; i>=0; i--) {
13467            ContentProviderRecord cpr = app.pubProviders.valueAt(i);
13468            final boolean always = app.bad || !allowRestart;
13469            if (removeDyingProviderLocked(app, cpr, always) || always) {
13470                // We left the provider in the launching list, need to
13471                // restart it.
13472                restart = true;
13473            }
13474
13475            cpr.provider = null;
13476            cpr.proc = null;
13477        }
13478        app.pubProviders.clear();
13479
13480        // Take care of any launching providers waiting for this process.
13481        if (checkAppInLaunchingProvidersLocked(app, false)) {
13482            restart = true;
13483        }
13484
13485        // Unregister from connected content providers.
13486        if (!app.conProviders.isEmpty()) {
13487            for (int i=0; i<app.conProviders.size(); i++) {
13488                ContentProviderConnection conn = app.conProviders.get(i);
13489                conn.provider.connections.remove(conn);
13490            }
13491            app.conProviders.clear();
13492        }
13493
13494        // At this point there may be remaining entries in mLaunchingProviders
13495        // where we were the only one waiting, so they are no longer of use.
13496        // Look for these and clean up if found.
13497        // XXX Commented out for now.  Trying to figure out a way to reproduce
13498        // the actual situation to identify what is actually going on.
13499        if (false) {
13500            for (int i=0; i<mLaunchingProviders.size(); i++) {
13501                ContentProviderRecord cpr = (ContentProviderRecord)
13502                        mLaunchingProviders.get(i);
13503                if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
13504                    synchronized (cpr) {
13505                        cpr.launchingApp = null;
13506                        cpr.notifyAll();
13507                    }
13508                }
13509            }
13510        }
13511
13512        skipCurrentReceiverLocked(app);
13513
13514        // Unregister any receivers.
13515        for (int i=app.receivers.size()-1; i>=0; i--) {
13516            removeReceiverLocked(app.receivers.valueAt(i));
13517        }
13518        app.receivers.clear();
13519
13520        // If the app is undergoing backup, tell the backup manager about it
13521        if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
13522            if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
13523                    + mBackupTarget.appInfo + " died during backup");
13524            try {
13525                IBackupManager bm = IBackupManager.Stub.asInterface(
13526                        ServiceManager.getService(Context.BACKUP_SERVICE));
13527                bm.agentDisconnected(app.info.packageName);
13528            } catch (RemoteException e) {
13529                // can't happen; backup manager is local
13530            }
13531        }
13532
13533        for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
13534            ProcessChangeItem item = mPendingProcessChanges.get(i);
13535            if (item.pid == app.pid) {
13536                mPendingProcessChanges.remove(i);
13537                mAvailProcessChanges.add(item);
13538            }
13539        }
13540        mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
13541
13542        // If the caller is restarting this app, then leave it in its
13543        // current lists and let the caller take care of it.
13544        if (restarting) {
13545            return;
13546        }
13547
13548        if (!app.persistent || app.isolated) {
13549            if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
13550                    "Removing non-persistent process during cleanup: " + app);
13551            mProcessNames.remove(app.processName, app.uid);
13552            mIsolatedProcesses.remove(app.uid);
13553            if (mHeavyWeightProcess == app) {
13554                mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
13555                        mHeavyWeightProcess.userId, 0));
13556                mHeavyWeightProcess = null;
13557            }
13558        } else if (!app.removed) {
13559            // This app is persistent, so we need to keep its record around.
13560            // If it is not already on the pending app list, add it there
13561            // and start a new process for it.
13562            if (mPersistentStartingProcesses.indexOf(app) < 0) {
13563                mPersistentStartingProcesses.add(app);
13564                restart = true;
13565            }
13566        }
13567        if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
13568                "Clean-up removing on hold: " + app);
13569        mProcessesOnHold.remove(app);
13570
13571        if (app == mHomeProcess) {
13572            mHomeProcess = null;
13573        }
13574        if (app == mPreviousProcess) {
13575            mPreviousProcess = null;
13576        }
13577
13578        if (restart && !app.isolated) {
13579            // We have components that still need to be running in the
13580            // process, so re-launch it.
13581            mProcessNames.put(app.processName, app.uid, app);
13582            startProcessLocked(app, "restart", app.processName);
13583        } else if (app.pid > 0 && app.pid != MY_PID) {
13584            // Goodbye!
13585            boolean removed;
13586            synchronized (mPidsSelfLocked) {
13587                mPidsSelfLocked.remove(app.pid);
13588                mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
13589            }
13590            mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid);
13591            if (app.isolated) {
13592                mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid);
13593            }
13594            app.setPid(0);
13595        }
13596    }
13597
13598    boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
13599        // Look through the content providers we are waiting to have launched,
13600        // and if any run in this process then either schedule a restart of
13601        // the process or kill the client waiting for it if this process has
13602        // gone bad.
13603        int NL = mLaunchingProviders.size();
13604        boolean restart = false;
13605        for (int i=0; i<NL; i++) {
13606            ContentProviderRecord cpr = mLaunchingProviders.get(i);
13607            if (cpr.launchingApp == app) {
13608                if (!alwaysBad && !app.bad) {
13609                    restart = true;
13610                } else {
13611                    removeDyingProviderLocked(app, cpr, true);
13612                    // cpr should have been removed from mLaunchingProviders
13613                    NL = mLaunchingProviders.size();
13614                    i--;
13615                }
13616            }
13617        }
13618        return restart;
13619    }
13620
13621    // =========================================================
13622    // SERVICES
13623    // =========================================================
13624
13625    @Override
13626    public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
13627            int flags) {
13628        enforceNotIsolatedCaller("getServices");
13629        synchronized (this) {
13630            return mServices.getRunningServiceInfoLocked(maxNum, flags);
13631        }
13632    }
13633
13634    @Override
13635    public PendingIntent getRunningServiceControlPanel(ComponentName name) {
13636        enforceNotIsolatedCaller("getRunningServiceControlPanel");
13637        synchronized (this) {
13638            return mServices.getRunningServiceControlPanelLocked(name);
13639        }
13640    }
13641
13642    @Override
13643    public ComponentName startService(IApplicationThread caller, Intent service,
13644            String resolvedType, int userId) {
13645        enforceNotIsolatedCaller("startService");
13646        // Refuse possible leaked file descriptors
13647        if (service != null && service.hasFileDescriptors() == true) {
13648            throw new IllegalArgumentException("File descriptors passed in Intent");
13649        }
13650
13651        if (DEBUG_SERVICE)
13652            Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
13653        synchronized(this) {
13654            final int callingPid = Binder.getCallingPid();
13655            final int callingUid = Binder.getCallingUid();
13656            final long origId = Binder.clearCallingIdentity();
13657            ComponentName res = mServices.startServiceLocked(caller, service,
13658                    resolvedType, callingPid, callingUid, userId);
13659            Binder.restoreCallingIdentity(origId);
13660            return res;
13661        }
13662    }
13663
13664    ComponentName startServiceInPackage(int uid,
13665            Intent service, String resolvedType, int userId) {
13666        synchronized(this) {
13667            if (DEBUG_SERVICE)
13668                Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
13669            final long origId = Binder.clearCallingIdentity();
13670            ComponentName res = mServices.startServiceLocked(null, service,
13671                    resolvedType, -1, uid, userId);
13672            Binder.restoreCallingIdentity(origId);
13673            return res;
13674        }
13675    }
13676
13677    @Override
13678    public int stopService(IApplicationThread caller, Intent service,
13679            String resolvedType, int userId) {
13680        enforceNotIsolatedCaller("stopService");
13681        // Refuse possible leaked file descriptors
13682        if (service != null && service.hasFileDescriptors() == true) {
13683            throw new IllegalArgumentException("File descriptors passed in Intent");
13684        }
13685
13686        synchronized(this) {
13687            return mServices.stopServiceLocked(caller, service, resolvedType, userId);
13688        }
13689    }
13690
13691    @Override
13692    public IBinder peekService(Intent service, String resolvedType) {
13693        enforceNotIsolatedCaller("peekService");
13694        // Refuse possible leaked file descriptors
13695        if (service != null && service.hasFileDescriptors() == true) {
13696            throw new IllegalArgumentException("File descriptors passed in Intent");
13697        }
13698        synchronized(this) {
13699            return mServices.peekServiceLocked(service, resolvedType);
13700        }
13701    }
13702
13703    @Override
13704    public boolean stopServiceToken(ComponentName className, IBinder token,
13705            int startId) {
13706        synchronized(this) {
13707            return mServices.stopServiceTokenLocked(className, token, startId);
13708        }
13709    }
13710
13711    @Override
13712    public void setServiceForeground(ComponentName className, IBinder token,
13713            int id, Notification notification, boolean removeNotification) {
13714        synchronized(this) {
13715            mServices.setServiceForegroundLocked(className, token, id, notification,
13716                    removeNotification);
13717        }
13718    }
13719
13720    @Override
13721    public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
13722            boolean requireFull, String name, String callerPackage) {
13723        return handleIncomingUser(callingPid, callingUid, userId, allowAll,
13724                requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage);
13725    }
13726
13727    int unsafeConvertIncomingUser(int userId) {
13728        return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
13729                ? mCurrentUserId : userId;
13730    }
13731
13732    int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
13733            int allowMode, String name, String callerPackage) {
13734        final int callingUserId = UserHandle.getUserId(callingUid);
13735        if (callingUserId == userId) {
13736            return userId;
13737        }
13738
13739        // Note that we may be accessing mCurrentUserId outside of a lock...
13740        // shouldn't be a big deal, if this is being called outside
13741        // of a locked context there is intrinsically a race with
13742        // the value the caller will receive and someone else changing it.
13743        // We assume that USER_CURRENT_OR_SELF will use the current user; later
13744        // we will switch to the calling user if access to the current user fails.
13745        int targetUserId = unsafeConvertIncomingUser(userId);
13746
13747        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13748            final boolean allow;
13749            if (checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
13750                    callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
13751                // If the caller has this permission, they always pass go.  And collect $200.
13752                allow = true;
13753            } else if (allowMode == ALLOW_FULL_ONLY) {
13754                // We require full access, sucks to be you.
13755                allow = false;
13756            } else if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
13757                    callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
13758                // If the caller does not have either permission, they are always doomed.
13759                allow = false;
13760            } else if (allowMode == ALLOW_NON_FULL) {
13761                // We are blanket allowing non-full access, you lucky caller!
13762                allow = true;
13763            } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
13764                // We may or may not allow this depending on whether the two users are
13765                // in the same profile.
13766                synchronized (mUserProfileGroupIdsSelfLocked) {
13767                    int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
13768                            UserInfo.NO_PROFILE_GROUP_ID);
13769                    int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
13770                            UserInfo.NO_PROFILE_GROUP_ID);
13771                    allow = callingProfile != UserInfo.NO_PROFILE_GROUP_ID
13772                            && callingProfile == targetProfile;
13773                }
13774            } else {
13775                throw new IllegalArgumentException("Unknown mode: " + allowMode);
13776            }
13777            if (!allow) {
13778                if (userId == UserHandle.USER_CURRENT_OR_SELF) {
13779                    // In this case, they would like to just execute as their
13780                    // owner user instead of failing.
13781                    targetUserId = callingUserId;
13782                } else {
13783                    StringBuilder builder = new StringBuilder(128);
13784                    builder.append("Permission Denial: ");
13785                    builder.append(name);
13786                    if (callerPackage != null) {
13787                        builder.append(" from ");
13788                        builder.append(callerPackage);
13789                    }
13790                    builder.append(" asks to run as user ");
13791                    builder.append(userId);
13792                    builder.append(" but is calling from user ");
13793                    builder.append(UserHandle.getUserId(callingUid));
13794                    builder.append("; this requires ");
13795                    builder.append(INTERACT_ACROSS_USERS_FULL);
13796                    if (allowMode != ALLOW_FULL_ONLY) {
13797                        builder.append(" or ");
13798                        builder.append(INTERACT_ACROSS_USERS);
13799                    }
13800                    String msg = builder.toString();
13801                    Slog.w(TAG, msg);
13802                    throw new SecurityException(msg);
13803                }
13804            }
13805        }
13806        if (!allowAll && targetUserId < 0) {
13807            throw new IllegalArgumentException(
13808                    "Call does not support special user #" + targetUserId);
13809        }
13810        return targetUserId;
13811    }
13812
13813    boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
13814            String className, int flags) {
13815        boolean result = false;
13816        // For apps that don't have pre-defined UIDs, check for permission
13817        if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
13818            if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
13819                if (ActivityManager.checkUidPermission(
13820                        INTERACT_ACROSS_USERS,
13821                        aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
13822                    ComponentName comp = new ComponentName(aInfo.packageName, className);
13823                    String msg = "Permission Denial: Component " + comp.flattenToShortString()
13824                            + " requests FLAG_SINGLE_USER, but app does not hold "
13825                            + INTERACT_ACROSS_USERS;
13826                    Slog.w(TAG, msg);
13827                    throw new SecurityException(msg);
13828                }
13829                // Permission passed
13830                result = true;
13831            }
13832        } else if ("system".equals(componentProcessName)) {
13833            result = true;
13834        } else if (UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID)
13835                && (flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
13836            // Phone app is allowed to export singleuser providers.
13837            result = true;
13838        } else {
13839            // App with pre-defined UID, check if it's a persistent app
13840            result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
13841        }
13842        if (DEBUG_MU) {
13843            Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
13844                    + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
13845        }
13846        return result;
13847    }
13848
13849    /**
13850     * Checks to see if the caller is in the same app as the singleton
13851     * component, or the component is in a special app. It allows special apps
13852     * to export singleton components but prevents exporting singleton
13853     * components for regular apps.
13854     */
13855    boolean isValidSingletonCall(int callingUid, int componentUid) {
13856        int componentAppId = UserHandle.getAppId(componentUid);
13857        return UserHandle.isSameApp(callingUid, componentUid)
13858                || componentAppId == Process.SYSTEM_UID
13859                || componentAppId == Process.PHONE_UID
13860                || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid)
13861                        == PackageManager.PERMISSION_GRANTED;
13862    }
13863
13864    public int bindService(IApplicationThread caller, IBinder token,
13865            Intent service, String resolvedType,
13866            IServiceConnection connection, int flags, int userId) {
13867        enforceNotIsolatedCaller("bindService");
13868        // Refuse possible leaked file descriptors
13869        if (service != null && service.hasFileDescriptors() == true) {
13870            throw new IllegalArgumentException("File descriptors passed in Intent");
13871        }
13872
13873        synchronized(this) {
13874            return mServices.bindServiceLocked(caller, token, service, resolvedType,
13875                    connection, flags, userId);
13876        }
13877    }
13878
13879    public boolean unbindService(IServiceConnection connection) {
13880        synchronized (this) {
13881            return mServices.unbindServiceLocked(connection);
13882        }
13883    }
13884
13885    public void publishService(IBinder token, Intent intent, IBinder service) {
13886        // Refuse possible leaked file descriptors
13887        if (intent != null && intent.hasFileDescriptors() == true) {
13888            throw new IllegalArgumentException("File descriptors passed in Intent");
13889        }
13890
13891        synchronized(this) {
13892            if (!(token instanceof ServiceRecord)) {
13893                throw new IllegalArgumentException("Invalid service token");
13894            }
13895            mServices.publishServiceLocked((ServiceRecord)token, intent, service);
13896        }
13897    }
13898
13899    public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
13900        // Refuse possible leaked file descriptors
13901        if (intent != null && intent.hasFileDescriptors() == true) {
13902            throw new IllegalArgumentException("File descriptors passed in Intent");
13903        }
13904
13905        synchronized(this) {
13906            mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
13907        }
13908    }
13909
13910    public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
13911        synchronized(this) {
13912            if (!(token instanceof ServiceRecord)) {
13913                throw new IllegalArgumentException("Invalid service token");
13914            }
13915            mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
13916        }
13917    }
13918
13919    // =========================================================
13920    // BACKUP AND RESTORE
13921    // =========================================================
13922
13923    // Cause the target app to be launched if necessary and its backup agent
13924    // instantiated.  The backup agent will invoke backupAgentCreated() on the
13925    // activity manager to announce its creation.
13926    public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
13927        if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
13928        enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
13929
13930        synchronized(this) {
13931            // !!! TODO: currently no check here that we're already bound
13932            BatteryStatsImpl.Uid.Pkg.Serv ss = null;
13933            BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13934            synchronized (stats) {
13935                ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
13936            }
13937
13938            // Backup agent is now in use, its package can't be stopped.
13939            try {
13940                AppGlobals.getPackageManager().setPackageStoppedState(
13941                        app.packageName, false, UserHandle.getUserId(app.uid));
13942            } catch (RemoteException e) {
13943            } catch (IllegalArgumentException e) {
13944                Slog.w(TAG, "Failed trying to unstop package "
13945                        + app.packageName + ": " + e);
13946            }
13947
13948            BackupRecord r = new BackupRecord(ss, app, backupMode);
13949            ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
13950                    ? new ComponentName(app.packageName, app.backupAgentName)
13951                    : new ComponentName("android", "FullBackupAgent");
13952            // startProcessLocked() returns existing proc's record if it's already running
13953            ProcessRecord proc = startProcessLocked(app.processName, app,
13954                    false, 0, "backup", hostingName, false, false, false);
13955            if (proc == null) {
13956                Slog.e(TAG, "Unable to start backup agent process " + r);
13957                return false;
13958            }
13959
13960            r.app = proc;
13961            mBackupTarget = r;
13962            mBackupAppName = app.packageName;
13963
13964            // Try not to kill the process during backup
13965            updateOomAdjLocked(proc);
13966
13967            // If the process is already attached, schedule the creation of the backup agent now.
13968            // If it is not yet live, this will be done when it attaches to the framework.
13969            if (proc.thread != null) {
13970                if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
13971                try {
13972                    proc.thread.scheduleCreateBackupAgent(app,
13973                            compatibilityInfoForPackageLocked(app), backupMode);
13974                } catch (RemoteException e) {
13975                    // Will time out on the backup manager side
13976                }
13977            } else {
13978                if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
13979            }
13980            // Invariants: at this point, the target app process exists and the application
13981            // is either already running or in the process of coming up.  mBackupTarget and
13982            // mBackupAppName describe the app, so that when it binds back to the AM we
13983            // know that it's scheduled for a backup-agent operation.
13984        }
13985
13986        return true;
13987    }
13988
13989    @Override
13990    public void clearPendingBackup() {
13991        if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
13992        enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
13993
13994        synchronized (this) {
13995            mBackupTarget = null;
13996            mBackupAppName = null;
13997        }
13998    }
13999
14000    // A backup agent has just come up
14001    public void backupAgentCreated(String agentPackageName, IBinder agent) {
14002        if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
14003                + " = " + agent);
14004
14005        synchronized(this) {
14006            if (!agentPackageName.equals(mBackupAppName)) {
14007                Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
14008                return;
14009            }
14010        }
14011
14012        long oldIdent = Binder.clearCallingIdentity();
14013        try {
14014            IBackupManager bm = IBackupManager.Stub.asInterface(
14015                    ServiceManager.getService(Context.BACKUP_SERVICE));
14016            bm.agentConnected(agentPackageName, agent);
14017        } catch (RemoteException e) {
14018            // can't happen; the backup manager service is local
14019        } catch (Exception e) {
14020            Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
14021            e.printStackTrace();
14022        } finally {
14023            Binder.restoreCallingIdentity(oldIdent);
14024        }
14025    }
14026
14027    // done with this agent
14028    public void unbindBackupAgent(ApplicationInfo appInfo) {
14029        if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
14030        if (appInfo == null) {
14031            Slog.w(TAG, "unbind backup agent for null app");
14032            return;
14033        }
14034
14035        synchronized(this) {
14036            try {
14037                if (mBackupAppName == null) {
14038                    Slog.w(TAG, "Unbinding backup agent with no active backup");
14039                    return;
14040                }
14041
14042                if (!mBackupAppName.equals(appInfo.packageName)) {
14043                    Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
14044                    return;
14045                }
14046
14047                // Not backing this app up any more; reset its OOM adjustment
14048                final ProcessRecord proc = mBackupTarget.app;
14049                updateOomAdjLocked(proc);
14050
14051                // If the app crashed during backup, 'thread' will be null here
14052                if (proc.thread != null) {
14053                    try {
14054                        proc.thread.scheduleDestroyBackupAgent(appInfo,
14055                                compatibilityInfoForPackageLocked(appInfo));
14056                    } catch (Exception e) {
14057                        Slog.e(TAG, "Exception when unbinding backup agent:");
14058                        e.printStackTrace();
14059                    }
14060                }
14061            } finally {
14062                mBackupTarget = null;
14063                mBackupAppName = null;
14064            }
14065        }
14066    }
14067    // =========================================================
14068    // BROADCASTS
14069    // =========================================================
14070
14071    private final List getStickiesLocked(String action, IntentFilter filter,
14072            List cur, int userId) {
14073        final ContentResolver resolver = mContext.getContentResolver();
14074        ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
14075        if (stickies == null) {
14076            return cur;
14077        }
14078        final ArrayList<Intent> list = stickies.get(action);
14079        if (list == null) {
14080            return cur;
14081        }
14082        int N = list.size();
14083        for (int i=0; i<N; i++) {
14084            Intent intent = list.get(i);
14085            if (filter.match(resolver, intent, true, TAG) >= 0) {
14086                if (cur == null) {
14087                    cur = new ArrayList<Intent>();
14088                }
14089                cur.add(intent);
14090            }
14091        }
14092        return cur;
14093    }
14094
14095    boolean isPendingBroadcastProcessLocked(int pid) {
14096        return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
14097                || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
14098    }
14099
14100    void skipPendingBroadcastLocked(int pid) {
14101            Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
14102            for (BroadcastQueue queue : mBroadcastQueues) {
14103                queue.skipPendingBroadcastLocked(pid);
14104            }
14105    }
14106
14107    // The app just attached; send any pending broadcasts that it should receive
14108    boolean sendPendingBroadcastsLocked(ProcessRecord app) {
14109        boolean didSomething = false;
14110        for (BroadcastQueue queue : mBroadcastQueues) {
14111            didSomething |= queue.sendPendingBroadcastsLocked(app);
14112        }
14113        return didSomething;
14114    }
14115
14116    public Intent registerReceiver(IApplicationThread caller, String callerPackage,
14117            IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
14118        enforceNotIsolatedCaller("registerReceiver");
14119        int callingUid;
14120        int callingPid;
14121        synchronized(this) {
14122            ProcessRecord callerApp = null;
14123            if (caller != null) {
14124                callerApp = getRecordForAppLocked(caller);
14125                if (callerApp == null) {
14126                    throw new SecurityException(
14127                            "Unable to find app for caller " + caller
14128                            + " (pid=" + Binder.getCallingPid()
14129                            + ") when registering receiver " + receiver);
14130                }
14131                if (callerApp.info.uid != Process.SYSTEM_UID &&
14132                        !callerApp.pkgList.containsKey(callerPackage) &&
14133                        !"android".equals(callerPackage)) {
14134                    throw new SecurityException("Given caller package " + callerPackage
14135                            + " is not running in process " + callerApp);
14136                }
14137                callingUid = callerApp.info.uid;
14138                callingPid = callerApp.pid;
14139            } else {
14140                callerPackage = null;
14141                callingUid = Binder.getCallingUid();
14142                callingPid = Binder.getCallingPid();
14143            }
14144
14145            userId = this.handleIncomingUser(callingPid, callingUid, userId,
14146                    true, ALLOW_FULL_ONLY, "registerReceiver", callerPackage);
14147
14148            List allSticky = null;
14149
14150            // Look for any matching sticky broadcasts...
14151            Iterator actions = filter.actionsIterator();
14152            if (actions != null) {
14153                while (actions.hasNext()) {
14154                    String action = (String)actions.next();
14155                    allSticky = getStickiesLocked(action, filter, allSticky,
14156                            UserHandle.USER_ALL);
14157                    allSticky = getStickiesLocked(action, filter, allSticky,
14158                            UserHandle.getUserId(callingUid));
14159                }
14160            } else {
14161                allSticky = getStickiesLocked(null, filter, allSticky,
14162                        UserHandle.USER_ALL);
14163                allSticky = getStickiesLocked(null, filter, allSticky,
14164                        UserHandle.getUserId(callingUid));
14165            }
14166
14167            // The first sticky in the list is returned directly back to
14168            // the client.
14169            Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
14170
14171            if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
14172                    + ": " + sticky);
14173
14174            if (receiver == null) {
14175                return sticky;
14176            }
14177
14178            ReceiverList rl
14179                = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
14180            if (rl == null) {
14181                rl = new ReceiverList(this, callerApp, callingPid, callingUid,
14182                        userId, receiver);
14183                if (rl.app != null) {
14184                    rl.app.receivers.add(rl);
14185                } else {
14186                    try {
14187                        receiver.asBinder().linkToDeath(rl, 0);
14188                    } catch (RemoteException e) {
14189                        return sticky;
14190                    }
14191                    rl.linkedToDeath = true;
14192                }
14193                mRegisteredReceivers.put(receiver.asBinder(), rl);
14194            } else if (rl.uid != callingUid) {
14195                throw new IllegalArgumentException(
14196                        "Receiver requested to register for uid " + callingUid
14197                        + " was previously registered for uid " + rl.uid);
14198            } else if (rl.pid != callingPid) {
14199                throw new IllegalArgumentException(
14200                        "Receiver requested to register for pid " + callingPid
14201                        + " was previously registered for pid " + rl.pid);
14202            } else if (rl.userId != userId) {
14203                throw new IllegalArgumentException(
14204                        "Receiver requested to register for user " + userId
14205                        + " was previously registered for user " + rl.userId);
14206            }
14207            BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
14208                    permission, callingUid, userId);
14209            rl.add(bf);
14210            if (!bf.debugCheck()) {
14211                Slog.w(TAG, "==> For Dynamic broadast");
14212            }
14213            mReceiverResolver.addFilter(bf);
14214
14215            // Enqueue broadcasts for all existing stickies that match
14216            // this filter.
14217            if (allSticky != null) {
14218                ArrayList receivers = new ArrayList();
14219                receivers.add(bf);
14220
14221                int N = allSticky.size();
14222                for (int i=0; i<N; i++) {
14223                    Intent intent = (Intent)allSticky.get(i);
14224                    BroadcastQueue queue = broadcastQueueForIntent(intent);
14225                    BroadcastRecord r = new BroadcastRecord(queue, intent, null,
14226                            null, -1, -1, null, null, AppOpsManager.OP_NONE, receivers, null, 0,
14227                            null, null, false, true, true, -1);
14228                    queue.enqueueParallelBroadcastLocked(r);
14229                    queue.scheduleBroadcastsLocked();
14230                }
14231            }
14232
14233            return sticky;
14234        }
14235    }
14236
14237    public void unregisterReceiver(IIntentReceiver receiver) {
14238        if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
14239
14240        final long origId = Binder.clearCallingIdentity();
14241        try {
14242            boolean doTrim = false;
14243
14244            synchronized(this) {
14245                ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder());
14246                if (rl != null) {
14247                    if (rl.curBroadcast != null) {
14248                        BroadcastRecord r = rl.curBroadcast;
14249                        final boolean doNext = finishReceiverLocked(
14250                                receiver.asBinder(), r.resultCode, r.resultData,
14251                                r.resultExtras, r.resultAbort);
14252                        if (doNext) {
14253                            doTrim = true;
14254                            r.queue.processNextBroadcast(false);
14255                        }
14256                    }
14257
14258                    if (rl.app != null) {
14259                        rl.app.receivers.remove(rl);
14260                    }
14261                    removeReceiverLocked(rl);
14262                    if (rl.linkedToDeath) {
14263                        rl.linkedToDeath = false;
14264                        rl.receiver.asBinder().unlinkToDeath(rl, 0);
14265                    }
14266                }
14267            }
14268
14269            // If we actually concluded any broadcasts, we might now be able
14270            // to trim the recipients' apps from our working set
14271            if (doTrim) {
14272                trimApplications();
14273                return;
14274            }
14275
14276        } finally {
14277            Binder.restoreCallingIdentity(origId);
14278        }
14279    }
14280
14281    void removeReceiverLocked(ReceiverList rl) {
14282        mRegisteredReceivers.remove(rl.receiver.asBinder());
14283        int N = rl.size();
14284        for (int i=0; i<N; i++) {
14285            mReceiverResolver.removeFilter(rl.get(i));
14286        }
14287    }
14288
14289    private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
14290        for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14291            ProcessRecord r = mLruProcesses.get(i);
14292            if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
14293                try {
14294                    r.thread.dispatchPackageBroadcast(cmd, packages);
14295                } catch (RemoteException ex) {
14296                }
14297            }
14298        }
14299    }
14300
14301    private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
14302            int[] users) {
14303        List<ResolveInfo> receivers = null;
14304        try {
14305            HashSet<ComponentName> singleUserReceivers = null;
14306            boolean scannedFirstReceivers = false;
14307            for (int user : users) {
14308                List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
14309                        .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
14310                if (user != 0 && newReceivers != null) {
14311                    // If this is not the primary user, we need to check for
14312                    // any receivers that should be filtered out.
14313                    for (int i=0; i<newReceivers.size(); i++) {
14314                        ResolveInfo ri = newReceivers.get(i);
14315                        if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
14316                            newReceivers.remove(i);
14317                            i--;
14318                        }
14319                    }
14320                }
14321                if (newReceivers != null && newReceivers.size() == 0) {
14322                    newReceivers = null;
14323                }
14324                if (receivers == null) {
14325                    receivers = newReceivers;
14326                } else if (newReceivers != null) {
14327                    // We need to concatenate the additional receivers
14328                    // found with what we have do far.  This would be easy,
14329                    // but we also need to de-dup any receivers that are
14330                    // singleUser.
14331                    if (!scannedFirstReceivers) {
14332                        // Collect any single user receivers we had already retrieved.
14333                        scannedFirstReceivers = true;
14334                        for (int i=0; i<receivers.size(); i++) {
14335                            ResolveInfo ri = receivers.get(i);
14336                            if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14337                                ComponentName cn = new ComponentName(
14338                                        ri.activityInfo.packageName, ri.activityInfo.name);
14339                                if (singleUserReceivers == null) {
14340                                    singleUserReceivers = new HashSet<ComponentName>();
14341                                }
14342                                singleUserReceivers.add(cn);
14343                            }
14344                        }
14345                    }
14346                    // Add the new results to the existing results, tracking
14347                    // and de-dupping single user receivers.
14348                    for (int i=0; i<newReceivers.size(); i++) {
14349                        ResolveInfo ri = newReceivers.get(i);
14350                        if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
14351                            ComponentName cn = new ComponentName(
14352                                    ri.activityInfo.packageName, ri.activityInfo.name);
14353                            if (singleUserReceivers == null) {
14354                                singleUserReceivers = new HashSet<ComponentName>();
14355                            }
14356                            if (!singleUserReceivers.contains(cn)) {
14357                                singleUserReceivers.add(cn);
14358                                receivers.add(ri);
14359                            }
14360                        } else {
14361                            receivers.add(ri);
14362                        }
14363                    }
14364                }
14365            }
14366        } catch (RemoteException ex) {
14367            // pm is in same process, this will never happen.
14368        }
14369        return receivers;
14370    }
14371
14372    private final int broadcastIntentLocked(ProcessRecord callerApp,
14373            String callerPackage, Intent intent, String resolvedType,
14374            IIntentReceiver resultTo, int resultCode, String resultData,
14375            Bundle map, String requiredPermission, int appOp,
14376            boolean ordered, boolean sticky, int callingPid, int callingUid,
14377            int userId) {
14378        intent = new Intent(intent);
14379
14380        // By default broadcasts do not go to stopped apps.
14381        intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
14382
14383        if (DEBUG_BROADCAST_LIGHT) Slog.v(
14384            TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
14385            + " ordered=" + ordered + " userid=" + userId);
14386        if ((resultTo != null) && !ordered) {
14387            Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
14388        }
14389
14390        userId = handleIncomingUser(callingPid, callingUid, userId,
14391                true, ALLOW_NON_FULL, "broadcast", callerPackage);
14392
14393        // Make sure that the user who is receiving this broadcast is started.
14394        // If not, we will just skip it.
14395
14396
14397        if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
14398            if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
14399                    & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
14400                Slog.w(TAG, "Skipping broadcast of " + intent
14401                        + ": user " + userId + " is stopped");
14402                return ActivityManager.BROADCAST_SUCCESS;
14403            }
14404        }
14405
14406        /*
14407         * Prevent non-system code (defined here to be non-persistent
14408         * processes) from sending protected broadcasts.
14409         */
14410        int callingAppId = UserHandle.getAppId(callingUid);
14411        if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
14412            || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID
14413            || callingAppId == Process.NFC_UID || callingUid == 0) {
14414            // Always okay.
14415        } else if (callerApp == null || !callerApp.persistent) {
14416            try {
14417                if (AppGlobals.getPackageManager().isProtectedBroadcast(
14418                        intent.getAction())) {
14419                    String msg = "Permission Denial: not allowed to send broadcast "
14420                            + intent.getAction() + " from pid="
14421                            + callingPid + ", uid=" + callingUid;
14422                    Slog.w(TAG, msg);
14423                    throw new SecurityException(msg);
14424                } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) {
14425                    // Special case for compatibility: we don't want apps to send this,
14426                    // but historically it has not been protected and apps may be using it
14427                    // to poke their own app widget.  So, instead of making it protected,
14428                    // just limit it to the caller.
14429                    if (callerApp == null) {
14430                        String msg = "Permission Denial: not allowed to send broadcast "
14431                                + intent.getAction() + " from unknown caller.";
14432                        Slog.w(TAG, msg);
14433                        throw new SecurityException(msg);
14434                    } else if (intent.getComponent() != null) {
14435                        // They are good enough to send to an explicit component...  verify
14436                        // it is being sent to the calling app.
14437                        if (!intent.getComponent().getPackageName().equals(
14438                                callerApp.info.packageName)) {
14439                            String msg = "Permission Denial: not allowed to send broadcast "
14440                                    + intent.getAction() + " to "
14441                                    + intent.getComponent().getPackageName() + " from "
14442                                    + callerApp.info.packageName;
14443                            Slog.w(TAG, msg);
14444                            throw new SecurityException(msg);
14445                        }
14446                    } else {
14447                        // Limit broadcast to their own package.
14448                        intent.setPackage(callerApp.info.packageName);
14449                    }
14450                }
14451            } catch (RemoteException e) {
14452                Slog.w(TAG, "Remote exception", e);
14453                return ActivityManager.BROADCAST_SUCCESS;
14454            }
14455        }
14456
14457        // Handle special intents: if this broadcast is from the package
14458        // manager about a package being removed, we need to remove all of
14459        // its activities from the history stack.
14460        final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
14461                intent.getAction());
14462        if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
14463                || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
14464                || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
14465                || uidRemoved) {
14466            if (checkComponentPermission(
14467                    android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
14468                    callingPid, callingUid, -1, true)
14469                    == PackageManager.PERMISSION_GRANTED) {
14470                if (uidRemoved) {
14471                    final Bundle intentExtras = intent.getExtras();
14472                    final int uid = intentExtras != null
14473                            ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
14474                    if (uid >= 0) {
14475                        BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
14476                        synchronized (bs) {
14477                            bs.removeUidStatsLocked(uid);
14478                        }
14479                        mAppOpsService.uidRemoved(uid);
14480                    }
14481                } else {
14482                    // If resources are unavailable just force stop all
14483                    // those packages and flush the attribute cache as well.
14484                    if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
14485                        String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
14486                        if (list != null && (list.length > 0)) {
14487                            for (String pkg : list) {
14488                                forceStopPackageLocked(pkg, -1, false, true, true, false, false, userId,
14489                                        "storage unmount");
14490                            }
14491                            sendPackageBroadcastLocked(
14492                                    IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
14493                        }
14494                    } else {
14495                        Uri data = intent.getData();
14496                        String ssp;
14497                        if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
14498                            boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(
14499                                    intent.getAction());
14500                            boolean fullUninstall = removed &&
14501                                    !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
14502                            if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
14503                                forceStopPackageLocked(ssp, UserHandle.getAppId(
14504                                        intent.getIntExtra(Intent.EXTRA_UID, -1)), false, true, true,
14505                                        false, fullUninstall, userId,
14506                                        removed ? "pkg removed" : "pkg changed");
14507                            }
14508                            if (removed) {
14509                                sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
14510                                        new String[] {ssp}, userId);
14511                                if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
14512                                    mAppOpsService.packageRemoved(
14513                                            intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
14514
14515                                    // Remove all permissions granted from/to this package
14516                                    removeUriPermissionsForPackageLocked(ssp, userId, true);
14517                                }
14518                            }
14519                        }
14520                    }
14521                }
14522            } else {
14523                String msg = "Permission Denial: " + intent.getAction()
14524                        + " broadcast from " + callerPackage + " (pid=" + callingPid
14525                        + ", uid=" + callingUid + ")"
14526                        + " requires "
14527                        + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
14528                Slog.w(TAG, msg);
14529                throw new SecurityException(msg);
14530            }
14531
14532        // Special case for adding a package: by default turn on compatibility
14533        // mode.
14534        } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
14535            Uri data = intent.getData();
14536            String ssp;
14537            if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
14538                mCompatModePackages.handlePackageAddedLocked(ssp,
14539                        intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
14540            }
14541        }
14542
14543        /*
14544         * If this is the time zone changed action, queue up a message that will reset the timezone
14545         * of all currently running processes. This message will get queued up before the broadcast
14546         * happens.
14547         */
14548        if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
14549            mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
14550        }
14551
14552        /*
14553         * If the user set the time, let all running processes know.
14554         */
14555        if (Intent.ACTION_TIME_CHANGED.equals(intent.getAction())) {
14556            final int is24Hour = intent.getBooleanExtra(
14557                    Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1 : 0;
14558            mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0));
14559        }
14560
14561        if (Intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
14562            mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG);
14563        }
14564
14565        if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
14566            ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO);
14567            mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy));
14568        }
14569
14570        // Add to the sticky list if requested.
14571        if (sticky) {
14572            if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
14573                    callingPid, callingUid)
14574                    != PackageManager.PERMISSION_GRANTED) {
14575                String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
14576                        + callingPid + ", uid=" + callingUid
14577                        + " requires " + android.Manifest.permission.BROADCAST_STICKY;
14578                Slog.w(TAG, msg);
14579                throw new SecurityException(msg);
14580            }
14581            if (requiredPermission != null) {
14582                Slog.w(TAG, "Can't broadcast sticky intent " + intent
14583                        + " and enforce permission " + requiredPermission);
14584                return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
14585            }
14586            if (intent.getComponent() != null) {
14587                throw new SecurityException(
14588                        "Sticky broadcasts can't target a specific component");
14589            }
14590            // We use userId directly here, since the "all" target is maintained
14591            // as a separate set of sticky broadcasts.
14592            if (userId != UserHandle.USER_ALL) {
14593                // But first, if this is not a broadcast to all users, then
14594                // make sure it doesn't conflict with an existing broadcast to
14595                // all users.
14596                ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
14597                        UserHandle.USER_ALL);
14598                if (stickies != null) {
14599                    ArrayList<Intent> list = stickies.get(intent.getAction());
14600                    if (list != null) {
14601                        int N = list.size();
14602                        int i;
14603                        for (i=0; i<N; i++) {
14604                            if (intent.filterEquals(list.get(i))) {
14605                                throw new IllegalArgumentException(
14606                                        "Sticky broadcast " + intent + " for user "
14607                                        + userId + " conflicts with existing global broadcast");
14608                            }
14609                        }
14610                    }
14611                }
14612            }
14613            ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
14614            if (stickies == null) {
14615                stickies = new ArrayMap<String, ArrayList<Intent>>();
14616                mStickyBroadcasts.put(userId, stickies);
14617            }
14618            ArrayList<Intent> list = stickies.get(intent.getAction());
14619            if (list == null) {
14620                list = new ArrayList<Intent>();
14621                stickies.put(intent.getAction(), list);
14622            }
14623            int N = list.size();
14624            int i;
14625            for (i=0; i<N; i++) {
14626                if (intent.filterEquals(list.get(i))) {
14627                    // This sticky already exists, replace it.
14628                    list.set(i, new Intent(intent));
14629                    break;
14630                }
14631            }
14632            if (i >= N) {
14633                list.add(new Intent(intent));
14634            }
14635        }
14636
14637        int[] users;
14638        if (userId == UserHandle.USER_ALL) {
14639            // Caller wants broadcast to go to all started users.
14640            users = mStartedUserArray;
14641        } else {
14642            // Caller wants broadcast to go to one specific user.
14643            users = new int[] {userId};
14644        }
14645
14646        // Figure out who all will receive this broadcast.
14647        List receivers = null;
14648        List<BroadcastFilter> registeredReceivers = null;
14649        // Need to resolve the intent to interested receivers...
14650        if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
14651                 == 0) {
14652            receivers = collectReceiverComponents(intent, resolvedType, users);
14653        }
14654        if (intent.getComponent() == null) {
14655            registeredReceivers = mReceiverResolver.queryIntent(intent,
14656                    resolvedType, false, userId);
14657        }
14658
14659        final boolean replacePending =
14660                (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
14661
14662        if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
14663                + " replacePending=" + replacePending);
14664
14665        int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
14666        if (!ordered && NR > 0) {
14667            // If we are not serializing this broadcast, then send the
14668            // registered receivers separately so they don't wait for the
14669            // components to be launched.
14670            final BroadcastQueue queue = broadcastQueueForIntent(intent);
14671            BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
14672                    callerPackage, callingPid, callingUid, resolvedType, requiredPermission,
14673                    appOp, registeredReceivers, resultTo, resultCode, resultData, map,
14674                    ordered, sticky, false, userId);
14675            if (DEBUG_BROADCAST) Slog.v(
14676                    TAG, "Enqueueing parallel broadcast " + r);
14677            final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
14678            if (!replaced) {
14679                queue.enqueueParallelBroadcastLocked(r);
14680                queue.scheduleBroadcastsLocked();
14681            }
14682            registeredReceivers = null;
14683            NR = 0;
14684        }
14685
14686        // Merge into one list.
14687        int ir = 0;
14688        if (receivers != null) {
14689            // A special case for PACKAGE_ADDED: do not allow the package
14690            // being added to see this broadcast.  This prevents them from
14691            // using this as a back door to get run as soon as they are
14692            // installed.  Maybe in the future we want to have a special install
14693            // broadcast or such for apps, but we'd like to deliberately make
14694            // this decision.
14695            String skipPackages[] = null;
14696            if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
14697                    || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
14698                    || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
14699                Uri data = intent.getData();
14700                if (data != null) {
14701                    String pkgName = data.getSchemeSpecificPart();
14702                    if (pkgName != null) {
14703                        skipPackages = new String[] { pkgName };
14704                    }
14705                }
14706            } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
14707                skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
14708            }
14709            if (skipPackages != null && (skipPackages.length > 0)) {
14710                for (String skipPackage : skipPackages) {
14711                    if (skipPackage != null) {
14712                        int NT = receivers.size();
14713                        for (int it=0; it<NT; it++) {
14714                            ResolveInfo curt = (ResolveInfo)receivers.get(it);
14715                            if (curt.activityInfo.packageName.equals(skipPackage)) {
14716                                receivers.remove(it);
14717                                it--;
14718                                NT--;
14719                            }
14720                        }
14721                    }
14722                }
14723            }
14724
14725            int NT = receivers != null ? receivers.size() : 0;
14726            int it = 0;
14727            ResolveInfo curt = null;
14728            BroadcastFilter curr = null;
14729            while (it < NT && ir < NR) {
14730                if (curt == null) {
14731                    curt = (ResolveInfo)receivers.get(it);
14732                }
14733                if (curr == null) {
14734                    curr = registeredReceivers.get(ir);
14735                }
14736                if (curr.getPriority() >= curt.priority) {
14737                    // Insert this broadcast record into the final list.
14738                    receivers.add(it, curr);
14739                    ir++;
14740                    curr = null;
14741                    it++;
14742                    NT++;
14743                } else {
14744                    // Skip to the next ResolveInfo in the final list.
14745                    it++;
14746                    curt = null;
14747                }
14748            }
14749        }
14750        while (ir < NR) {
14751            if (receivers == null) {
14752                receivers = new ArrayList();
14753            }
14754            receivers.add(registeredReceivers.get(ir));
14755            ir++;
14756        }
14757
14758        if ((receivers != null && receivers.size() > 0)
14759                || resultTo != null) {
14760            BroadcastQueue queue = broadcastQueueForIntent(intent);
14761            BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
14762                    callerPackage, callingPid, callingUid, resolvedType,
14763                    requiredPermission, appOp, receivers, resultTo, resultCode,
14764                    resultData, map, ordered, sticky, false, userId);
14765            if (DEBUG_BROADCAST) Slog.v(
14766                    TAG, "Enqueueing ordered broadcast " + r
14767                    + ": prev had " + queue.mOrderedBroadcasts.size());
14768            if (DEBUG_BROADCAST) {
14769                int seq = r.intent.getIntExtra("seq", -1);
14770                Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
14771            }
14772            boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
14773            if (!replaced) {
14774                queue.enqueueOrderedBroadcastLocked(r);
14775                queue.scheduleBroadcastsLocked();
14776            }
14777        }
14778
14779        return ActivityManager.BROADCAST_SUCCESS;
14780    }
14781
14782    final Intent verifyBroadcastLocked(Intent intent) {
14783        // Refuse possible leaked file descriptors
14784        if (intent != null && intent.hasFileDescriptors() == true) {
14785            throw new IllegalArgumentException("File descriptors passed in Intent");
14786        }
14787
14788        int flags = intent.getFlags();
14789
14790        if (!mProcessesReady) {
14791            // if the caller really truly claims to know what they're doing, go
14792            // ahead and allow the broadcast without launching any receivers
14793            if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
14794                intent = new Intent(intent);
14795                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14796            } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
14797                Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
14798                        + " before boot completion");
14799                throw new IllegalStateException("Cannot broadcast before boot completed");
14800            }
14801        }
14802
14803        if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
14804            throw new IllegalArgumentException(
14805                    "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
14806        }
14807
14808        return intent;
14809    }
14810
14811    public final int broadcastIntent(IApplicationThread caller,
14812            Intent intent, String resolvedType, IIntentReceiver resultTo,
14813            int resultCode, String resultData, Bundle map,
14814            String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
14815        enforceNotIsolatedCaller("broadcastIntent");
14816        synchronized(this) {
14817            intent = verifyBroadcastLocked(intent);
14818
14819            final ProcessRecord callerApp = getRecordForAppLocked(caller);
14820            final int callingPid = Binder.getCallingPid();
14821            final int callingUid = Binder.getCallingUid();
14822            final long origId = Binder.clearCallingIdentity();
14823            int res = broadcastIntentLocked(callerApp,
14824                    callerApp != null ? callerApp.info.packageName : null,
14825                    intent, resolvedType, resultTo,
14826                    resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
14827                    callingPid, callingUid, userId);
14828            Binder.restoreCallingIdentity(origId);
14829            return res;
14830        }
14831    }
14832
14833    int broadcastIntentInPackage(String packageName, int uid,
14834            Intent intent, String resolvedType, IIntentReceiver resultTo,
14835            int resultCode, String resultData, Bundle map,
14836            String requiredPermission, boolean serialized, boolean sticky, int userId) {
14837        synchronized(this) {
14838            intent = verifyBroadcastLocked(intent);
14839
14840            final long origId = Binder.clearCallingIdentity();
14841            int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
14842                    resultTo, resultCode, resultData, map, requiredPermission,
14843                    AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
14844            Binder.restoreCallingIdentity(origId);
14845            return res;
14846        }
14847    }
14848
14849    public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
14850        // Refuse possible leaked file descriptors
14851        if (intent != null && intent.hasFileDescriptors() == true) {
14852            throw new IllegalArgumentException("File descriptors passed in Intent");
14853        }
14854
14855        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
14856                userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null);
14857
14858        synchronized(this) {
14859            if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
14860                    != PackageManager.PERMISSION_GRANTED) {
14861                String msg = "Permission Denial: unbroadcastIntent() from pid="
14862                        + Binder.getCallingPid()
14863                        + ", uid=" + Binder.getCallingUid()
14864                        + " requires " + android.Manifest.permission.BROADCAST_STICKY;
14865                Slog.w(TAG, msg);
14866                throw new SecurityException(msg);
14867            }
14868            ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
14869            if (stickies != null) {
14870                ArrayList<Intent> list = stickies.get(intent.getAction());
14871                if (list != null) {
14872                    int N = list.size();
14873                    int i;
14874                    for (i=0; i<N; i++) {
14875                        if (intent.filterEquals(list.get(i))) {
14876                            list.remove(i);
14877                            break;
14878                        }
14879                    }
14880                    if (list.size() <= 0) {
14881                        stickies.remove(intent.getAction());
14882                    }
14883                }
14884                if (stickies.size() <= 0) {
14885                    mStickyBroadcasts.remove(userId);
14886                }
14887            }
14888        }
14889    }
14890
14891    private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
14892            String resultData, Bundle resultExtras, boolean resultAbort) {
14893        final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
14894        if (r == null) {
14895            Slog.w(TAG, "finishReceiver called but not found on queue");
14896            return false;
14897        }
14898
14899        return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort, false);
14900    }
14901
14902    void backgroundServicesFinishedLocked(int userId) {
14903        for (BroadcastQueue queue : mBroadcastQueues) {
14904            queue.backgroundServicesFinishedLocked(userId);
14905        }
14906    }
14907
14908    public void finishReceiver(IBinder who, int resultCode, String resultData,
14909            Bundle resultExtras, boolean resultAbort) {
14910        if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
14911
14912        // Refuse possible leaked file descriptors
14913        if (resultExtras != null && resultExtras.hasFileDescriptors()) {
14914            throw new IllegalArgumentException("File descriptors passed in Bundle");
14915        }
14916
14917        final long origId = Binder.clearCallingIdentity();
14918        try {
14919            boolean doNext = false;
14920            BroadcastRecord r;
14921
14922            synchronized(this) {
14923                r = broadcastRecordForReceiverLocked(who);
14924                if (r != null) {
14925                    doNext = r.queue.finishReceiverLocked(r, resultCode,
14926                        resultData, resultExtras, resultAbort, true);
14927                }
14928            }
14929
14930            if (doNext) {
14931                r.queue.processNextBroadcast(false);
14932            }
14933            trimApplications();
14934        } finally {
14935            Binder.restoreCallingIdentity(origId);
14936        }
14937    }
14938
14939    // =========================================================
14940    // INSTRUMENTATION
14941    // =========================================================
14942
14943    public boolean startInstrumentation(ComponentName className,
14944            String profileFile, int flags, Bundle arguments,
14945            IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
14946            int userId, String abiOverride) {
14947        enforceNotIsolatedCaller("startInstrumentation");
14948        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
14949                userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null);
14950        // Refuse possible leaked file descriptors
14951        if (arguments != null && arguments.hasFileDescriptors()) {
14952            throw new IllegalArgumentException("File descriptors passed in Bundle");
14953        }
14954
14955        synchronized(this) {
14956            InstrumentationInfo ii = null;
14957            ApplicationInfo ai = null;
14958            try {
14959                ii = mContext.getPackageManager().getInstrumentationInfo(
14960                    className, STOCK_PM_FLAGS);
14961                ai = AppGlobals.getPackageManager().getApplicationInfo(
14962                        ii.targetPackage, STOCK_PM_FLAGS, userId);
14963            } catch (PackageManager.NameNotFoundException e) {
14964            } catch (RemoteException e) {
14965            }
14966            if (ii == null) {
14967                reportStartInstrumentationFailure(watcher, className,
14968                        "Unable to find instrumentation info for: " + className);
14969                return false;
14970            }
14971            if (ai == null) {
14972                reportStartInstrumentationFailure(watcher, className,
14973                        "Unable to find instrumentation target package: " + ii.targetPackage);
14974                return false;
14975            }
14976
14977            int match = mContext.getPackageManager().checkSignatures(
14978                    ii.targetPackage, ii.packageName);
14979            if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
14980                String msg = "Permission Denial: starting instrumentation "
14981                        + className + " from pid="
14982                        + Binder.getCallingPid()
14983                        + ", uid=" + Binder.getCallingPid()
14984                        + " not allowed because package " + ii.packageName
14985                        + " does not have a signature matching the target "
14986                        + ii.targetPackage;
14987                reportStartInstrumentationFailure(watcher, className, msg);
14988                throw new SecurityException(msg);
14989            }
14990
14991            final long origId = Binder.clearCallingIdentity();
14992            // Instrumentation can kill and relaunch even persistent processes
14993            forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId,
14994                    "start instr");
14995            ProcessRecord app = addAppLocked(ai, false, abiOverride);
14996            app.instrumentationClass = className;
14997            app.instrumentationInfo = ai;
14998            app.instrumentationProfileFile = profileFile;
14999            app.instrumentationArguments = arguments;
15000            app.instrumentationWatcher = watcher;
15001            app.instrumentationUiAutomationConnection = uiAutomationConnection;
15002            app.instrumentationResultClass = className;
15003            Binder.restoreCallingIdentity(origId);
15004        }
15005
15006        return true;
15007    }
15008
15009    /**
15010     * Report errors that occur while attempting to start Instrumentation.  Always writes the
15011     * error to the logs, but if somebody is watching, send the report there too.  This enables
15012     * the "am" command to report errors with more information.
15013     *
15014     * @param watcher The IInstrumentationWatcher.  Null if there isn't one.
15015     * @param cn The component name of the instrumentation.
15016     * @param report The error report.
15017     */
15018    private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
15019            ComponentName cn, String report) {
15020        Slog.w(TAG, report);
15021        try {
15022            if (watcher != null) {
15023                Bundle results = new Bundle();
15024                results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
15025                results.putString("Error", report);
15026                watcher.instrumentationStatus(cn, -1, results);
15027            }
15028        } catch (RemoteException e) {
15029            Slog.w(TAG, e);
15030        }
15031    }
15032
15033    void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
15034        if (app.instrumentationWatcher != null) {
15035            try {
15036                // NOTE:  IInstrumentationWatcher *must* be oneway here
15037                app.instrumentationWatcher.instrumentationFinished(
15038                    app.instrumentationClass,
15039                    resultCode,
15040                    results);
15041            } catch (RemoteException e) {
15042            }
15043        }
15044        if (app.instrumentationUiAutomationConnection != null) {
15045            try {
15046                app.instrumentationUiAutomationConnection.shutdown();
15047            } catch (RemoteException re) {
15048                /* ignore */
15049            }
15050            // Only a UiAutomation can set this flag and now that
15051            // it is finished we make sure it is reset to its default.
15052            mUserIsMonkey = false;
15053        }
15054        app.instrumentationWatcher = null;
15055        app.instrumentationUiAutomationConnection = null;
15056        app.instrumentationClass = null;
15057        app.instrumentationInfo = null;
15058        app.instrumentationProfileFile = null;
15059        app.instrumentationArguments = null;
15060
15061        forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId,
15062                "finished inst");
15063    }
15064
15065    public void finishInstrumentation(IApplicationThread target,
15066            int resultCode, Bundle results) {
15067        int userId = UserHandle.getCallingUserId();
15068        // Refuse possible leaked file descriptors
15069        if (results != null && results.hasFileDescriptors()) {
15070            throw new IllegalArgumentException("File descriptors passed in Intent");
15071        }
15072
15073        synchronized(this) {
15074            ProcessRecord app = getRecordForAppLocked(target);
15075            if (app == null) {
15076                Slog.w(TAG, "finishInstrumentation: no app for " + target);
15077                return;
15078            }
15079            final long origId = Binder.clearCallingIdentity();
15080            finishInstrumentationLocked(app, resultCode, results);
15081            Binder.restoreCallingIdentity(origId);
15082        }
15083    }
15084
15085    // =========================================================
15086    // CONFIGURATION
15087    // =========================================================
15088
15089    public ConfigurationInfo getDeviceConfigurationInfo() {
15090        ConfigurationInfo config = new ConfigurationInfo();
15091        synchronized (this) {
15092            config.reqTouchScreen = mConfiguration.touchscreen;
15093            config.reqKeyboardType = mConfiguration.keyboard;
15094            config.reqNavigation = mConfiguration.navigation;
15095            if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
15096                    || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
15097                config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
15098            }
15099            if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
15100                    && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
15101                config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
15102            }
15103            config.reqGlEsVersion = GL_ES_VERSION;
15104        }
15105        return config;
15106    }
15107
15108    ActivityStack getFocusedStack() {
15109        return mStackSupervisor.getFocusedStack();
15110    }
15111
15112    public Configuration getConfiguration() {
15113        Configuration ci;
15114        synchronized(this) {
15115            ci = new Configuration(mConfiguration);
15116        }
15117        return ci;
15118    }
15119
15120    public void updatePersistentConfiguration(Configuration values) {
15121        enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
15122                "updateConfiguration()");
15123        enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
15124                "updateConfiguration()");
15125        if (values == null) {
15126            throw new NullPointerException("Configuration must not be null");
15127        }
15128
15129        synchronized(this) {
15130            final long origId = Binder.clearCallingIdentity();
15131            updateConfigurationLocked(values, null, true, false);
15132            Binder.restoreCallingIdentity(origId);
15133        }
15134    }
15135
15136    public void updateConfiguration(Configuration values) {
15137        enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
15138                "updateConfiguration()");
15139
15140        synchronized(this) {
15141            if (values == null && mWindowManager != null) {
15142                // sentinel: fetch the current configuration from the window manager
15143                values = mWindowManager.computeNewConfiguration();
15144            }
15145
15146            if (mWindowManager != null) {
15147                mProcessList.applyDisplaySize(mWindowManager);
15148            }
15149
15150            final long origId = Binder.clearCallingIdentity();
15151            if (values != null) {
15152                Settings.System.clearConfiguration(values);
15153            }
15154            updateConfigurationLocked(values, null, false, false);
15155            Binder.restoreCallingIdentity(origId);
15156        }
15157    }
15158
15159    /**
15160     * Do either or both things: (1) change the current configuration, and (2)
15161     * make sure the given activity is running with the (now) current
15162     * configuration.  Returns true if the activity has been left running, or
15163     * false if <var>starting</var> is being destroyed to match the new
15164     * configuration.
15165     * @param persistent TODO
15166     */
15167    boolean updateConfigurationLocked(Configuration values,
15168            ActivityRecord starting, boolean persistent, boolean initLocale) {
15169        int changes = 0;
15170
15171        if (values != null) {
15172            Configuration newConfig = new Configuration(mConfiguration);
15173            changes = newConfig.updateFrom(values);
15174            if (changes != 0) {
15175                if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
15176                    Slog.i(TAG, "Updating configuration to: " + values);
15177                }
15178
15179                EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
15180
15181                if (values.locale != null && !initLocale) {
15182                    saveLocaleLocked(values.locale,
15183                                     !values.locale.equals(mConfiguration.locale),
15184                                     values.userSetLocale);
15185                }
15186
15187                mConfigurationSeq++;
15188                if (mConfigurationSeq <= 0) {
15189                    mConfigurationSeq = 1;
15190                }
15191                newConfig.seq = mConfigurationSeq;
15192                mConfiguration = newConfig;
15193                Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
15194                //mUsageStatsService.noteStartConfig(newConfig);
15195
15196                final Configuration configCopy = new Configuration(mConfiguration);
15197
15198                // TODO: If our config changes, should we auto dismiss any currently
15199                // showing dialogs?
15200                mShowDialogs = shouldShowDialogs(newConfig);
15201
15202                AttributeCache ac = AttributeCache.instance();
15203                if (ac != null) {
15204                    ac.updateConfiguration(configCopy);
15205                }
15206
15207                // Make sure all resources in our process are updated
15208                // right now, so that anyone who is going to retrieve
15209                // resource values after we return will be sure to get
15210                // the new ones.  This is especially important during
15211                // boot, where the first config change needs to guarantee
15212                // all resources have that config before following boot
15213                // code is executed.
15214                mSystemThread.applyConfigurationToResources(configCopy);
15215
15216                if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
15217                    Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
15218                    msg.obj = new Configuration(configCopy);
15219                    mHandler.sendMessage(msg);
15220                }
15221
15222                for (int i=mLruProcesses.size()-1; i>=0; i--) {
15223                    ProcessRecord app = mLruProcesses.get(i);
15224                    try {
15225                        if (app.thread != null) {
15226                            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
15227                                    + app.processName + " new config " + mConfiguration);
15228                            app.thread.scheduleConfigurationChanged(configCopy);
15229                        }
15230                    } catch (Exception e) {
15231                    }
15232                }
15233                Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
15234                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
15235                        | Intent.FLAG_RECEIVER_REPLACE_PENDING
15236                        | Intent.FLAG_RECEIVER_FOREGROUND);
15237                broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
15238                        null, AppOpsManager.OP_NONE, false, false, MY_PID,
15239                        Process.SYSTEM_UID, UserHandle.USER_ALL);
15240                if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
15241                    intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
15242                    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15243                    broadcastIntentLocked(null, null, intent,
15244                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
15245                            false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
15246                }
15247            }
15248        }
15249
15250        boolean kept = true;
15251        final ActivityStack mainStack = mStackSupervisor.getFocusedStack();
15252        // mainStack is null during startup.
15253        if (mainStack != null) {
15254            if (changes != 0 && starting == null) {
15255                // If the configuration changed, and the caller is not already
15256                // in the process of starting an activity, then find the top
15257                // activity to check if its configuration needs to change.
15258                starting = mainStack.topRunningActivityLocked(null);
15259            }
15260
15261            if (starting != null) {
15262                kept = mainStack.ensureActivityConfigurationLocked(starting, changes);
15263                // And we need to make sure at this point that all other activities
15264                // are made visible with the correct configuration.
15265                mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes);
15266            }
15267        }
15268
15269        if (values != null && mWindowManager != null) {
15270            mWindowManager.setNewConfiguration(mConfiguration);
15271        }
15272
15273        return kept;
15274    }
15275
15276    /**
15277     * Decide based on the configuration whether we should shouw the ANR,
15278     * crash, etc dialogs.  The idea is that if there is no affordnace to
15279     * press the on-screen buttons, we shouldn't show the dialog.
15280     *
15281     * A thought: SystemUI might also want to get told about this, the Power
15282     * dialog / global actions also might want different behaviors.
15283     */
15284    private static final boolean shouldShowDialogs(Configuration config) {
15285        return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
15286                && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
15287    }
15288
15289    /**
15290     * Save the locale.  You must be inside a synchronized (this) block.
15291     */
15292    private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
15293        if(isDiff) {
15294            SystemProperties.set("user.language", l.getLanguage());
15295            SystemProperties.set("user.region", l.getCountry());
15296        }
15297
15298        if(isPersist) {
15299            SystemProperties.set("persist.sys.language", l.getLanguage());
15300            SystemProperties.set("persist.sys.country", l.getCountry());
15301            SystemProperties.set("persist.sys.localevar", l.getVariant());
15302        }
15303    }
15304
15305    @Override
15306    public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
15307        ActivityRecord srec = ActivityRecord.forToken(token);
15308        return srec != null && srec.task.affinity != null &&
15309                srec.task.affinity.equals(destAffinity);
15310    }
15311
15312    public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
15313            Intent resultData) {
15314
15315        synchronized (this) {
15316            final ActivityStack stack = ActivityRecord.getStackLocked(token);
15317            if (stack != null) {
15318                return stack.navigateUpToLocked(token, destIntent, resultCode, resultData);
15319            }
15320            return false;
15321        }
15322    }
15323
15324    public int getLaunchedFromUid(IBinder activityToken) {
15325        ActivityRecord srec = ActivityRecord.forToken(activityToken);
15326        if (srec == null) {
15327            return -1;
15328        }
15329        return srec.launchedFromUid;
15330    }
15331
15332    public String getLaunchedFromPackage(IBinder activityToken) {
15333        ActivityRecord srec = ActivityRecord.forToken(activityToken);
15334        if (srec == null) {
15335            return null;
15336        }
15337        return srec.launchedFromPackage;
15338    }
15339
15340    // =========================================================
15341    // LIFETIME MANAGEMENT
15342    // =========================================================
15343
15344    // Returns which broadcast queue the app is the current [or imminent] receiver
15345    // on, or 'null' if the app is not an active broadcast recipient.
15346    private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
15347        BroadcastRecord r = app.curReceiver;
15348        if (r != null) {
15349            return r.queue;
15350        }
15351
15352        // It's not the current receiver, but it might be starting up to become one
15353        synchronized (this) {
15354            for (BroadcastQueue queue : mBroadcastQueues) {
15355                r = queue.mPendingBroadcast;
15356                if (r != null && r.curApp == app) {
15357                    // found it; report which queue it's in
15358                    return queue;
15359                }
15360            }
15361        }
15362
15363        return null;
15364    }
15365
15366    private final int computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP,
15367            boolean doingAll, long now) {
15368        if (mAdjSeq == app.adjSeq) {
15369            // This adjustment has already been computed.
15370            return app.curRawAdj;
15371        }
15372
15373        if (app.thread == null) {
15374            app.adjSeq = mAdjSeq;
15375            app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
15376            app.curProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
15377            return (app.curAdj=app.curRawAdj=ProcessList.CACHED_APP_MAX_ADJ);
15378        }
15379
15380        app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
15381        app.adjSource = null;
15382        app.adjTarget = null;
15383        app.empty = false;
15384        app.cached = false;
15385
15386        final int activitiesSize = app.activities.size();
15387
15388        if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
15389            // The max adjustment doesn't allow this app to be anything
15390            // below foreground, so it is not worth doing work for it.
15391            app.adjType = "fixed";
15392            app.adjSeq = mAdjSeq;
15393            app.curRawAdj = app.maxAdj;
15394            app.foregroundActivities = false;
15395            app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
15396            app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT;
15397            // System processes can do UI, and when they do we want to have
15398            // them trim their memory after the user leaves the UI.  To
15399            // facilitate this, here we need to determine whether or not it
15400            // is currently showing UI.
15401            app.systemNoUi = true;
15402            if (app == TOP_APP) {
15403                app.systemNoUi = false;
15404            } else if (activitiesSize > 0) {
15405                for (int j = 0; j < activitiesSize; j++) {
15406                    final ActivityRecord r = app.activities.get(j);
15407                    if (r.visible) {
15408                        app.systemNoUi = false;
15409                    }
15410                }
15411            }
15412            if (!app.systemNoUi) {
15413                app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT_UI;
15414            }
15415            return (app.curAdj=app.maxAdj);
15416        }
15417
15418        app.systemNoUi = false;
15419
15420        // Determine the importance of the process, starting with most
15421        // important to least, and assign an appropriate OOM adjustment.
15422        int adj;
15423        int schedGroup;
15424        int procState;
15425        boolean foregroundActivities = false;
15426        BroadcastQueue queue;
15427        if (app == TOP_APP) {
15428            // The last app on the list is the foreground app.
15429            adj = ProcessList.FOREGROUND_APP_ADJ;
15430            schedGroup = Process.THREAD_GROUP_DEFAULT;
15431            app.adjType = "top-activity";
15432            foregroundActivities = true;
15433            procState = ActivityManager.PROCESS_STATE_TOP;
15434        } else if (app.instrumentationClass != null) {
15435            // Don't want to kill running instrumentation.
15436            adj = ProcessList.FOREGROUND_APP_ADJ;
15437            schedGroup = Process.THREAD_GROUP_DEFAULT;
15438            app.adjType = "instrumentation";
15439            procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15440        } else if ((queue = isReceivingBroadcast(app)) != null) {
15441            // An app that is currently receiving a broadcast also
15442            // counts as being in the foreground for OOM killer purposes.
15443            // It's placed in a sched group based on the nature of the
15444            // broadcast as reflected by which queue it's active in.
15445            adj = ProcessList.FOREGROUND_APP_ADJ;
15446            schedGroup = (queue == mFgBroadcastQueue)
15447                    ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
15448            app.adjType = "broadcast";
15449            procState = ActivityManager.PROCESS_STATE_RECEIVER;
15450        } else if (app.executingServices.size() > 0) {
15451            // An app that is currently executing a service callback also
15452            // counts as being in the foreground.
15453            adj = ProcessList.FOREGROUND_APP_ADJ;
15454            schedGroup = app.execServicesFg ?
15455                    Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
15456            app.adjType = "exec-service";
15457            procState = ActivityManager.PROCESS_STATE_SERVICE;
15458            //Slog.i(TAG, "EXEC " + (app.execServicesFg ? "FG" : "BG") + ": " + app);
15459        } else {
15460            // As far as we know the process is empty.  We may change our mind later.
15461            schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
15462            // At this point we don't actually know the adjustment.  Use the cached adj
15463            // value that the caller wants us to.
15464            adj = cachedAdj;
15465            procState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
15466            app.cached = true;
15467            app.empty = true;
15468            app.adjType = "cch-empty";
15469        }
15470
15471        // Examine all activities if not already foreground.
15472        if (!foregroundActivities && activitiesSize > 0) {
15473            for (int j = 0; j < activitiesSize; j++) {
15474                final ActivityRecord r = app.activities.get(j);
15475                if (r.app != app) {
15476                    Slog.w(TAG, "Wtf, activity " + r + " in proc activity list not using proc "
15477                            + app + "?!?");
15478                    continue;
15479                }
15480                if (r.visible) {
15481                    // App has a visible activity; only upgrade adjustment.
15482                    if (adj > ProcessList.VISIBLE_APP_ADJ) {
15483                        adj = ProcessList.VISIBLE_APP_ADJ;
15484                        app.adjType = "visible";
15485                    }
15486                    if (procState > ActivityManager.PROCESS_STATE_TOP) {
15487                        procState = ActivityManager.PROCESS_STATE_TOP;
15488                    }
15489                    schedGroup = Process.THREAD_GROUP_DEFAULT;
15490                    app.cached = false;
15491                    app.empty = false;
15492                    foregroundActivities = true;
15493                    break;
15494                } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
15495                    if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
15496                        adj = ProcessList.PERCEPTIBLE_APP_ADJ;
15497                        app.adjType = "pausing";
15498                    }
15499                    if (procState > ActivityManager.PROCESS_STATE_TOP) {
15500                        procState = ActivityManager.PROCESS_STATE_TOP;
15501                    }
15502                    schedGroup = Process.THREAD_GROUP_DEFAULT;
15503                    app.cached = false;
15504                    app.empty = false;
15505                    foregroundActivities = true;
15506                } else if (r.state == ActivityState.STOPPING) {
15507                    if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
15508                        adj = ProcessList.PERCEPTIBLE_APP_ADJ;
15509                        app.adjType = "stopping";
15510                    }
15511                    // For the process state, we will at this point consider the
15512                    // process to be cached.  It will be cached either as an activity
15513                    // or empty depending on whether the activity is finishing.  We do
15514                    // this so that we can treat the process as cached for purposes of
15515                    // memory trimming (determing current memory level, trim command to
15516                    // send to process) since there can be an arbitrary number of stopping
15517                    // processes and they should soon all go into the cached state.
15518                    if (!r.finishing) {
15519                        if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
15520                            procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
15521                        }
15522                    }
15523                    app.cached = false;
15524                    app.empty = false;
15525                    foregroundActivities = true;
15526                } else {
15527                    if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
15528                        procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
15529                        app.adjType = "cch-act";
15530                    }
15531                }
15532            }
15533        }
15534
15535        if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
15536            if (app.foregroundServices) {
15537                // The user is aware of this app, so make it visible.
15538                adj = ProcessList.PERCEPTIBLE_APP_ADJ;
15539                procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15540                app.cached = false;
15541                app.adjType = "fg-service";
15542                schedGroup = Process.THREAD_GROUP_DEFAULT;
15543            } else if (app.forcingToForeground != null) {
15544                // The user is aware of this app, so make it visible.
15545                adj = ProcessList.PERCEPTIBLE_APP_ADJ;
15546                procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15547                app.cached = false;
15548                app.adjType = "force-fg";
15549                app.adjSource = app.forcingToForeground;
15550                schedGroup = Process.THREAD_GROUP_DEFAULT;
15551            }
15552        }
15553
15554        if (app == mHeavyWeightProcess) {
15555            if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ) {
15556                // We don't want to kill the current heavy-weight process.
15557                adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
15558                schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
15559                app.cached = false;
15560                app.adjType = "heavy";
15561            }
15562            if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
15563                procState = ActivityManager.PROCESS_STATE_HEAVY_WEIGHT;
15564            }
15565        }
15566
15567        if (app == mHomeProcess) {
15568            if (adj > ProcessList.HOME_APP_ADJ) {
15569                // This process is hosting what we currently consider to be the
15570                // home app, so we don't want to let it go into the background.
15571                adj = ProcessList.HOME_APP_ADJ;
15572                schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
15573                app.cached = false;
15574                app.adjType = "home";
15575            }
15576            if (procState > ActivityManager.PROCESS_STATE_HOME) {
15577                procState = ActivityManager.PROCESS_STATE_HOME;
15578            }
15579        }
15580
15581        if (app == mPreviousProcess && app.activities.size() > 0) {
15582            if (adj > ProcessList.PREVIOUS_APP_ADJ) {
15583                // This was the previous process that showed UI to the user.
15584                // We want to try to keep it around more aggressively, to give
15585                // a good experience around switching between two apps.
15586                adj = ProcessList.PREVIOUS_APP_ADJ;
15587                schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
15588                app.cached = false;
15589                app.adjType = "previous";
15590            }
15591            if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
15592                procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY;
15593            }
15594        }
15595
15596        if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
15597                + " reason=" + app.adjType);
15598
15599        // By default, we use the computed adjustment.  It may be changed if
15600        // there are applications dependent on our services or providers, but
15601        // this gives us a baseline and makes sure we don't get into an
15602        // infinite recursion.
15603        app.adjSeq = mAdjSeq;
15604        app.curRawAdj = adj;
15605        app.hasStartedServices = false;
15606
15607        if (mBackupTarget != null && app == mBackupTarget.app) {
15608            // If possible we want to avoid killing apps while they're being backed up
15609            if (adj > ProcessList.BACKUP_APP_ADJ) {
15610                if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
15611                adj = ProcessList.BACKUP_APP_ADJ;
15612                if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
15613                    procState = ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND;
15614                }
15615                app.adjType = "backup";
15616                app.cached = false;
15617            }
15618            if (procState > ActivityManager.PROCESS_STATE_BACKUP) {
15619                procState = ActivityManager.PROCESS_STATE_BACKUP;
15620            }
15621        }
15622
15623        boolean mayBeTop = false;
15624
15625        for (int is = app.services.size()-1;
15626                is >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
15627                        || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
15628                        || procState > ActivityManager.PROCESS_STATE_TOP);
15629                is--) {
15630            ServiceRecord s = app.services.valueAt(is);
15631            if (s.startRequested) {
15632                app.hasStartedServices = true;
15633                if (procState > ActivityManager.PROCESS_STATE_SERVICE) {
15634                    procState = ActivityManager.PROCESS_STATE_SERVICE;
15635                }
15636                if (app.hasShownUi && app != mHomeProcess) {
15637                    // If this process has shown some UI, let it immediately
15638                    // go to the LRU list because it may be pretty heavy with
15639                    // UI stuff.  We'll tag it with a label just to help
15640                    // debug and understand what is going on.
15641                    if (adj > ProcessList.SERVICE_ADJ) {
15642                        app.adjType = "cch-started-ui-services";
15643                    }
15644                } else {
15645                    if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
15646                        // This service has seen some activity within
15647                        // recent memory, so we will keep its process ahead
15648                        // of the background processes.
15649                        if (adj > ProcessList.SERVICE_ADJ) {
15650                            adj = ProcessList.SERVICE_ADJ;
15651                            app.adjType = "started-services";
15652                            app.cached = false;
15653                        }
15654                    }
15655                    // If we have let the service slide into the background
15656                    // state, still have some text describing what it is doing
15657                    // even though the service no longer has an impact.
15658                    if (adj > ProcessList.SERVICE_ADJ) {
15659                        app.adjType = "cch-started-services";
15660                    }
15661                }
15662            }
15663            for (int conni = s.connections.size()-1;
15664                    conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
15665                            || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
15666                            || procState > ActivityManager.PROCESS_STATE_TOP);
15667                    conni--) {
15668                ArrayList<ConnectionRecord> clist = s.connections.valueAt(conni);
15669                for (int i = 0;
15670                        i < clist.size() && (adj > ProcessList.FOREGROUND_APP_ADJ
15671                                || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
15672                                || procState > ActivityManager.PROCESS_STATE_TOP);
15673                        i++) {
15674                    // XXX should compute this based on the max of
15675                    // all connected clients.
15676                    ConnectionRecord cr = clist.get(i);
15677                    if (cr.binding.client == app) {
15678                        // Binding to ourself is not interesting.
15679                        continue;
15680                    }
15681                    if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
15682                        ProcessRecord client = cr.binding.client;
15683                        int clientAdj = computeOomAdjLocked(client, cachedAdj,
15684                                TOP_APP, doingAll, now);
15685                        int clientProcState = client.curProcState;
15686                        if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
15687                            // If the other app is cached for any reason, for purposes here
15688                            // we are going to consider it empty.  The specific cached state
15689                            // doesn't propagate except under certain conditions.
15690                            clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
15691                        }
15692                        String adjType = null;
15693                        if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
15694                            // Not doing bind OOM management, so treat
15695                            // this guy more like a started service.
15696                            if (app.hasShownUi && app != mHomeProcess) {
15697                                // If this process has shown some UI, let it immediately
15698                                // go to the LRU list because it may be pretty heavy with
15699                                // UI stuff.  We'll tag it with a label just to help
15700                                // debug and understand what is going on.
15701                                if (adj > clientAdj) {
15702                                    adjType = "cch-bound-ui-services";
15703                                }
15704                                app.cached = false;
15705                                clientAdj = adj;
15706                                clientProcState = procState;
15707                            } else {
15708                                if (now >= (s.lastActivity
15709                                        + ActiveServices.MAX_SERVICE_INACTIVITY)) {
15710                                    // This service has not seen activity within
15711                                    // recent memory, so allow it to drop to the
15712                                    // LRU list if there is no other reason to keep
15713                                    // it around.  We'll also tag it with a label just
15714                                    // to help debug and undertand what is going on.
15715                                    if (adj > clientAdj) {
15716                                        adjType = "cch-bound-services";
15717                                    }
15718                                    clientAdj = adj;
15719                                }
15720                            }
15721                        }
15722                        if (adj > clientAdj) {
15723                            // If this process has recently shown UI, and
15724                            // the process that is binding to it is less
15725                            // important than being visible, then we don't
15726                            // care about the binding as much as we care
15727                            // about letting this process get into the LRU
15728                            // list to be killed and restarted if needed for
15729                            // memory.
15730                            if (app.hasShownUi && app != mHomeProcess
15731                                    && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
15732                                adjType = "cch-bound-ui-services";
15733                            } else {
15734                                if ((cr.flags&(Context.BIND_ABOVE_CLIENT
15735                                        |Context.BIND_IMPORTANT)) != 0) {
15736                                    adj = clientAdj;
15737                                } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
15738                                        && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
15739                                        && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
15740                                    adj = ProcessList.PERCEPTIBLE_APP_ADJ;
15741                                } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
15742                                    adj = clientAdj;
15743                                } else {
15744                                    if (adj > ProcessList.VISIBLE_APP_ADJ) {
15745                                        adj = ProcessList.VISIBLE_APP_ADJ;
15746                                    }
15747                                }
15748                                if (!client.cached) {
15749                                    app.cached = false;
15750                                }
15751                                adjType = "service";
15752                            }
15753                        }
15754                        if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
15755                            if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
15756                                schedGroup = Process.THREAD_GROUP_DEFAULT;
15757                            }
15758                            if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) {
15759                                if (clientProcState == ActivityManager.PROCESS_STATE_TOP) {
15760                                    // Special handling of clients who are in the top state.
15761                                    // We *may* want to consider this process to be in the
15762                                    // top state as well, but only if there is not another
15763                                    // reason for it to be running.  Being on the top is a
15764                                    // special state, meaning you are specifically running
15765                                    // for the current top app.  If the process is already
15766                                    // running in the background for some other reason, it
15767                                    // is more important to continue considering it to be
15768                                    // in the background state.
15769                                    mayBeTop = true;
15770                                    clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
15771                                } else {
15772                                    // Special handling for above-top states (persistent
15773                                    // processes).  These should not bring the current process
15774                                    // into the top state, since they are not on top.  Instead
15775                                    // give them the best state after that.
15776                                    clientProcState =
15777                                            ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15778                                }
15779                            }
15780                        } else {
15781                            if (clientProcState <
15782                                    ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) {
15783                                clientProcState =
15784                                        ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND;
15785                            }
15786                        }
15787                        if (procState > clientProcState) {
15788                            procState = clientProcState;
15789                        }
15790                        if (procState < ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
15791                                && (cr.flags&Context.BIND_SHOWING_UI) != 0) {
15792                            app.pendingUiClean = true;
15793                        }
15794                        if (adjType != null) {
15795                            app.adjType = adjType;
15796                            app.adjTypeCode = ActivityManager.RunningAppProcessInfo
15797                                    .REASON_SERVICE_IN_USE;
15798                            app.adjSource = cr.binding.client;
15799                            app.adjSourceProcState = clientProcState;
15800                            app.adjTarget = s.name;
15801                        }
15802                    }
15803                    if ((cr.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
15804                        app.treatLikeActivity = true;
15805                    }
15806                    final ActivityRecord a = cr.activity;
15807                    if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
15808                        if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
15809                                (a.visible || a.state == ActivityState.RESUMED
15810                                 || a.state == ActivityState.PAUSING)) {
15811                            adj = ProcessList.FOREGROUND_APP_ADJ;
15812                            if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
15813                                schedGroup = Process.THREAD_GROUP_DEFAULT;
15814                            }
15815                            app.cached = false;
15816                            app.adjType = "service";
15817                            app.adjTypeCode = ActivityManager.RunningAppProcessInfo
15818                                    .REASON_SERVICE_IN_USE;
15819                            app.adjSource = a;
15820                            app.adjSourceProcState = procState;
15821                            app.adjTarget = s.name;
15822                        }
15823                    }
15824                }
15825            }
15826        }
15827
15828        for (int provi = app.pubProviders.size()-1;
15829                provi >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
15830                        || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
15831                        || procState > ActivityManager.PROCESS_STATE_TOP);
15832                provi--) {
15833            ContentProviderRecord cpr = app.pubProviders.valueAt(provi);
15834            for (int i = cpr.connections.size()-1;
15835                    i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
15836                            || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE
15837                            || procState > ActivityManager.PROCESS_STATE_TOP);
15838                    i--) {
15839                ContentProviderConnection conn = cpr.connections.get(i);
15840                ProcessRecord client = conn.client;
15841                if (client == app) {
15842                    // Being our own client is not interesting.
15843                    continue;
15844                }
15845                int clientAdj = computeOomAdjLocked(client, cachedAdj, TOP_APP, doingAll, now);
15846                int clientProcState = client.curProcState;
15847                if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) {
15848                    // If the other app is cached for any reason, for purposes here
15849                    // we are going to consider it empty.
15850                    clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
15851                }
15852                if (adj > clientAdj) {
15853                    if (app.hasShownUi && app != mHomeProcess
15854                            && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
15855                        app.adjType = "cch-ui-provider";
15856                    } else {
15857                        adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
15858                                ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
15859                        app.adjType = "provider";
15860                    }
15861                    app.cached &= client.cached;
15862                    app.adjTypeCode = ActivityManager.RunningAppProcessInfo
15863                            .REASON_PROVIDER_IN_USE;
15864                    app.adjSource = client;
15865                    app.adjSourceProcState = clientProcState;
15866                    app.adjTarget = cpr.name;
15867                }
15868                if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) {
15869                    if (clientProcState == ActivityManager.PROCESS_STATE_TOP) {
15870                        // Special handling of clients who are in the top state.
15871                        // We *may* want to consider this process to be in the
15872                        // top state as well, but only if there is not another
15873                        // reason for it to be running.  Being on the top is a
15874                        // special state, meaning you are specifically running
15875                        // for the current top app.  If the process is already
15876                        // running in the background for some other reason, it
15877                        // is more important to continue considering it to be
15878                        // in the background state.
15879                        mayBeTop = true;
15880                        clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
15881                    } else {
15882                        // Special handling for above-top states (persistent
15883                        // processes).  These should not bring the current process
15884                        // into the top state, since they are not on top.  Instead
15885                        // give them the best state after that.
15886                        clientProcState =
15887                                ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15888                    }
15889                }
15890                if (procState > clientProcState) {
15891                    procState = clientProcState;
15892                }
15893                if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
15894                    schedGroup = Process.THREAD_GROUP_DEFAULT;
15895                }
15896            }
15897            // If the provider has external (non-framework) process
15898            // dependencies, ensure that its adjustment is at least
15899            // FOREGROUND_APP_ADJ.
15900            if (cpr.hasExternalProcessHandles()) {
15901                if (adj > ProcessList.FOREGROUND_APP_ADJ) {
15902                    adj = ProcessList.FOREGROUND_APP_ADJ;
15903                    schedGroup = Process.THREAD_GROUP_DEFAULT;
15904                    app.cached = false;
15905                    app.adjType = "provider";
15906                    app.adjTarget = cpr.name;
15907                }
15908                if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
15909                    procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15910                }
15911            }
15912        }
15913
15914        if (mayBeTop && procState > ActivityManager.PROCESS_STATE_TOP) {
15915            // A client of one of our services or providers is in the top state.  We
15916            // *may* want to be in the top state, but not if we are already running in
15917            // the background for some other reason.  For the decision here, we are going
15918            // to pick out a few specific states that we want to remain in when a client
15919            // is top (states that tend to be longer-term) and otherwise allow it to go
15920            // to the top state.
15921            switch (procState) {
15922                case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND:
15923                case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND:
15924                case ActivityManager.PROCESS_STATE_SERVICE:
15925                    // These all are longer-term states, so pull them up to the top
15926                    // of the background states, but not all the way to the top state.
15927                    procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
15928                    break;
15929                default:
15930                    // Otherwise, top is a better choice, so take it.
15931                    procState = ActivityManager.PROCESS_STATE_TOP;
15932                    break;
15933            }
15934        }
15935
15936        if (procState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
15937            if (app.hasClientActivities) {
15938                // This is a cached process, but with client activities.  Mark it so.
15939                procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT;
15940                app.adjType = "cch-client-act";
15941            } else if (app.treatLikeActivity) {
15942                // This is a cached process, but somebody wants us to treat it like it has
15943                // an activity, okay!
15944                procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY;
15945                app.adjType = "cch-as-act";
15946            }
15947        }
15948
15949        if (adj == ProcessList.SERVICE_ADJ) {
15950            if (doingAll) {
15951                app.serviceb = mNewNumAServiceProcs > (mNumServiceProcs/3);
15952                mNewNumServiceProcs++;
15953                //Slog.i(TAG, "ADJ " + app + " serviceb=" + app.serviceb);
15954                if (!app.serviceb) {
15955                    // This service isn't far enough down on the LRU list to
15956                    // normally be a B service, but if we are low on RAM and it
15957                    // is large we want to force it down since we would prefer to
15958                    // keep launcher over it.
15959                    if (mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL
15960                            && app.lastPss >= mProcessList.getCachedRestoreThresholdKb()) {
15961                        app.serviceHighRam = true;
15962                        app.serviceb = true;
15963                        //Slog.i(TAG, "ADJ " + app + " high ram!");
15964                    } else {
15965                        mNewNumAServiceProcs++;
15966                        //Slog.i(TAG, "ADJ " + app + " not high ram!");
15967                    }
15968                } else {
15969                    app.serviceHighRam = false;
15970                }
15971            }
15972            if (app.serviceb) {
15973                adj = ProcessList.SERVICE_B_ADJ;
15974            }
15975        }
15976
15977        app.curRawAdj = adj;
15978
15979        //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
15980        //      " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
15981        if (adj > app.maxAdj) {
15982            adj = app.maxAdj;
15983            if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
15984                schedGroup = Process.THREAD_GROUP_DEFAULT;
15985            }
15986        }
15987
15988        // Do final modification to adj.  Everything we do between here and applying
15989        // the final setAdj must be done in this function, because we will also use
15990        // it when computing the final cached adj later.  Note that we don't need to
15991        // worry about this for max adj above, since max adj will always be used to
15992        // keep it out of the cached vaues.
15993        app.curAdj = app.modifyRawOomAdj(adj);
15994        app.curSchedGroup = schedGroup;
15995        app.curProcState = procState;
15996        app.foregroundActivities = foregroundActivities;
15997
15998        return app.curRawAdj;
15999    }
16000
16001    /**
16002     * Schedule PSS collection of a process.
16003     */
16004    void requestPssLocked(ProcessRecord proc, int procState) {
16005        if (mPendingPssProcesses.contains(proc)) {
16006            return;
16007        }
16008        if (mPendingPssProcesses.size() == 0) {
16009            mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
16010        }
16011        if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of: " + proc);
16012        proc.pssProcState = procState;
16013        mPendingPssProcesses.add(proc);
16014    }
16015
16016    /**
16017     * Schedule PSS collection of all processes.
16018     */
16019    void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) {
16020        if (!always) {
16021            if (now < (mLastFullPssTime +
16022                    (memLowered ? FULL_PSS_LOWERED_INTERVAL : FULL_PSS_MIN_INTERVAL))) {
16023                return;
16024            }
16025        }
16026        if (DEBUG_PSS) Slog.d(TAG, "Requesting PSS of all procs!  memLowered=" + memLowered);
16027        mLastFullPssTime = now;
16028        mFullPssPending = true;
16029        mPendingPssProcesses.ensureCapacity(mLruProcesses.size());
16030        mPendingPssProcesses.clear();
16031        for (int i=mLruProcesses.size()-1; i>=0; i--) {
16032            ProcessRecord app = mLruProcesses.get(i);
16033            if (memLowered || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) {
16034                app.pssProcState = app.setProcState;
16035                app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true,
16036                        isSleeping(), now);
16037                mPendingPssProcesses.add(app);
16038            }
16039        }
16040        mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG);
16041    }
16042
16043    /**
16044     * Ask a given process to GC right now.
16045     */
16046    final void performAppGcLocked(ProcessRecord app) {
16047        try {
16048            app.lastRequestedGc = SystemClock.uptimeMillis();
16049            if (app.thread != null) {
16050                if (app.reportLowMemory) {
16051                    app.reportLowMemory = false;
16052                    app.thread.scheduleLowMemory();
16053                } else {
16054                    app.thread.processInBackground();
16055                }
16056            }
16057        } catch (Exception e) {
16058            // whatever.
16059        }
16060    }
16061
16062    /**
16063     * Returns true if things are idle enough to perform GCs.
16064     */
16065    private final boolean canGcNowLocked() {
16066        boolean processingBroadcasts = false;
16067        for (BroadcastQueue q : mBroadcastQueues) {
16068            if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
16069                processingBroadcasts = true;
16070            }
16071        }
16072        return !processingBroadcasts
16073                && (isSleeping() || mStackSupervisor.allResumedActivitiesIdle());
16074    }
16075
16076    /**
16077     * Perform GCs on all processes that are waiting for it, but only
16078     * if things are idle.
16079     */
16080    final void performAppGcsLocked() {
16081        final int N = mProcessesToGc.size();
16082        if (N <= 0) {
16083            return;
16084        }
16085        if (canGcNowLocked()) {
16086            while (mProcessesToGc.size() > 0) {
16087                ProcessRecord proc = mProcessesToGc.remove(0);
16088                if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
16089                    if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
16090                            <= SystemClock.uptimeMillis()) {
16091                        // To avoid spamming the system, we will GC processes one
16092                        // at a time, waiting a few seconds between each.
16093                        performAppGcLocked(proc);
16094                        scheduleAppGcsLocked();
16095                        return;
16096                    } else {
16097                        // It hasn't been long enough since we last GCed this
16098                        // process...  put it in the list to wait for its time.
16099                        addProcessToGcListLocked(proc);
16100                        break;
16101                    }
16102                }
16103            }
16104
16105            scheduleAppGcsLocked();
16106        }
16107    }
16108
16109    /**
16110     * If all looks good, perform GCs on all processes waiting for them.
16111     */
16112    final void performAppGcsIfAppropriateLocked() {
16113        if (canGcNowLocked()) {
16114            performAppGcsLocked();
16115            return;
16116        }
16117        // Still not idle, wait some more.
16118        scheduleAppGcsLocked();
16119    }
16120
16121    /**
16122     * Schedule the execution of all pending app GCs.
16123     */
16124    final void scheduleAppGcsLocked() {
16125        mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
16126
16127        if (mProcessesToGc.size() > 0) {
16128            // Schedule a GC for the time to the next process.
16129            ProcessRecord proc = mProcessesToGc.get(0);
16130            Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
16131
16132            long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
16133            long now = SystemClock.uptimeMillis();
16134            if (when < (now+GC_TIMEOUT)) {
16135                when = now + GC_TIMEOUT;
16136            }
16137            mHandler.sendMessageAtTime(msg, when);
16138        }
16139    }
16140
16141    /**
16142     * Add a process to the array of processes waiting to be GCed.  Keeps the
16143     * list in sorted order by the last GC time.  The process can't already be
16144     * on the list.
16145     */
16146    final void addProcessToGcListLocked(ProcessRecord proc) {
16147        boolean added = false;
16148        for (int i=mProcessesToGc.size()-1; i>=0; i--) {
16149            if (mProcessesToGc.get(i).lastRequestedGc <
16150                    proc.lastRequestedGc) {
16151                added = true;
16152                mProcessesToGc.add(i+1, proc);
16153                break;
16154            }
16155        }
16156        if (!added) {
16157            mProcessesToGc.add(0, proc);
16158        }
16159    }
16160
16161    /**
16162     * Set up to ask a process to GC itself.  This will either do it
16163     * immediately, or put it on the list of processes to gc the next
16164     * time things are idle.
16165     */
16166    final void scheduleAppGcLocked(ProcessRecord app) {
16167        long now = SystemClock.uptimeMillis();
16168        if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
16169            return;
16170        }
16171        if (!mProcessesToGc.contains(app)) {
16172            addProcessToGcListLocked(app);
16173            scheduleAppGcsLocked();
16174        }
16175    }
16176
16177    final void checkExcessivePowerUsageLocked(boolean doKills) {
16178        updateCpuStatsNow();
16179
16180        BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
16181        boolean doWakeKills = doKills;
16182        boolean doCpuKills = doKills;
16183        if (mLastPowerCheckRealtime == 0) {
16184            doWakeKills = false;
16185        }
16186        if (mLastPowerCheckUptime == 0) {
16187            doCpuKills = false;
16188        }
16189        if (stats.isScreenOn()) {
16190            doWakeKills = false;
16191        }
16192        final long curRealtime = SystemClock.elapsedRealtime();
16193        final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
16194        final long curUptime = SystemClock.uptimeMillis();
16195        final long uptimeSince = curUptime - mLastPowerCheckUptime;
16196        mLastPowerCheckRealtime = curRealtime;
16197        mLastPowerCheckUptime = curUptime;
16198        if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
16199            doWakeKills = false;
16200        }
16201        if (uptimeSince < CPU_MIN_CHECK_DURATION) {
16202            doCpuKills = false;
16203        }
16204        int i = mLruProcesses.size();
16205        while (i > 0) {
16206            i--;
16207            ProcessRecord app = mLruProcesses.get(i);
16208            if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
16209                long wtime;
16210                synchronized (stats) {
16211                    wtime = stats.getProcessWakeTime(app.info.uid,
16212                            app.pid, curRealtime);
16213                }
16214                long wtimeUsed = wtime - app.lastWakeTime;
16215                long cputimeUsed = app.curCpuTime - app.lastCpuTime;
16216                if (DEBUG_POWER) {
16217                    StringBuilder sb = new StringBuilder(128);
16218                    sb.append("Wake for ");
16219                    app.toShortString(sb);
16220                    sb.append(": over ");
16221                    TimeUtils.formatDuration(realtimeSince, sb);
16222                    sb.append(" used ");
16223                    TimeUtils.formatDuration(wtimeUsed, sb);
16224                    sb.append(" (");
16225                    sb.append((wtimeUsed*100)/realtimeSince);
16226                    sb.append("%)");
16227                    Slog.i(TAG, sb.toString());
16228                    sb.setLength(0);
16229                    sb.append("CPU for ");
16230                    app.toShortString(sb);
16231                    sb.append(": over ");
16232                    TimeUtils.formatDuration(uptimeSince, sb);
16233                    sb.append(" used ");
16234                    TimeUtils.formatDuration(cputimeUsed, sb);
16235                    sb.append(" (");
16236                    sb.append((cputimeUsed*100)/uptimeSince);
16237                    sb.append("%)");
16238                    Slog.i(TAG, sb.toString());
16239                }
16240                // If a process has held a wake lock for more
16241                // than 50% of the time during this period,
16242                // that sounds bad.  Kill!
16243                if (doWakeKills && realtimeSince > 0
16244                        && ((wtimeUsed*100)/realtimeSince) >= 50) {
16245                    synchronized (stats) {
16246                        stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
16247                                realtimeSince, wtimeUsed);
16248                    }
16249                    killUnneededProcessLocked(app, "excessive wake held " + wtimeUsed
16250                            + " during " + realtimeSince);
16251                    app.baseProcessTracker.reportExcessiveWake(app.pkgList);
16252                } else if (doCpuKills && uptimeSince > 0
16253                        && ((cputimeUsed*100)/uptimeSince) >= 25) {
16254                    synchronized (stats) {
16255                        stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
16256                                uptimeSince, cputimeUsed);
16257                    }
16258                    killUnneededProcessLocked(app, "excessive cpu " + cputimeUsed
16259                            + " during " + uptimeSince);
16260                    app.baseProcessTracker.reportExcessiveCpu(app.pkgList);
16261                } else {
16262                    app.lastWakeTime = wtime;
16263                    app.lastCpuTime = app.curCpuTime;
16264                }
16265            }
16266        }
16267    }
16268
16269    private final boolean applyOomAdjLocked(ProcessRecord app,
16270            ProcessRecord TOP_APP, boolean doingAll, long now) {
16271        boolean success = true;
16272
16273        if (app.curRawAdj != app.setRawAdj) {
16274            app.setRawAdj = app.curRawAdj;
16275        }
16276
16277        int changes = 0;
16278
16279        if (app.curAdj != app.setAdj) {
16280            ProcessList.setOomAdj(app.pid, app.info.uid, app.curAdj);
16281            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
16282                TAG, "Set " + app.pid + " " + app.processName +
16283                " adj " + app.curAdj + ": " + app.adjType);
16284            app.setAdj = app.curAdj;
16285        }
16286
16287        if (app.setSchedGroup != app.curSchedGroup) {
16288            app.setSchedGroup = app.curSchedGroup;
16289            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16290                    "Setting process group of " + app.processName
16291                    + " to " + app.curSchedGroup);
16292            if (app.waitingToKill != null &&
16293                    app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
16294                killUnneededProcessLocked(app, app.waitingToKill);
16295                success = false;
16296            } else {
16297                if (true) {
16298                    long oldId = Binder.clearCallingIdentity();
16299                    try {
16300                        Process.setProcessGroup(app.pid, app.curSchedGroup);
16301                    } catch (Exception e) {
16302                        Slog.w(TAG, "Failed setting process group of " + app.pid
16303                                + " to " + app.curSchedGroup);
16304                        e.printStackTrace();
16305                    } finally {
16306                        Binder.restoreCallingIdentity(oldId);
16307                    }
16308                } else {
16309                    if (app.thread != null) {
16310                        try {
16311                            app.thread.setSchedulingGroup(app.curSchedGroup);
16312                        } catch (RemoteException e) {
16313                        }
16314                    }
16315                }
16316                Process.setSwappiness(app.pid,
16317                        app.curSchedGroup <= Process.THREAD_GROUP_BG_NONINTERACTIVE);
16318            }
16319        }
16320        if (app.repForegroundActivities != app.foregroundActivities) {
16321            app.repForegroundActivities = app.foregroundActivities;
16322            changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
16323        }
16324        if (app.repProcState != app.curProcState) {
16325            app.repProcState = app.curProcState;
16326            changes |= ProcessChangeItem.CHANGE_PROCESS_STATE;
16327            if (app.thread != null) {
16328                try {
16329                    if (false) {
16330                        //RuntimeException h = new RuntimeException("here");
16331                        Slog.i(TAG, "Sending new process state " + app.repProcState
16332                                + " to " + app /*, h*/);
16333                    }
16334                    app.thread.setProcessState(app.repProcState);
16335                } catch (RemoteException e) {
16336                }
16337            }
16338        }
16339        if (app.setProcState < 0 || ProcessList.procStatesDifferForMem(app.curProcState,
16340                app.setProcState)) {
16341            app.lastStateTime = now;
16342            app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true,
16343                    isSleeping(), now);
16344            if (DEBUG_PSS) Slog.d(TAG, "Process state change from "
16345                    + ProcessList.makeProcStateString(app.setProcState) + " to "
16346                    + ProcessList.makeProcStateString(app.curProcState) + " next pss in "
16347                    + (app.nextPssTime-now) + ": " + app);
16348        } else {
16349            if (now > app.nextPssTime || (now > (app.lastPssTime+ProcessList.PSS_MAX_INTERVAL)
16350                    && now > (app.lastStateTime+ProcessList.PSS_MIN_TIME_FROM_STATE_CHANGE))) {
16351                requestPssLocked(app, app.setProcState);
16352                app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, false,
16353                        isSleeping(), now);
16354            } else if (false && DEBUG_PSS) {
16355                Slog.d(TAG, "Not requesting PSS of " + app + ": next=" + (app.nextPssTime-now));
16356            }
16357        }
16358        if (app.setProcState != app.curProcState) {
16359            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16360                    "Proc state change of " + app.processName
16361                    + " to " + app.curProcState);
16362            boolean setImportant = app.setProcState < ActivityManager.PROCESS_STATE_SERVICE;
16363            boolean curImportant = app.curProcState < ActivityManager.PROCESS_STATE_SERVICE;
16364            if (setImportant && !curImportant) {
16365                // This app is no longer something we consider important enough to allow to
16366                // use arbitrary amounts of battery power.  Note
16367                // its current wake lock time to later know to kill it if
16368                // it is not behaving well.
16369                BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
16370                synchronized (stats) {
16371                    app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
16372                            app.pid, SystemClock.elapsedRealtime());
16373                }
16374                app.lastCpuTime = app.curCpuTime;
16375
16376            }
16377            app.setProcState = app.curProcState;
16378            if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
16379                app.notCachedSinceIdle = false;
16380            }
16381            if (!doingAll) {
16382                setProcessTrackerStateLocked(app, mProcessStats.getMemFactorLocked(), now);
16383            } else {
16384                app.procStateChanged = true;
16385            }
16386        }
16387
16388        if (changes != 0) {
16389            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
16390            int i = mPendingProcessChanges.size()-1;
16391            ProcessChangeItem item = null;
16392            while (i >= 0) {
16393                item = mPendingProcessChanges.get(i);
16394                if (item.pid == app.pid) {
16395                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
16396                    break;
16397                }
16398                i--;
16399            }
16400            if (i < 0) {
16401                // No existing item in pending changes; need a new one.
16402                final int NA = mAvailProcessChanges.size();
16403                if (NA > 0) {
16404                    item = mAvailProcessChanges.remove(NA-1);
16405                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
16406                } else {
16407                    item = new ProcessChangeItem();
16408                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
16409                }
16410                item.changes = 0;
16411                item.pid = app.pid;
16412                item.uid = app.info.uid;
16413                if (mPendingProcessChanges.size() == 0) {
16414                    if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
16415                            "*** Enqueueing dispatch processes changed!");
16416                    mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
16417                }
16418                mPendingProcessChanges.add(item);
16419            }
16420            item.changes |= changes;
16421            item.processState = app.repProcState;
16422            item.foregroundActivities = app.repForegroundActivities;
16423            if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
16424                    + Integer.toHexString(System.identityHashCode(item))
16425                    + " " + app.toShortString() + ": changes=" + item.changes
16426                    + " procState=" + item.processState
16427                    + " foreground=" + item.foregroundActivities
16428                    + " type=" + app.adjType + " source=" + app.adjSource
16429                    + " target=" + app.adjTarget);
16430        }
16431
16432        return success;
16433    }
16434
16435    private final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) {
16436        if (proc.thread != null) {
16437            if (proc.baseProcessTracker != null) {
16438                proc.baseProcessTracker.setState(proc.repProcState, memFactor, now, proc.pkgList);
16439            }
16440            if (proc.repProcState >= 0) {
16441                mBatteryStatsService.noteProcessState(proc.processName, proc.info.uid,
16442                        proc.repProcState);
16443            }
16444        }
16445    }
16446
16447    private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj,
16448            ProcessRecord TOP_APP, boolean doingAll, long now) {
16449        if (app.thread == null) {
16450            return false;
16451        }
16452
16453        computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now);
16454
16455        return applyOomAdjLocked(app, TOP_APP, doingAll, now);
16456    }
16457
16458    final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground,
16459            boolean oomAdj) {
16460        if (isForeground != proc.foregroundServices) {
16461            proc.foregroundServices = isForeground;
16462            ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName,
16463                    proc.info.uid);
16464            if (isForeground) {
16465                if (curProcs == null) {
16466                    curProcs = new ArrayList<ProcessRecord>();
16467                    mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs);
16468                }
16469                if (!curProcs.contains(proc)) {
16470                    curProcs.add(proc);
16471                    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START,
16472                            proc.info.packageName, proc.info.uid);
16473                }
16474            } else {
16475                if (curProcs != null) {
16476                    if (curProcs.remove(proc)) {
16477                        mBatteryStatsService.noteEvent(
16478                                BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH,
16479                                proc.info.packageName, proc.info.uid);
16480                        if (curProcs.size() <= 0) {
16481                            mForegroundPackages.remove(proc.info.packageName, proc.info.uid);
16482                        }
16483                    }
16484                }
16485            }
16486            if (oomAdj) {
16487                updateOomAdjLocked();
16488            }
16489        }
16490    }
16491
16492    private final ActivityRecord resumedAppLocked() {
16493        ActivityRecord act = mStackSupervisor.resumedAppLocked();
16494        String pkg;
16495        int uid;
16496        if (act != null) {
16497            pkg = act.packageName;
16498            uid = act.info.applicationInfo.uid;
16499        } else {
16500            pkg = null;
16501            uid = -1;
16502        }
16503        // Has the UID or resumed package name changed?
16504        if (uid != mCurResumedUid || (pkg != mCurResumedPackage
16505                && (pkg == null || !pkg.equals(mCurResumedPackage)))) {
16506            if (mCurResumedPackage != null) {
16507                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH,
16508                        mCurResumedPackage, mCurResumedUid);
16509            }
16510            mCurResumedPackage = pkg;
16511            mCurResumedUid = uid;
16512            if (mCurResumedPackage != null) {
16513                mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START,
16514                        mCurResumedPackage, mCurResumedUid);
16515            }
16516        }
16517        return act;
16518    }
16519
16520    final boolean updateOomAdjLocked(ProcessRecord app) {
16521        final ActivityRecord TOP_ACT = resumedAppLocked();
16522        final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
16523        final boolean wasCached = app.cached;
16524
16525        mAdjSeq++;
16526
16527        // This is the desired cached adjusment we want to tell it to use.
16528        // If our app is currently cached, we know it, and that is it.  Otherwise,
16529        // we don't know it yet, and it needs to now be cached we will then
16530        // need to do a complete oom adj.
16531        final int cachedAdj = app.curRawAdj >= ProcessList.CACHED_APP_MIN_ADJ
16532                ? app.curRawAdj : ProcessList.UNKNOWN_ADJ;
16533        boolean success = updateOomAdjLocked(app, cachedAdj, TOP_APP, false,
16534                SystemClock.uptimeMillis());
16535        if (wasCached != app.cached || app.curRawAdj == ProcessList.UNKNOWN_ADJ) {
16536            // Changed to/from cached state, so apps after it in the LRU
16537            // list may also be changed.
16538            updateOomAdjLocked();
16539        }
16540        return success;
16541    }
16542
16543    final void updateOomAdjLocked() {
16544        final ActivityRecord TOP_ACT = resumedAppLocked();
16545        final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
16546        final long now = SystemClock.uptimeMillis();
16547        final long oldTime = now - ProcessList.MAX_EMPTY_TIME;
16548        final int N = mLruProcesses.size();
16549
16550        if (false) {
16551            RuntimeException e = new RuntimeException();
16552            e.fillInStackTrace();
16553            Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
16554        }
16555
16556        mAdjSeq++;
16557        mNewNumServiceProcs = 0;
16558        mNewNumAServiceProcs = 0;
16559
16560        final int emptyProcessLimit;
16561        final int cachedProcessLimit;
16562        if (mProcessLimit <= 0) {
16563            emptyProcessLimit = cachedProcessLimit = 0;
16564        } else if (mProcessLimit == 1) {
16565            emptyProcessLimit = 1;
16566            cachedProcessLimit = 0;
16567        } else {
16568            emptyProcessLimit = ProcessList.computeEmptyProcessLimit(mProcessLimit);
16569            cachedProcessLimit = mProcessLimit - emptyProcessLimit;
16570        }
16571
16572        // Let's determine how many processes we have running vs.
16573        // how many slots we have for background processes; we may want
16574        // to put multiple processes in a slot of there are enough of
16575        // them.
16576        int numSlots = (ProcessList.CACHED_APP_MAX_ADJ
16577                - ProcessList.CACHED_APP_MIN_ADJ + 1) / 2;
16578        int numEmptyProcs = N - mNumNonCachedProcs - mNumCachedHiddenProcs;
16579        if (numEmptyProcs > cachedProcessLimit) {
16580            // If there are more empty processes than our limit on cached
16581            // processes, then use the cached process limit for the factor.
16582            // This ensures that the really old empty processes get pushed
16583            // down to the bottom, so if we are running low on memory we will
16584            // have a better chance at keeping around more cached processes
16585            // instead of a gazillion empty processes.
16586            numEmptyProcs = cachedProcessLimit;
16587        }
16588        int emptyFactor = numEmptyProcs/numSlots;
16589        if (emptyFactor < 1) emptyFactor = 1;
16590        int cachedFactor = (mNumCachedHiddenProcs > 0 ? mNumCachedHiddenProcs : 1)/numSlots;
16591        if (cachedFactor < 1) cachedFactor = 1;
16592        int stepCached = 0;
16593        int stepEmpty = 0;
16594        int numCached = 0;
16595        int numEmpty = 0;
16596        int numTrimming = 0;
16597
16598        mNumNonCachedProcs = 0;
16599        mNumCachedHiddenProcs = 0;
16600
16601        // First update the OOM adjustment for each of the
16602        // application processes based on their current state.
16603        int curCachedAdj = ProcessList.CACHED_APP_MIN_ADJ;
16604        int nextCachedAdj = curCachedAdj+1;
16605        int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ;
16606        int nextEmptyAdj = curEmptyAdj+2;
16607        for (int i=N-1; i>=0; i--) {
16608            ProcessRecord app = mLruProcesses.get(i);
16609            if (!app.killedByAm && app.thread != null) {
16610                app.procStateChanged = false;
16611                computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now);
16612
16613                // If we haven't yet assigned the final cached adj
16614                // to the process, do that now.
16615                if (app.curAdj >= ProcessList.UNKNOWN_ADJ) {
16616                    switch (app.curProcState) {
16617                        case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY:
16618                        case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
16619                            // This process is a cached process holding activities...
16620                            // assign it the next cached value for that type, and then
16621                            // step that cached level.
16622                            app.curRawAdj = curCachedAdj;
16623                            app.curAdj = app.modifyRawOomAdj(curCachedAdj);
16624                            if (DEBUG_LRU && false) Slog.d(TAG, "Assigning activity LRU #" + i
16625                                    + " adj: " + app.curAdj + " (curCachedAdj=" + curCachedAdj
16626                                    + ")");
16627                            if (curCachedAdj != nextCachedAdj) {
16628                                stepCached++;
16629                                if (stepCached >= cachedFactor) {
16630                                    stepCached = 0;
16631                                    curCachedAdj = nextCachedAdj;
16632                                    nextCachedAdj += 2;
16633                                    if (nextCachedAdj > ProcessList.CACHED_APP_MAX_ADJ) {
16634                                        nextCachedAdj = ProcessList.CACHED_APP_MAX_ADJ;
16635                                    }
16636                                }
16637                            }
16638                            break;
16639                        default:
16640                            // For everything else, assign next empty cached process
16641                            // level and bump that up.  Note that this means that
16642                            // long-running services that have dropped down to the
16643                            // cached level will be treated as empty (since their process
16644                            // state is still as a service), which is what we want.
16645                            app.curRawAdj = curEmptyAdj;
16646                            app.curAdj = app.modifyRawOomAdj(curEmptyAdj);
16647                            if (DEBUG_LRU && false) Slog.d(TAG, "Assigning empty LRU #" + i
16648                                    + " adj: " + app.curAdj + " (curEmptyAdj=" + curEmptyAdj
16649                                    + ")");
16650                            if (curEmptyAdj != nextEmptyAdj) {
16651                                stepEmpty++;
16652                                if (stepEmpty >= emptyFactor) {
16653                                    stepEmpty = 0;
16654                                    curEmptyAdj = nextEmptyAdj;
16655                                    nextEmptyAdj += 2;
16656                                    if (nextEmptyAdj > ProcessList.CACHED_APP_MAX_ADJ) {
16657                                        nextEmptyAdj = ProcessList.CACHED_APP_MAX_ADJ;
16658                                    }
16659                                }
16660                            }
16661                            break;
16662                    }
16663                }
16664
16665                applyOomAdjLocked(app, TOP_APP, true, now);
16666
16667                // Count the number of process types.
16668                switch (app.curProcState) {
16669                    case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY:
16670                    case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
16671                        mNumCachedHiddenProcs++;
16672                        numCached++;
16673                        if (numCached > cachedProcessLimit) {
16674                            killUnneededProcessLocked(app, "cached #" + numCached);
16675                        }
16676                        break;
16677                    case ActivityManager.PROCESS_STATE_CACHED_EMPTY:
16678                        if (numEmpty > ProcessList.TRIM_EMPTY_APPS
16679                                && app.lastActivityTime < oldTime) {
16680                            killUnneededProcessLocked(app, "empty for "
16681                                    + ((oldTime + ProcessList.MAX_EMPTY_TIME - app.lastActivityTime)
16682                                    / 1000) + "s");
16683                        } else {
16684                            numEmpty++;
16685                            if (numEmpty > emptyProcessLimit) {
16686                                killUnneededProcessLocked(app, "empty #" + numEmpty);
16687                            }
16688                        }
16689                        break;
16690                    default:
16691                        mNumNonCachedProcs++;
16692                        break;
16693                }
16694
16695                if (app.isolated && app.services.size() <= 0) {
16696                    // If this is an isolated process, and there are no
16697                    // services running in it, then the process is no longer
16698                    // needed.  We agressively kill these because we can by
16699                    // definition not re-use the same process again, and it is
16700                    // good to avoid having whatever code was running in them
16701                    // left sitting around after no longer needed.
16702                    killUnneededProcessLocked(app, "isolated not needed");
16703                }
16704
16705                if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME
16706                        && !app.killedByAm) {
16707                    numTrimming++;
16708                }
16709            }
16710        }
16711
16712        mNumServiceProcs = mNewNumServiceProcs;
16713
16714        // Now determine the memory trimming level of background processes.
16715        // Unfortunately we need to start at the back of the list to do this
16716        // properly.  We only do this if the number of background apps we
16717        // are managing to keep around is less than half the maximum we desire;
16718        // if we are keeping a good number around, we'll let them use whatever
16719        // memory they want.
16720        final int numCachedAndEmpty = numCached + numEmpty;
16721        int memFactor;
16722        if (numCached <= ProcessList.TRIM_CACHED_APPS
16723                && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
16724            if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
16725                memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL;
16726            } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
16727                memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW;
16728            } else {
16729                memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE;
16730            }
16731        } else {
16732            memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL;
16733        }
16734        // We always allow the memory level to go up (better).  We only allow it to go
16735        // down if we are in a state where that is allowed, *and* the total number of processes
16736        // has gone down since last time.
16737        if (DEBUG_OOM_ADJ) Slog.d(TAG, "oom: memFactor=" + memFactor + " last=" + mLastMemoryLevel
16738                + " allowLow=" + mAllowLowerMemLevel + " numProcs=" + mLruProcesses.size()
16739                + " last=" + mLastNumProcesses);
16740        if (memFactor > mLastMemoryLevel) {
16741            if (!mAllowLowerMemLevel || mLruProcesses.size() >= mLastNumProcesses) {
16742                memFactor = mLastMemoryLevel;
16743                if (DEBUG_OOM_ADJ) Slog.d(TAG, "Keeping last mem factor!");
16744            }
16745        }
16746        mLastMemoryLevel = memFactor;
16747        mLastNumProcesses = mLruProcesses.size();
16748        boolean allChanged = mProcessStats.setMemFactorLocked(memFactor, !isSleeping(), now);
16749        final int trackerMemFactor = mProcessStats.getMemFactorLocked();
16750        if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) {
16751            if (mLowRamStartTime == 0) {
16752                mLowRamStartTime = now;
16753            }
16754            int step = 0;
16755            int fgTrimLevel;
16756            switch (memFactor) {
16757                case ProcessStats.ADJ_MEM_FACTOR_CRITICAL:
16758                    fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
16759                    break;
16760                case ProcessStats.ADJ_MEM_FACTOR_LOW:
16761                    fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
16762                    break;
16763                default:
16764                    fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
16765                    break;
16766            }
16767            int factor = numTrimming/3;
16768            int minFactor = 2;
16769            if (mHomeProcess != null) minFactor++;
16770            if (mPreviousProcess != null) minFactor++;
16771            if (factor < minFactor) factor = minFactor;
16772            int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
16773            for (int i=N-1; i>=0; i--) {
16774                ProcessRecord app = mLruProcesses.get(i);
16775                if (allChanged || app.procStateChanged) {
16776                    setProcessTrackerStateLocked(app, trackerMemFactor, now);
16777                    app.procStateChanged = false;
16778                }
16779                if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME
16780                        && !app.killedByAm) {
16781                    if (app.trimMemoryLevel < curLevel && app.thread != null) {
16782                        try {
16783                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16784                                    "Trimming memory of " + app.processName
16785                                    + " to " + curLevel);
16786                            app.thread.scheduleTrimMemory(curLevel);
16787                        } catch (RemoteException e) {
16788                        }
16789                        if (false) {
16790                            // For now we won't do this; our memory trimming seems
16791                            // to be good enough at this point that destroying
16792                            // activities causes more harm than good.
16793                            if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
16794                                    && app != mHomeProcess && app != mPreviousProcess) {
16795                                // Need to do this on its own message because the stack may not
16796                                // be in a consistent state at this point.
16797                                // For these apps we will also finish their activities
16798                                // to help them free memory.
16799                                mStackSupervisor.scheduleDestroyAllActivities(app, "trim");
16800                            }
16801                        }
16802                    }
16803                    app.trimMemoryLevel = curLevel;
16804                    step++;
16805                    if (step >= factor) {
16806                        step = 0;
16807                        switch (curLevel) {
16808                            case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
16809                                curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
16810                                break;
16811                            case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
16812                                curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
16813                                break;
16814                        }
16815                    }
16816                } else if (app.curProcState == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) {
16817                    if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
16818                            && app.thread != null) {
16819                        try {
16820                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16821                                    "Trimming memory of heavy-weight " + app.processName
16822                                    + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
16823                            app.thread.scheduleTrimMemory(
16824                                    ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
16825                        } catch (RemoteException e) {
16826                        }
16827                    }
16828                    app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
16829                } else {
16830                    if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
16831                            || app.systemNoUi) && app.pendingUiClean) {
16832                        // If this application is now in the background and it
16833                        // had done UI, then give it the special trim level to
16834                        // have it free UI resources.
16835                        final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
16836                        if (app.trimMemoryLevel < level && app.thread != null) {
16837                            try {
16838                                if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16839                                        "Trimming memory of bg-ui " + app.processName
16840                                        + " to " + level);
16841                                app.thread.scheduleTrimMemory(level);
16842                            } catch (RemoteException e) {
16843                            }
16844                        }
16845                        app.pendingUiClean = false;
16846                    }
16847                    if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
16848                        try {
16849                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16850                                    "Trimming memory of fg " + app.processName
16851                                    + " to " + fgTrimLevel);
16852                            app.thread.scheduleTrimMemory(fgTrimLevel);
16853                        } catch (RemoteException e) {
16854                        }
16855                    }
16856                    app.trimMemoryLevel = fgTrimLevel;
16857                }
16858            }
16859        } else {
16860            if (mLowRamStartTime != 0) {
16861                mLowRamTimeSinceLastIdle += now - mLowRamStartTime;
16862                mLowRamStartTime = 0;
16863            }
16864            for (int i=N-1; i>=0; i--) {
16865                ProcessRecord app = mLruProcesses.get(i);
16866                if (allChanged || app.procStateChanged) {
16867                    setProcessTrackerStateLocked(app, trackerMemFactor, now);
16868                    app.procStateChanged = false;
16869                }
16870                if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
16871                        || app.systemNoUi) && app.pendingUiClean) {
16872                    if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
16873                            && app.thread != null) {
16874                        try {
16875                            if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
16876                                    "Trimming memory of ui hidden " + app.processName
16877                                    + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
16878                            app.thread.scheduleTrimMemory(
16879                                    ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
16880                        } catch (RemoteException e) {
16881                        }
16882                    }
16883                    app.pendingUiClean = false;
16884                }
16885                app.trimMemoryLevel = 0;
16886            }
16887        }
16888
16889        if (mAlwaysFinishActivities) {
16890            // Need to do this on its own message because the stack may not
16891            // be in a consistent state at this point.
16892            mStackSupervisor.scheduleDestroyAllActivities(null, "always-finish");
16893        }
16894
16895        if (allChanged) {
16896            requestPssAllProcsLocked(now, false, mProcessStats.isMemFactorLowered());
16897        }
16898
16899        if (mProcessStats.shouldWriteNowLocked(now)) {
16900            mHandler.post(new Runnable() {
16901                @Override public void run() {
16902                    synchronized (ActivityManagerService.this) {
16903                        mProcessStats.writeStateAsyncLocked();
16904                    }
16905                }
16906            });
16907        }
16908
16909        if (DEBUG_OOM_ADJ) {
16910            Slog.d(TAG, "Did OOM ADJ in " + (SystemClock.uptimeMillis()-now) + "ms");
16911        }
16912    }
16913
16914    final void trimApplications() {
16915        synchronized (this) {
16916            int i;
16917
16918            // First remove any unused application processes whose package
16919            // has been removed.
16920            for (i=mRemovedProcesses.size()-1; i>=0; i--) {
16921                final ProcessRecord app = mRemovedProcesses.get(i);
16922                if (app.activities.size() == 0
16923                        && app.curReceiver == null && app.services.size() == 0) {
16924                    Slog.i(
16925                        TAG, "Exiting empty application process "
16926                        + app.processName + " ("
16927                        + (app.thread != null ? app.thread.asBinder() : null)
16928                        + ")\n");
16929                    if (app.pid > 0 && app.pid != MY_PID) {
16930                        EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
16931                                app.processName, app.setAdj, "empty");
16932                        app.killedByAm = true;
16933                        Process.killProcessQuiet(app.pid);
16934                        Process.killProcessGroup(app.info.uid, app.pid);
16935                    } else {
16936                        try {
16937                            app.thread.scheduleExit();
16938                        } catch (Exception e) {
16939                            // Ignore exceptions.
16940                        }
16941                    }
16942                    cleanUpApplicationRecordLocked(app, false, true, -1);
16943                    mRemovedProcesses.remove(i);
16944
16945                    if (app.persistent) {
16946                        addAppLocked(app.info, false, null /* ABI override */);
16947                    }
16948                }
16949            }
16950
16951            // Now update the oom adj for all processes.
16952            updateOomAdjLocked();
16953        }
16954    }
16955
16956    /** This method sends the specified signal to each of the persistent apps */
16957    public void signalPersistentProcesses(int sig) throws RemoteException {
16958        if (sig != Process.SIGNAL_USR1) {
16959            throw new SecurityException("Only SIGNAL_USR1 is allowed");
16960        }
16961
16962        synchronized (this) {
16963            if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
16964                    != PackageManager.PERMISSION_GRANTED) {
16965                throw new SecurityException("Requires permission "
16966                        + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
16967            }
16968
16969            for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
16970                ProcessRecord r = mLruProcesses.get(i);
16971                if (r.thread != null && r.persistent) {
16972                    Process.sendSignal(r.pid, sig);
16973                }
16974            }
16975        }
16976    }
16977
16978    private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
16979        if (proc == null || proc == mProfileProc) {
16980            proc = mProfileProc;
16981            path = mProfileFile;
16982            profileType = mProfileType;
16983            clearProfilerLocked();
16984        }
16985        if (proc == null) {
16986            return;
16987        }
16988        try {
16989            proc.thread.profilerControl(false, path, null, profileType);
16990        } catch (RemoteException e) {
16991            throw new IllegalStateException("Process disappeared");
16992        }
16993    }
16994
16995    private void clearProfilerLocked() {
16996        if (mProfileFd != null) {
16997            try {
16998                mProfileFd.close();
16999            } catch (IOException e) {
17000            }
17001        }
17002        mProfileApp = null;
17003        mProfileProc = null;
17004        mProfileFile = null;
17005        mProfileType = 0;
17006        mAutoStopProfiler = false;
17007    }
17008
17009    public boolean profileControl(String process, int userId, boolean start,
17010            String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
17011
17012        try {
17013            synchronized (this) {
17014                // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17015                // its own permission.
17016                if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17017                        != PackageManager.PERMISSION_GRANTED) {
17018                    throw new SecurityException("Requires permission "
17019                            + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17020                }
17021
17022                if (start && fd == null) {
17023                    throw new IllegalArgumentException("null fd");
17024                }
17025
17026                ProcessRecord proc = null;
17027                if (process != null) {
17028                    proc = findProcessLocked(process, userId, "profileControl");
17029                }
17030
17031                if (start && (proc == null || proc.thread == null)) {
17032                    throw new IllegalArgumentException("Unknown process: " + process);
17033                }
17034
17035                if (start) {
17036                    stopProfilerLocked(null, null, 0);
17037                    setProfileApp(proc.info, proc.processName, path, fd, false);
17038                    mProfileProc = proc;
17039                    mProfileType = profileType;
17040                    try {
17041                        fd = fd.dup();
17042                    } catch (IOException e) {
17043                        fd = null;
17044                    }
17045                    proc.thread.profilerControl(start, path, fd, profileType);
17046                    fd = null;
17047                    mProfileFd = null;
17048                } else {
17049                    stopProfilerLocked(proc, path, profileType);
17050                    if (fd != null) {
17051                        try {
17052                            fd.close();
17053                        } catch (IOException e) {
17054                        }
17055                    }
17056                }
17057
17058                return true;
17059            }
17060        } catch (RemoteException e) {
17061            throw new IllegalStateException("Process disappeared");
17062        } finally {
17063            if (fd != null) {
17064                try {
17065                    fd.close();
17066                } catch (IOException e) {
17067                }
17068            }
17069        }
17070    }
17071
17072    private ProcessRecord findProcessLocked(String process, int userId, String callName) {
17073        userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
17074                userId, true, ALLOW_FULL_ONLY, callName, null);
17075        ProcessRecord proc = null;
17076        try {
17077            int pid = Integer.parseInt(process);
17078            synchronized (mPidsSelfLocked) {
17079                proc = mPidsSelfLocked.get(pid);
17080            }
17081        } catch (NumberFormatException e) {
17082        }
17083
17084        if (proc == null) {
17085            ArrayMap<String, SparseArray<ProcessRecord>> all
17086                    = mProcessNames.getMap();
17087            SparseArray<ProcessRecord> procs = all.get(process);
17088            if (procs != null && procs.size() > 0) {
17089                proc = procs.valueAt(0);
17090                if (userId != UserHandle.USER_ALL && proc.userId != userId) {
17091                    for (int i=1; i<procs.size(); i++) {
17092                        ProcessRecord thisProc = procs.valueAt(i);
17093                        if (thisProc.userId == userId) {
17094                            proc = thisProc;
17095                            break;
17096                        }
17097                    }
17098                }
17099            }
17100        }
17101
17102        return proc;
17103    }
17104
17105    public boolean dumpHeap(String process, int userId, boolean managed,
17106            String path, ParcelFileDescriptor fd) throws RemoteException {
17107
17108        try {
17109            synchronized (this) {
17110                // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
17111                // its own permission (same as profileControl).
17112                if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
17113                        != PackageManager.PERMISSION_GRANTED) {
17114                    throw new SecurityException("Requires permission "
17115                            + android.Manifest.permission.SET_ACTIVITY_WATCHER);
17116                }
17117
17118                if (fd == null) {
17119                    throw new IllegalArgumentException("null fd");
17120                }
17121
17122                ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
17123                if (proc == null || proc.thread == null) {
17124                    throw new IllegalArgumentException("Unknown process: " + process);
17125                }
17126
17127                boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
17128                if (!isDebuggable) {
17129                    if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
17130                        throw new SecurityException("Process not debuggable: " + proc);
17131                    }
17132                }
17133
17134                proc.thread.dumpHeap(managed, path, fd);
17135                fd = null;
17136                return true;
17137            }
17138        } catch (RemoteException e) {
17139            throw new IllegalStateException("Process disappeared");
17140        } finally {
17141            if (fd != null) {
17142                try {
17143                    fd.close();
17144                } catch (IOException e) {
17145                }
17146            }
17147        }
17148    }
17149
17150    /** In this method we try to acquire our lock to make sure that we have not deadlocked */
17151    public void monitor() {
17152        synchronized (this) { }
17153    }
17154
17155    void onCoreSettingsChange(Bundle settings) {
17156        for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
17157            ProcessRecord processRecord = mLruProcesses.get(i);
17158            try {
17159                if (processRecord.thread != null) {
17160                    processRecord.thread.setCoreSettings(settings);
17161                }
17162            } catch (RemoteException re) {
17163                /* ignore */
17164            }
17165        }
17166    }
17167
17168    // Multi-user methods
17169
17170    /**
17171     * Start user, if its not already running, but don't bring it to foreground.
17172     */
17173    @Override
17174    public boolean startUserInBackground(final int userId) {
17175        return startUser(userId, /* foreground */ false);
17176    }
17177
17178    /**
17179     * Refreshes the list of users related to the current user when either a
17180     * user switch happens or when a new related user is started in the
17181     * background.
17182     */
17183    private void updateCurrentProfileIdsLocked() {
17184        final List<UserInfo> profiles = getUserManagerLocked().getProfiles(
17185                mCurrentUserId, false /* enabledOnly */);
17186        int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
17187        for (int i = 0; i < currentProfileIds.length; i++) {
17188            currentProfileIds[i] = profiles.get(i).id;
17189        }
17190        mCurrentProfileIds = currentProfileIds;
17191
17192        synchronized (mUserProfileGroupIdsSelfLocked) {
17193            mUserProfileGroupIdsSelfLocked.clear();
17194            final List<UserInfo> users = getUserManagerLocked().getUsers(false);
17195            for (int i = 0; i < users.size(); i++) {
17196                UserInfo user = users.get(i);
17197                if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
17198                    mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
17199                }
17200            }
17201        }
17202    }
17203
17204    private Set getProfileIdsLocked(int userId) {
17205        Set userIds = new HashSet<Integer>();
17206        final List<UserInfo> profiles = getUserManagerLocked().getProfiles(
17207                userId, false /* enabledOnly */);
17208        for (UserInfo user : profiles) {
17209            userIds.add(Integer.valueOf(user.id));
17210        }
17211        return userIds;
17212    }
17213
17214    @Override
17215    public boolean switchUser(final int userId) {
17216        return startUser(userId, /* foregound */ true);
17217    }
17218
17219    private boolean startUser(final int userId, boolean foreground) {
17220        if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
17221                != PackageManager.PERMISSION_GRANTED) {
17222            String msg = "Permission Denial: switchUser() from pid="
17223                    + Binder.getCallingPid()
17224                    + ", uid=" + Binder.getCallingUid()
17225                    + " requires " + INTERACT_ACROSS_USERS_FULL;
17226            Slog.w(TAG, msg);
17227            throw new SecurityException(msg);
17228        }
17229
17230        if (DEBUG_MU) Slog.i(TAG_MU, "starting userid:" + userId + " fore:" + foreground);
17231
17232        final long ident = Binder.clearCallingIdentity();
17233        try {
17234            synchronized (this) {
17235                final int oldUserId = mCurrentUserId;
17236                if (oldUserId == userId) {
17237                    return true;
17238                }
17239
17240                mStackSupervisor.setLockTaskModeLocked(null, false);
17241
17242                final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
17243                if (userInfo == null) {
17244                    Slog.w(TAG, "No user info for user #" + userId);
17245                    return false;
17246                }
17247                if (foreground && userInfo.isManagedProfile()) {
17248                    Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
17249                    return false;
17250                }
17251
17252                if (foreground) {
17253                    mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
17254                            R.anim.screen_user_enter);
17255                }
17256
17257                boolean needStart = false;
17258
17259                // If the user we are switching to is not currently started, then
17260                // we need to start it now.
17261                if (mStartedUsers.get(userId) == null) {
17262                    mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
17263                    updateStartedUserArrayLocked();
17264                    needStart = true;
17265                }
17266
17267                final Integer userIdInt = Integer.valueOf(userId);
17268                mUserLru.remove(userIdInt);
17269                mUserLru.add(userIdInt);
17270
17271                if (foreground) {
17272                    mCurrentUserId = userId;
17273                    updateCurrentProfileIdsLocked();
17274                    mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
17275                    // Once the internal notion of the active user has switched, we lock the device
17276                    // with the option to show the user switcher on the keyguard.
17277                    mWindowManager.lockNow(null);
17278                } else {
17279                    final Integer currentUserIdInt = Integer.valueOf(mCurrentUserId);
17280                    updateCurrentProfileIdsLocked();
17281                    mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
17282                    mUserLru.remove(currentUserIdInt);
17283                    mUserLru.add(currentUserIdInt);
17284                }
17285
17286                final UserStartedState uss = mStartedUsers.get(userId);
17287
17288                // Make sure user is in the started state.  If it is currently
17289                // stopping, we need to knock that off.
17290                if (uss.mState == UserStartedState.STATE_STOPPING) {
17291                    // If we are stopping, we haven't sent ACTION_SHUTDOWN,
17292                    // so we can just fairly silently bring the user back from
17293                    // the almost-dead.
17294                    uss.mState = UserStartedState.STATE_RUNNING;
17295                    updateStartedUserArrayLocked();
17296                    needStart = true;
17297                } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
17298                    // This means ACTION_SHUTDOWN has been sent, so we will
17299                    // need to treat this as a new boot of the user.
17300                    uss.mState = UserStartedState.STATE_BOOTING;
17301                    updateStartedUserArrayLocked();
17302                    needStart = true;
17303                }
17304
17305                if (uss.mState == UserStartedState.STATE_BOOTING) {
17306                    // Booting up a new user, need to tell system services about it.
17307                    // Note that this is on the same handler as scheduling of broadcasts,
17308                    // which is important because it needs to go first.
17309                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId));
17310                }
17311
17312                if (foreground) {
17313                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
17314                            oldUserId));
17315                    mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
17316                    mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
17317                    mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
17318                            oldUserId, userId, uss));
17319                    mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
17320                            oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
17321                }
17322
17323                if (needStart) {
17324                    // Send USER_STARTED broadcast
17325                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
17326                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
17327                            | Intent.FLAG_RECEIVER_FOREGROUND);
17328                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17329                    broadcastIntentLocked(null, null, intent,
17330                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
17331                            false, false, MY_PID, Process.SYSTEM_UID, userId);
17332                }
17333
17334                if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
17335                    if (userId != UserHandle.USER_OWNER) {
17336                        // Send PRE_BOOT_COMPLETED broadcasts for this new user
17337                        final ArrayList<ComponentName> doneReceivers
17338                                = new ArrayList<ComponentName>();
17339                        deliverPreBootCompleted(null, doneReceivers, userId);
17340
17341                        Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
17342                        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
17343                        broadcastIntentLocked(null, null, intent, null,
17344                                new IIntentReceiver.Stub() {
17345                                    public void performReceive(Intent intent, int resultCode,
17346                                            String data, Bundle extras, boolean ordered,
17347                                            boolean sticky, int sendingUser) {
17348                                        userInitialized(uss, userId);
17349                                    }
17350                                }, 0, null, null, null, AppOpsManager.OP_NONE,
17351                                true, false, MY_PID, Process.SYSTEM_UID,
17352                                userId);
17353                        uss.initializing = true;
17354                    } else {
17355                        getUserManagerLocked().makeInitialized(userInfo.id);
17356                    }
17357                }
17358
17359                if (foreground) {
17360                    boolean homeInFront = mStackSupervisor.switchUserLocked(userId, uss);
17361                    if (homeInFront) {
17362                        startHomeActivityLocked(userId);
17363                    } else {
17364                        mStackSupervisor.resumeTopActivitiesLocked();
17365                    }
17366                    EventLogTags.writeAmSwitchUser(userId);
17367                    getUserManagerLocked().userForeground(userId);
17368                    sendUserSwitchBroadcastsLocked(oldUserId, userId);
17369                } else {
17370                    mStackSupervisor.startBackgroundUserLocked(userId, uss);
17371                }
17372
17373                if (needStart) {
17374                    Intent intent = new Intent(Intent.ACTION_USER_STARTING);
17375                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
17376                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17377                    broadcastIntentLocked(null, null, intent,
17378                            null, new IIntentReceiver.Stub() {
17379                                @Override
17380                                public void performReceive(Intent intent, int resultCode, String data,
17381                                        Bundle extras, boolean ordered, boolean sticky, int sendingUser)
17382                                        throws RemoteException {
17383                                }
17384                            }, 0, null, null,
17385                            INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
17386                            true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
17387                }
17388            }
17389        } finally {
17390            Binder.restoreCallingIdentity(ident);
17391        }
17392
17393        return true;
17394    }
17395
17396    void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
17397        long ident = Binder.clearCallingIdentity();
17398        try {
17399            Intent intent;
17400            if (oldUserId >= 0) {
17401                // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
17402                List<UserInfo> profiles = mUserManager.getProfiles(oldUserId, false);
17403                int count = profiles.size();
17404                for (int i = 0; i < count; i++) {
17405                    int profileUserId = profiles.get(i).id;
17406                    intent = new Intent(Intent.ACTION_USER_BACKGROUND);
17407                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
17408                            | Intent.FLAG_RECEIVER_FOREGROUND);
17409                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
17410                    broadcastIntentLocked(null, null, intent,
17411                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
17412                            false, false, MY_PID, Process.SYSTEM_UID, profileUserId);
17413                }
17414            }
17415            if (newUserId >= 0) {
17416                // Send USER_FOREGROUND broadcast to all profiles of the incoming user
17417                List<UserInfo> profiles = mUserManager.getProfiles(newUserId, false);
17418                int count = profiles.size();
17419                for (int i = 0; i < count; i++) {
17420                    int profileUserId = profiles.get(i).id;
17421                    intent = new Intent(Intent.ACTION_USER_FOREGROUND);
17422                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
17423                            | Intent.FLAG_RECEIVER_FOREGROUND);
17424                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
17425                    broadcastIntentLocked(null, null, intent,
17426                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
17427                            false, false, MY_PID, Process.SYSTEM_UID, profileUserId);
17428                }
17429                intent = new Intent(Intent.ACTION_USER_SWITCHED);
17430                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
17431                        | Intent.FLAG_RECEIVER_FOREGROUND);
17432                intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
17433                broadcastIntentLocked(null, null, intent,
17434                        null, null, 0, null, null,
17435                        android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
17436                        false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
17437            }
17438        } finally {
17439            Binder.restoreCallingIdentity(ident);
17440        }
17441    }
17442
17443    void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
17444            final int newUserId) {
17445        final int N = mUserSwitchObservers.beginBroadcast();
17446        if (N > 0) {
17447            final IRemoteCallback callback = new IRemoteCallback.Stub() {
17448                int mCount = 0;
17449                @Override
17450                public void sendResult(Bundle data) throws RemoteException {
17451                    synchronized (ActivityManagerService.this) {
17452                        if (mCurUserSwitchCallback == this) {
17453                            mCount++;
17454                            if (mCount == N) {
17455                                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
17456                            }
17457                        }
17458                    }
17459                }
17460            };
17461            synchronized (this) {
17462                uss.switching = true;
17463                mCurUserSwitchCallback = callback;
17464            }
17465            for (int i=0; i<N; i++) {
17466                try {
17467                    mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
17468                            newUserId, callback);
17469                } catch (RemoteException e) {
17470                }
17471            }
17472        } else {
17473            synchronized (this) {
17474                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
17475            }
17476        }
17477        mUserSwitchObservers.finishBroadcast();
17478    }
17479
17480    void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
17481        synchronized (this) {
17482            Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
17483            sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
17484        }
17485    }
17486
17487    void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
17488        mCurUserSwitchCallback = null;
17489        mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
17490        mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
17491                oldUserId, newUserId, uss));
17492    }
17493
17494    void userInitialized(UserStartedState uss, int newUserId) {
17495        completeSwitchAndInitalize(uss, newUserId, true, false);
17496    }
17497
17498    void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
17499        completeSwitchAndInitalize(uss, newUserId, false, true);
17500    }
17501
17502    void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
17503            boolean clearInitializing, boolean clearSwitching) {
17504        boolean unfrozen = false;
17505        synchronized (this) {
17506            if (clearInitializing) {
17507                uss.initializing = false;
17508                getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
17509            }
17510            if (clearSwitching) {
17511                uss.switching = false;
17512            }
17513            if (!uss.switching && !uss.initializing) {
17514                mWindowManager.stopFreezingScreen();
17515                unfrozen = true;
17516            }
17517        }
17518        if (unfrozen) {
17519            final int N = mUserSwitchObservers.beginBroadcast();
17520            for (int i=0; i<N; i++) {
17521                try {
17522                    mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
17523                } catch (RemoteException e) {
17524                }
17525            }
17526            mUserSwitchObservers.finishBroadcast();
17527        }
17528    }
17529
17530    void scheduleStartProfilesLocked() {
17531        if (!mHandler.hasMessages(START_PROFILES_MSG)) {
17532            mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG),
17533                    DateUtils.SECOND_IN_MILLIS);
17534        }
17535    }
17536
17537    void startProfilesLocked() {
17538        if (DEBUG_MU) Slog.i(TAG_MU, "startProfilesLocked");
17539        List<UserInfo> profiles = getUserManagerLocked().getProfiles(
17540                mCurrentUserId, false /* enabledOnly */);
17541        List<UserInfo> toStart = new ArrayList<UserInfo>(profiles.size());
17542        for (UserInfo user : profiles) {
17543            if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
17544                    && user.id != mCurrentUserId) {
17545                toStart.add(user);
17546            }
17547        }
17548        final int n = toStart.size();
17549        int i = 0;
17550        for (; i < n && i < (MAX_RUNNING_USERS - 1); ++i) {
17551            startUserInBackground(toStart.get(i).id);
17552        }
17553        if (i < n) {
17554            Slog.w(TAG_MU, "More profiles than MAX_RUNNING_USERS");
17555        }
17556    }
17557
17558    void finishUserBoot(UserStartedState uss) {
17559        synchronized (this) {
17560            if (uss.mState == UserStartedState.STATE_BOOTING
17561                    && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
17562                uss.mState = UserStartedState.STATE_RUNNING;
17563                final int userId = uss.mHandle.getIdentifier();
17564                Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
17565                intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17566                intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
17567                broadcastIntentLocked(null, null, intent,
17568                        null, null, 0, null, null,
17569                        android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
17570                        true, false, MY_PID, Process.SYSTEM_UID, userId);
17571            }
17572        }
17573    }
17574
17575    void finishUserSwitch(UserStartedState uss) {
17576        synchronized (this) {
17577            finishUserBoot(uss);
17578
17579            startProfilesLocked();
17580
17581            int num = mUserLru.size();
17582            int i = 0;
17583            while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
17584                Integer oldUserId = mUserLru.get(i);
17585                UserStartedState oldUss = mStartedUsers.get(oldUserId);
17586                if (oldUss == null) {
17587                    // Shouldn't happen, but be sane if it does.
17588                    mUserLru.remove(i);
17589                    num--;
17590                    continue;
17591                }
17592                if (oldUss.mState == UserStartedState.STATE_STOPPING
17593                        || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
17594                    // This user is already stopping, doesn't count.
17595                    num--;
17596                    i++;
17597                    continue;
17598                }
17599                if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
17600                    // Owner and current can't be stopped, but count as running.
17601                    i++;
17602                    continue;
17603                }
17604                // This is a user to be stopped.
17605                stopUserLocked(oldUserId, null);
17606                num--;
17607                i++;
17608            }
17609        }
17610    }
17611
17612    @Override
17613    public int stopUser(final int userId, final IStopUserCallback callback) {
17614        if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
17615                != PackageManager.PERMISSION_GRANTED) {
17616            String msg = "Permission Denial: switchUser() from pid="
17617                    + Binder.getCallingPid()
17618                    + ", uid=" + Binder.getCallingUid()
17619                    + " requires " + INTERACT_ACROSS_USERS_FULL;
17620            Slog.w(TAG, msg);
17621            throw new SecurityException(msg);
17622        }
17623        if (userId <= 0) {
17624            throw new IllegalArgumentException("Can't stop primary user " + userId);
17625        }
17626        synchronized (this) {
17627            return stopUserLocked(userId, callback);
17628        }
17629    }
17630
17631    private int stopUserLocked(final int userId, final IStopUserCallback callback) {
17632        if (DEBUG_MU) Slog.i(TAG_MU, "stopUserLocked userId=" + userId);
17633        if (mCurrentUserId == userId) {
17634            return ActivityManager.USER_OP_IS_CURRENT;
17635        }
17636
17637        final UserStartedState uss = mStartedUsers.get(userId);
17638        if (uss == null) {
17639            // User is not started, nothing to do...  but we do need to
17640            // callback if requested.
17641            if (callback != null) {
17642                mHandler.post(new Runnable() {
17643                    @Override
17644                    public void run() {
17645                        try {
17646                            callback.userStopped(userId);
17647                        } catch (RemoteException e) {
17648                        }
17649                    }
17650                });
17651            }
17652            return ActivityManager.USER_OP_SUCCESS;
17653        }
17654
17655        if (callback != null) {
17656            uss.mStopCallbacks.add(callback);
17657        }
17658
17659        if (uss.mState != UserStartedState.STATE_STOPPING
17660                && uss.mState != UserStartedState.STATE_SHUTDOWN) {
17661            uss.mState = UserStartedState.STATE_STOPPING;
17662            updateStartedUserArrayLocked();
17663
17664            long ident = Binder.clearCallingIdentity();
17665            try {
17666                // We are going to broadcast ACTION_USER_STOPPING and then
17667                // once that is done send a final ACTION_SHUTDOWN and then
17668                // stop the user.
17669                final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
17670                stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
17671                stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
17672                stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
17673                final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
17674                // This is the result receiver for the final shutdown broadcast.
17675                final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
17676                    @Override
17677                    public void performReceive(Intent intent, int resultCode, String data,
17678                            Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
17679                        finishUserStop(uss);
17680                    }
17681                };
17682                // This is the result receiver for the initial stopping broadcast.
17683                final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
17684                    @Override
17685                    public void performReceive(Intent intent, int resultCode, String data,
17686                            Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
17687                        // On to the next.
17688                        synchronized (ActivityManagerService.this) {
17689                            if (uss.mState != UserStartedState.STATE_STOPPING) {
17690                                // Whoops, we are being started back up.  Abort, abort!
17691                                return;
17692                            }
17693                            uss.mState = UserStartedState.STATE_SHUTDOWN;
17694                        }
17695                        mBatteryStatsService.noteEvent(
17696                                BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
17697                                Integer.toString(userId), userId);
17698                        mSystemServiceManager.stopUser(userId);
17699                        broadcastIntentLocked(null, null, shutdownIntent,
17700                                null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
17701                                true, false, MY_PID, Process.SYSTEM_UID, userId);
17702                    }
17703                };
17704                // Kick things off.
17705                broadcastIntentLocked(null, null, stoppingIntent,
17706                        null, stoppingReceiver, 0, null, null,
17707                        INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
17708                        true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
17709            } finally {
17710                Binder.restoreCallingIdentity(ident);
17711            }
17712        }
17713
17714        return ActivityManager.USER_OP_SUCCESS;
17715    }
17716
17717    void finishUserStop(UserStartedState uss) {
17718        final int userId = uss.mHandle.getIdentifier();
17719        boolean stopped;
17720        ArrayList<IStopUserCallback> callbacks;
17721        synchronized (this) {
17722            callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
17723            if (mStartedUsers.get(userId) != uss) {
17724                stopped = false;
17725            } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
17726                stopped = false;
17727            } else {
17728                stopped = true;
17729                // User can no longer run.
17730                mStartedUsers.remove(userId);
17731                mUserLru.remove(Integer.valueOf(userId));
17732                updateStartedUserArrayLocked();
17733
17734                // Clean up all state and processes associated with the user.
17735                // Kill all the processes for the user.
17736                forceStopUserLocked(userId, "finish user");
17737            }
17738
17739            // Explicitly remove the old information in mRecentTasks.
17740            removeRecentTasksForUserLocked(userId);
17741        }
17742
17743        for (int i=0; i<callbacks.size(); i++) {
17744            try {
17745                if (stopped) callbacks.get(i).userStopped(userId);
17746                else callbacks.get(i).userStopAborted(userId);
17747            } catch (RemoteException e) {
17748            }
17749        }
17750
17751        if (stopped) {
17752            mSystemServiceManager.cleanupUser(userId);
17753            synchronized (this) {
17754                mStackSupervisor.removeUserLocked(userId);
17755            }
17756        }
17757    }
17758
17759    @Override
17760    public UserInfo getCurrentUser() {
17761        if ((checkCallingPermission(INTERACT_ACROSS_USERS)
17762                != PackageManager.PERMISSION_GRANTED) && (
17763                checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
17764                != PackageManager.PERMISSION_GRANTED)) {
17765            String msg = "Permission Denial: getCurrentUser() from pid="
17766                    + Binder.getCallingPid()
17767                    + ", uid=" + Binder.getCallingUid()
17768                    + " requires " + INTERACT_ACROSS_USERS;
17769            Slog.w(TAG, msg);
17770            throw new SecurityException(msg);
17771        }
17772        synchronized (this) {
17773            return getUserManagerLocked().getUserInfo(mCurrentUserId);
17774        }
17775    }
17776
17777    int getCurrentUserIdLocked() {
17778        return mCurrentUserId;
17779    }
17780
17781    @Override
17782    public boolean isUserRunning(int userId, boolean orStopped) {
17783        if (checkCallingPermission(INTERACT_ACROSS_USERS)
17784                != PackageManager.PERMISSION_GRANTED) {
17785            String msg = "Permission Denial: isUserRunning() from pid="
17786                    + Binder.getCallingPid()
17787                    + ", uid=" + Binder.getCallingUid()
17788                    + " requires " + INTERACT_ACROSS_USERS;
17789            Slog.w(TAG, msg);
17790            throw new SecurityException(msg);
17791        }
17792        synchronized (this) {
17793            return isUserRunningLocked(userId, orStopped);
17794        }
17795    }
17796
17797    boolean isUserRunningLocked(int userId, boolean orStopped) {
17798        UserStartedState state = mStartedUsers.get(userId);
17799        if (state == null) {
17800            return false;
17801        }
17802        if (orStopped) {
17803            return true;
17804        }
17805        return state.mState != UserStartedState.STATE_STOPPING
17806                && state.mState != UserStartedState.STATE_SHUTDOWN;
17807    }
17808
17809    @Override
17810    public int[] getRunningUserIds() {
17811        if (checkCallingPermission(INTERACT_ACROSS_USERS)
17812                != PackageManager.PERMISSION_GRANTED) {
17813            String msg = "Permission Denial: isUserRunning() from pid="
17814                    + Binder.getCallingPid()
17815                    + ", uid=" + Binder.getCallingUid()
17816                    + " requires " + INTERACT_ACROSS_USERS;
17817            Slog.w(TAG, msg);
17818            throw new SecurityException(msg);
17819        }
17820        synchronized (this) {
17821            return mStartedUserArray;
17822        }
17823    }
17824
17825    private void updateStartedUserArrayLocked() {
17826        int num = 0;
17827        for (int i=0; i<mStartedUsers.size();  i++) {
17828            UserStartedState uss = mStartedUsers.valueAt(i);
17829            // This list does not include stopping users.
17830            if (uss.mState != UserStartedState.STATE_STOPPING
17831                    && uss.mState != UserStartedState.STATE_SHUTDOWN) {
17832                num++;
17833            }
17834        }
17835        mStartedUserArray = new int[num];
17836        num = 0;
17837        for (int i=0; i<mStartedUsers.size();  i++) {
17838            UserStartedState uss = mStartedUsers.valueAt(i);
17839            if (uss.mState != UserStartedState.STATE_STOPPING
17840                    && uss.mState != UserStartedState.STATE_SHUTDOWN) {
17841                mStartedUserArray[num] = mStartedUsers.keyAt(i);
17842                num++;
17843            }
17844        }
17845    }
17846
17847    @Override
17848    public void registerUserSwitchObserver(IUserSwitchObserver observer) {
17849        if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
17850                != PackageManager.PERMISSION_GRANTED) {
17851            String msg = "Permission Denial: registerUserSwitchObserver() from pid="
17852                    + Binder.getCallingPid()
17853                    + ", uid=" + Binder.getCallingUid()
17854                    + " requires " + INTERACT_ACROSS_USERS_FULL;
17855            Slog.w(TAG, msg);
17856            throw new SecurityException(msg);
17857        }
17858
17859        mUserSwitchObservers.register(observer);
17860    }
17861
17862    @Override
17863    public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
17864        mUserSwitchObservers.unregister(observer);
17865    }
17866
17867    private boolean userExists(int userId) {
17868        if (userId == 0) {
17869            return true;
17870        }
17871        UserManagerService ums = getUserManagerLocked();
17872        return ums != null ? (ums.getUserInfo(userId) != null) : false;
17873    }
17874
17875    int[] getUsersLocked() {
17876        UserManagerService ums = getUserManagerLocked();
17877        return ums != null ? ums.getUserIds() : new int[] { 0 };
17878    }
17879
17880    UserManagerService getUserManagerLocked() {
17881        if (mUserManager == null) {
17882            IBinder b = ServiceManager.getService(Context.USER_SERVICE);
17883            mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
17884        }
17885        return mUserManager;
17886    }
17887
17888    private int applyUserId(int uid, int userId) {
17889        return UserHandle.getUid(userId, uid);
17890    }
17891
17892    ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
17893        if (info == null) return null;
17894        ApplicationInfo newInfo = new ApplicationInfo(info);
17895        newInfo.uid = applyUserId(info.uid, userId);
17896        newInfo.dataDir = USER_DATA_DIR + userId + "/"
17897                + info.packageName;
17898        return newInfo;
17899    }
17900
17901    ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
17902        if (aInfo == null
17903                || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
17904            return aInfo;
17905        }
17906
17907        ActivityInfo info = new ActivityInfo(aInfo);
17908        info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
17909        return info;
17910    }
17911
17912    private final class LocalService extends ActivityManagerInternal {
17913        @Override
17914        public void goingToSleep() {
17915            ActivityManagerService.this.goingToSleep();
17916        }
17917
17918        @Override
17919        public void wakingUp() {
17920            ActivityManagerService.this.wakingUp();
17921        }
17922
17923        @Override
17924        public int startIsolatedProcess(String entryPoint, String[] entryPointArgs,
17925                String processName, String abiOverride, int uid, Runnable crashHandler) {
17926            return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs,
17927                    processName, abiOverride, uid, crashHandler);
17928        }
17929    }
17930
17931    /**
17932     * An implementation of IAppTask, that allows an app to manage its own tasks via
17933     * {@link android.app.ActivityManager.AppTask}.  We keep track of the callingUid to ensure that
17934     * only the process that calls getAppTasks() can call the AppTask methods.
17935     */
17936    class AppTaskImpl extends IAppTask.Stub {
17937        private int mTaskId;
17938        private int mCallingUid;
17939
17940        public AppTaskImpl(int taskId, int callingUid) {
17941            mTaskId = taskId;
17942            mCallingUid = callingUid;
17943        }
17944
17945        @Override
17946        public void finishAndRemoveTask() {
17947            // Ensure that we are called from the same process that created this AppTask
17948            if (mCallingUid != Binder.getCallingUid()) {
17949                Slog.w(TAG, "finishAndRemoveTask: caller " + mCallingUid
17950                        + " does not match caller of getAppTasks(): " + Binder.getCallingUid());
17951                return;
17952            }
17953
17954            synchronized (ActivityManagerService.this) {
17955                long origId = Binder.clearCallingIdentity();
17956                try {
17957                    TaskRecord tr = recentTaskForIdLocked(mTaskId);
17958                    if (tr != null) {
17959                        // Only kill the process if we are not a new document
17960                        int flags = tr.getBaseIntent().getFlags();
17961                        boolean isDocument = (flags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) ==
17962                                Intent.FLAG_ACTIVITY_NEW_DOCUMENT;
17963                        removeTaskByIdLocked(mTaskId,
17964                                !isDocument ? ActivityManager.REMOVE_TASK_KILL_PROCESS : 0);
17965                    }
17966                } finally {
17967                    Binder.restoreCallingIdentity(origId);
17968                }
17969            }
17970        }
17971
17972        @Override
17973        public ActivityManager.RecentTaskInfo getTaskInfo() {
17974            // Ensure that we are called from the same process that created this AppTask
17975            if (mCallingUid != Binder.getCallingUid()) {
17976                Slog.w(TAG, "finishAndRemoveTask: caller " + mCallingUid
17977                        + " does not match caller of getAppTasks(): " + Binder.getCallingUid());
17978                return null;
17979            }
17980
17981            synchronized (ActivityManagerService.this) {
17982                long origId = Binder.clearCallingIdentity();
17983                try {
17984                    TaskRecord tr = recentTaskForIdLocked(mTaskId);
17985                    if (tr != null) {
17986                        return createRecentTaskInfoFromTaskRecord(tr);
17987                    }
17988                } finally {
17989                    Binder.restoreCallingIdentity(origId);
17990                }
17991                return null;
17992            }
17993        }
17994    }
17995}
17996